diff --git "a/4380.jsonl" "b/4380.jsonl"
new file mode 100644--- /dev/null
+++ "b/4380.jsonl"
@@ -0,0 +1,699 @@
+{"seq_id":"3491002","text":"import pandas as pd\nimport re\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom lmf.dbv2 import db_write,db_command,db_query\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport sys\nimport time\n\nimport json\n\nfrom zhulong.util.etl import add_info,est_meta,est_html,est_tbs\n\n\n_name_=\"huzhou\"\n\n\n\n# __conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"hunan\",\"changsha\"]\n\n\n# url=\"https://ggzy.changsha.gov.cn/spweb/CS/TradeCenter/tradeList.do?Deal_Type=Deal_Type2\"\n# driver=webdriver.Chrome()\n# driver.minimize_window()\n# driver.get(url)\n\n\n\ndef f1(driver, num):\n\n locator = (By.XPATH, \"(//a[@class='WebList_sub'])[1]\")\n val = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n\n locator = (By.XPATH, \"//td[@class='huifont']\")\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n cnum = re.findall(r'(\\d+)/', str)[0]\n\n url = driver.current_url\n if num != int(cnum):\n if num == 1:\n url = re.sub(\"Paging=[0-9]*\", \"Paging=1\", url)\n else:\n s = \"Paging=%d\" % (num) if num > 1 else \"Paging=1\"\n url = re.sub(\"Paging=[0-9]*\", s, url)\n # print(cnum)\n driver.get(url)\n try:\n locator = (By.XPATH, \"(//a[@class='WebList_sub'])[1][string()!='%s']\" % val)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n except:\n driver.refresh()\n locator = (By.XPATH, \"(//a[@class='WebList_sub'])[1][string()!='%s']\" % val)\n WebDriverWait(driver, 3).until(EC.presence_of_element_located(locator))\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n table = soup.find(\"table\", width='98%')\n\n trs = table.find_all(\"tr\", height=\"24\")\n data = []\n for tr in trs[1:]:\n a = tr.find(\"a\")\n try:\n link = a[\"href\"]\n except:\n link = ''\n td = tr.find(\"td\", width=\"80\").text\n tmp = [a[\"title\"].strip(), td.strip(), \"http://ggzy.huzhou.gov.cn\" + link.strip()]\n data.append(tmp)\n\n df = pd.DataFrame(data)\n df['info'] = None\n return df\n\n\ndef f2(driver):\n locator = (By.XPATH, \"(//a[@class='WebList_sub'])[1]\")\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n locator = (By.XPATH, '//td[@class=\"huifont\"]')\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n num = re.findall(r'/(\\d+)', str)[0]\n\n driver.quit()\n return int(num)\n\n\n\ndef f3(driver, url):\n driver.get(url)\n\n locator = (By.CLASS_NAME, \"bg\")\n\n WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located(locator))\n\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i = 0\n while before != after:\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i += 1\n if i > 5: break\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n div = soup.find('td', height='500')\n # div=div.find_all('div',class_='ewb-article')[0]\n\n return div\n\n\ndata = [\n [\"gcjs_jianshe_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001001/029001001001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_jianshe_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001001/029001001002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_jiaotong_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001002/029001002001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_jiaotong_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001002/029001002002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n\n [\"gcjs_shuili_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001003/029001003001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_shuli_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001003/029001003002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_xianer_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001004/029001004001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n\n [\"zfcg_jizhong_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004001/029004001001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_jizhong_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004001/029004001002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_jizhong_yucai_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004001/029004001003/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n\n [\"zfcg_fensan_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004002/029004002001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_fensan_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004002/029004002002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n [\"zfcg_fensan_yucai_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004002/029004002003/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_xieyi_cheliangweixiu_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004004/029004004001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_jizhong_caigoumulu_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029004/029004005/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"ylcg_jizhong_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029005/029005001/029005001001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"ylcg_jizhong_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029005/029005001/029005001002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"ylcg_fensan_zhaobiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029005/029005002/029005002001/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"ylcg_fensan_zhongbiao_gg\",\n \"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029005/029005002/029005002002/?Paging=1\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n]\n\n\ndef work(conp,**args):\n est_meta(conp,data=data,diqu=\"浙江省湖州市\",**args)\n est_html(conp,f=f3,**args)\n\n\nif __name__=='__main__':\n work(conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"zhejiang\",\"huzhou\"])\n\n\n # driver=webdriver.Chrome()\n # url=\"http://ggzy.huzhou.gov.cn/HZfront/jyxx_HuZhou/029001/029001001/029001001001/?Paging=1\"\n # driver.get(url)\n # df = f2(driver)\n # print(df)\n # for i in range(1, 6):\n # df=f1(driver, i)\n # print(df)\n","sub_path":"zl_spider/zhejiang/huzhou.py","file_name":"huzhou.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"628420547","text":"from collections import defaultdict\nfrom more_itertools import grouper\nfrom pathlib import Path\n\n\ndef parse_data():\n with open(Path(__file__).stem + \".txt\") as fp:\n data = fp.read()\n return data\n\n\ndef get_direction(direction):\n x = 0\n y = 0\n if direction == \"^\":\n y += 1\n elif direction == \"v\":\n y -= 1\n elif direction == \"<\":\n x -= 1\n elif direction == \">\":\n x += 1\n return x, y\n\n\ndef main_a():\n data = parse_data()\n x = 0\n y = 0\n chart = defaultdict(int)\n chart[(x, y)] += 1\n for direction in data:\n direction = get_direction(direction)\n x += direction[0]\n y += direction[1]\n chart[(x, y)] += 1\n print(len(chart.keys()))\n\n\ndef main_b():\n data = parse_data()\n santa = [0, 0]\n robo = [0, 0]\n chart = defaultdict(int)\n chart[tuple(santa)] += 2\n for s, r in grouper(data, 2):\n direction = get_direction(s)\n santa[0] += direction[0]\n santa[1] += direction[1]\n chart[tuple(santa)] += 1\n direction = get_direction(r)\n robo[0] += direction[0]\n robo[1] += direction[1]\n chart[tuple(robo)] += 1\n print(len(chart.keys()))\n\n\nif __name__ == \"__main__\":\n # main_a()\n main_b()\n","sub_path":"2015/a03.py","file_name":"a03.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"1897498","text":"# coding=utf-8\n\"\"\"\nInaSAFE Disaster risk assessment tool developed by AusAid - **Help Class.**\n\nContact : ole.moller.nielsen@gmail.com\n\n.. note:: 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\"\"\"\n\n__author__ = 'tim@linfiniti.com'\n__revision__ = '8e90270d76bc3e85f0084bd480f8e977a33cb812'\n__date__ = '20/01/2011'\n__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '\n 'Disaster Reduction')\n\nimport os\nimport logging\n\n#noinspection PyPackageRequirements\nfrom PyQt4 import (QtGui, QtCore)\n\nfrom safe_qgis.exceptions import HelpFileMissingError\n\nLOGGER = logging.getLogger('InaSAFE')\n\n\ndef show_context_help(context=None):\n \"\"\"Show help using the user's web browser.\n\n :type context: str\n :param context: Page name (without path) of a document in the\n user-docs subdirectory. e.g. 'keywords'\n \"\"\"\n\n try:\n _show_local_help(context)\n except HelpFileMissingError:\n _show_online_help(context)\n\n\ndef _show_local_help(context=None):\n \"\"\"Show help using the user's web browser - uses local help file.\n\n :type context: str\n :param context: Page name (without path) of a document in the\n user-docs subdirectory. e.g. 'keywords'\n\n :raises: HelpFileMissingError\n \"\"\"\n\n # First we try using local filesystem\n\n base_url = os.path.abspath(os.path.join(\n __file__, os.path.pardir, os.path.pardir, os.path.pardir, 'docs'\n ))\n\n # set default value for locale\n locale = 'en'\n if 'LANG' in os.environ:\n locale = os.environ['LANG']\n\n if locale not in ['id', 'en']:\n locale = 'en'\n\n base_url = os.path.join(base_url, locale)\n\n if context is not None:\n base_url = os.path.join(base_url, context + '.html')\n LOGGER.debug(os.path.isfile(base_url))\n else:\n base_url = os.path.join(base_url, 'index.html')\n\n if not os.path.exists(base_url):\n raise HelpFileMissingError('Help file not found: %s' % base_url)\n\n #noinspection PyTypeChecker,PyArgumentList\n url = QtCore.QUrl.fromLocalFile(base_url)\n # noinspection PyCallByClass,PyTypeChecker,PyArgumentList\n QtGui.QDesktopServices.openUrl(url)\n\n\ndef _show_online_help(context=None):\n \"\"\"Show help using the user's web browser - uses inasafe web site.\n\n :type context: str\n :param context: Page name (without path) of a document in the\n user-docs subdirectory. e.g. 'keywords'\n \"\"\"\n\n # First we try using local filesystem\n\n base_url = 'http://inasafe.org/'\n\n # set default value for locale\n locale = 'en'\n if 'LANG' in os.environ:\n locale = os.environ['LANG']\n\n if locale not in ['id', 'en']:\n locale = 'en'\n\n base_url += locale\n base_url += '/user-docs/'\n\n if context is not None:\n base_url += context + '.html'\n LOGGER.debug(os.path.isfile(base_url))\n else:\n base_url += 'index.html'\n url = QtCore.QUrl(base_url)\n # noinspection PyCallByClass,PyTypeChecker,PyArgumentList\n QtGui.QDesktopServices.openUrl(url)\n","sub_path":"safe_qgis/utilities/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"190706087","text":"\"\"\"\nhttps://docs.python.org/3/library/multiprocessing.html#multiprocessing.managers.Namespace\n\"\"\"\nimport multiprocessing\nfrom multiprocessing.managers import BaseManager\nimport pprint\n\n\ndef worker(d, key, value):\n d[key] = value\n\n\n# Shared Namespace\ndef producer(ns, event):\n # It is important to know that updates to the contents of mutable values\n # in the namespace are not propagated automatically.\n # when using a proxy for a namespace object,\n # an attribute beginning with '_' will be an attribute of the proxy and not an attribute of the referent:\n ns.value = 'This is the value'\n event.set()\n\n\ndef consumer(ns, event):\n try:\n print('Before event: {}'.format(ns.value))\n except Exception as err:\n print('Before event, error:', str(err))\n event.wait()\n print('After event:', ns.value)\n\n\nclass MathsClass:\n def add(self, x, y):\n return x + y\n def mul(self, x, y):\n return x * y\n\nclass MyManager(BaseManager):\n pass\n\nMyManager.register('Maths', MathsClass)\n\n\nif __name__ == '__main__':\n mgr = multiprocessing.Manager()\n d = mgr.dict()\n jobs = [\n multiprocessing.Process(\n target=worker,\n args=(d, i, i ** 2),\n )\n for i in range(10)\n ]\n for j in jobs:\n j.start()\n for j in jobs:\n j.join()\n print('Results:', d)\n\n namespace = mgr.Namespace()\n event = multiprocessing.Event()\n p = multiprocessing.Process(\n target=producer,\n args=(namespace, event),\n )\n c = multiprocessing.Process(\n target=consumer,\n args=(namespace, event),\n )\n\n c.start()\n p.start()\n\n c.join()\n p.join()\n\n print('Custom manager:')\n with MyManager() as manager:\n maths = manager.Maths()\n print(maths.add(4, 3))\n print(maths.mul(7, 8))","sub_path":"cheatsheet/multiprocess/manager_shared_state.py","file_name":"manager_shared_state.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"195159084","text":"#!/usr/bin/env python\nimport codefast as cf\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nfrom dofast.toolkits.telegram import messalert\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.layers import (GRU, LSTM, Bidirectional, Dense, Dropout,\n Embedding, GlobalMaxPool1D, Input)\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nimport premium as pm\nfrom premium.postprocess import get_binary_prediction\nfrom premium.preprocess import label_encode, pad_sequences, tokenize\n\ntf.compat.v1.disable_eager_execution()\n\n\nclass OverFat:\n def __init__(self,\n max_feature: int = 50000,\n max_len: int = 300,\n embed_size: int = 200,\n X=None,\n y=None) -> None:\n self.max_feature = max_feature\n self.max_len = max_len\n self.embed_size = embed_size\n self.X = X\n self.y = y\n self.sequence = None\n self.tokenizer = None\n self.word_index = None\n\n def tokenize_sequence(self):\n self.X, tokenizer = tokenize(self.X, max_feature=self.max_feature)\n self.sequence = sequence.pad_sequences(self.X, maxlen=self.max_len)\n self.tokenizer = tokenizer\n self.word_index = tokenizer.word_index\n cf.info('{} of unique tokens found'.format(len(self.word_index)))\n return self.tokenizer\n\n def embed(self, pretrained_vector: str = 'glove-wiki-gigaword-50'):\n self.embeddings_index = pm.word2vec.load(pretrained_vector)\n cf.info('load {} completes'.format(pretrained_vector))\n\n all_embeddings = np.stack(list(self.embeddings_index.values()))\n emb_mean, emb_std = all_embeddings.mean(), all_embeddings.std()\n assert self.word_index is not None, 'Tokenize and sequence text first!'\n\n self.max_feature = min(self.max_feature, len(self.word_index))\n self.embedding_matrix = np.random.normal(\n emb_mean, emb_std, (self.max_feature, self.embed_size))\n\n hit, missed = 0, 0\n for word, i in self.word_index.items():\n if i < self.max_feature:\n embedding_vector = self.embeddings_index.get(word)\n if embedding_vector is not None:\n self.embedding_matrix[i] = embedding_vector\n hit += 1\n else:\n missed += 1\n cf.info(\n 'embed completes, size of embedding matrix {}. Missed {}, hit {}'.\n format(self.embedding_matrix.shape, missed, hit))\n\n return self.embedding_matrix\n\n def build_model(self):\n inp = Input(shape=(self.max_len, ))\n x = Embedding(self.max_feature,\n self.embed_size,\n weights=[self.embedding_matrix])(inp)\n # x = Embedding(max_feature, embed_size)(inp)\n x = Bidirectional(GRU(80, return_sequences=True))(x)\n x = GlobalMaxPool1D()(x)\n x = Dropout(0.3)(x)\n x = Dense(50, activation=\"relu\")(x)\n x = Dropout(0.3)(x)\n opt = Dense(6, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=opt)\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n model.summary()\n self.model = model\n cf.info('model was built.')\n return model\n\n def fine_tune_model(self, batch_size: int = 1024, epochs: int = 20):\n file_path = f\"/tmp/best_weights_{cf.uuid()}.hdf5\"\n checkpoint = ModelCheckpoint(file_path,\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n mode='min')\n\n early = EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=6)\n\n callbacks_list = [checkpoint, early] #early\n self.model.fit(self.sequence,\n self.y,\n batch_size=batch_size,\n epochs=epochs,\n validation_split=0.15,\n callbacks=callbacks_list,\n use_multiprocessing=True)\n\n self.model.load_weights(file_path)\n return self.model\n\n def predict(self, X_te, cats):\n y_test = self.model.predict(X_te,\n batch_size=1024,\n verbose=1,\n use_multiprocessing=True)\n sample_submission = pd.read_csv(\"/tmp/sample_submission.csv\")\n sample_submission[cats] = y_test\n export_file = f\"tmp/pred_toxic_{cf.uuid()}.csv\"\n cf.info('Export to file', export_file)\n sample_submission.to_csv(export_file, index=False)\n messalert('Toxic Done')\n\n\nclass UnderFat:\n def __init__(self, train_file, test_file):\n train = pd.read_csv(train_file)\n test = pd.read_csv(test_file)\n text_train = train[\"comment_text\"].fillna(\"CVxTz\").values\n cats = [\n \"toxic\", \"severe_toxic\", \"obscene\", \"threat\", \"insult\",\n \"identity_hate\"\n ]\n y = train[cats].values\n\n max_feature = 10000\n max_len = 50\n embed_size = 50\n fat = OverFat(max_feature, max_len, embed_size, text_train, y)\n fat.y = y\n fat.tokenize_sequence()\n fat.embed('glove-wiki-gigaword-50')\n fat.build_model()\n fat.fine_tune_model()\n\n\ndef build_bilstm(maxlen: int, max_feature: int, embed_size: int):\n inp = Input(shape=(maxlen, ))\n layer = Embedding(max_feature, embed_size)(inp)\n layer = Bidirectional(LSTM(50, return_sequences=True))(layer)\n layer = GlobalMaxPool1D()(layer)\n layer = Dropout(0.1)(layer)\n layer = Dense(50, activation=\"relu\")(layer)\n layer = Dropout(0.1)(layer)\n opt = Dense(6, activation=\"sigmoid\")(layer)\n model = Model(inputs=inp, outputs=opt)\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n model.summary()\n\n return model\n\n\ndef optimal_batch_size(sequence_size: int) -> int:\n import math\n base = int(math.log(sequence_size + 1, 10))\n batch_size = 1 << (base + 2)\n cf.info('Batch size is set to ', batch_size)\n return batch_size\n\n\nclass NNTouchStone:\n def __init__(self,\n X,\n y,\n validation_split: float = 0.15,\n max_len: int = -1):\n self.X = X\n self.y = y\n self.X_train = None\n self.y_train = None\n self.validation_split = validation_split\n self.max_len = max_len\n self.epochs = 63\n self.save_model = False\n\n def preprocess(self):\n self.X_train, self.X_test, self.y_train, self.y_test, _i, _j = train_test_split(\n self.X,\n self.y,\n np.arange(len(self.X)),\n random_state=63,\n test_size=self.validation_split)\n\n self.indices = {'train': _i, 'val': _j}\n\n cf.info('start tokenizing')\n self.X_train, tokenizer = tokenize(self.X_train)\n self.X_test = tokenizer.texts_to_sequences(self.X_test)\n self.tokenizer = tokenizer\n self.word_index = tokenizer.word_index\n\n if self.max_len < 0:\n self.max_len = int(np.percentile(list(map(len, self.X)), 95))\n cf.info('MAX_LENGTH_SEQUENCE set to {}'.format(self.max_len))\n assert self.max_len >= 2, 'max length is less than 2, check your data.'\n\n self.X_train = pad_sequences(self.X_train, maxlen=self.max_len, padding=\"pre\")\n self.X_test = pad_sequences(self.X_test, maxlen=self.max_len, padding=\"pre\")\n\n self.input_dim = len(tokenizer.word_index) + 1\n\n def embed(self, pretrained_vector: str = ''):\n if pretrained_vector:\n self.embeddings_index = pm.word2vec.load(pretrained_vector)\n cf.info('load {} completes'.format(pretrained_vector))\n\n all_embeddings = np.stack(list(self.embeddings_index.values()))\n emb_mean, emb_std = all_embeddings.mean(), all_embeddings.std()\n assert self.word_index is not None, 'Tokenize and sequence text first!'\n\n self.max_feature = min(self.max_feature, len(self.word_index))\n self.embedding_matrix = np.random.normal(\n emb_mean, emb_std, (self.max_feature, self.embed_size))\n\n missed, hit = 0, 0\n for word, i in self.word_index.items():\n if i < self.max_feature:\n embedding_vector = self.embeddings_index.get(word)\n if embedding_vector is not None:\n self.embedding_matrix[i] = embedding_vector\n hit += 1\n else:\n missed += 1\n\n cf.info(\n 'embed completes, size of embedding matrix {}. Missed {}, hit {}'.\n format(self.embedding_matrix.shape, missed, hit))\n\n return self.embedding_matrix\n\n def build_model(self):\n cf.info('Building model...')\n M = Sequential()\n M.add(Embedding(self.input_dim, 100, input_length=self.max_len))\n\n # M.add(Bidirectional(LSTM(100)))\n M.add(Bidirectional(GRU(100)))\n M.add(Dropout(0.4))\n\n M.add(Dense(60, activation=\"relu\"))\n M.add(Dropout(0.4))\n M.add(Dense(1, activation=\"sigmoid\"))\n\n M.compile(loss=\"binary_crossentropy\",\n optimizer=\"adam\",\n metrics=[\"accuracy\"])\n M.summary()\n self.model = M\n return M\n\n def train(self):\n cf.info('training model')\n weight_path = f'/tmp/best_weights_{cf.uuid()}.h5'\n es = EarlyStopping(monitor='val_loss',\n mode='min',\n verbose=1,\n patience=5)\n checkpoint = ModelCheckpoint(weight_path,\n monitor='val_loss',\n save_weights_only=True,\n verbose=1,\n save_best_only=True,\n period=1)\n fit_params = {\n 'batch_size': optimal_batch_size(len(self.X)),\n 'validation_split': 0.1,\n 'epochs': self.epochs,\n 'callbacks': [es, checkpoint]\n }\n self.model.fit(self.X_train, self.y_train, **fit_params)\n self.model.load_weights(weight_path)\n if self.save_model:\n self.model.save('/tmp/saved_model.h5')\n\n def predict(self):\n y_pred = get_binary_prediction(self.model.predict(self.X_test))\n pm.libra.metrics(self.y_test, y_pred)\n return self.y_test, y_pred\n\n def pipeline(self):\n self.preprocess()\n self.build_model()\n self.train()\n return self.predict()\n","sub_path":"premium/models/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":11124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"570441943","text":"import socket\nimport time\n\nwith socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n\n s.settimeout(1)\n\n start_t = time.time()\n max_du = 0;\n min_du = 1e6;\n every_t = 0\n \n try:\n while True:\n\n s.sendto(b'hellohello',(\"192.168.25.238\", 5005))\n try:\n data, addr = s.recvfrom(4096)\n except socket.timeout:\n print(\"caught a timeout at first echo\")\n\n #print(repr(data))\n\n try:\n data, addr = s.recvfrom(4096)\n except socket.timeout:\n print(\"caught a timeout at second echo\")\n\n #print(int.from_bytes(data, 'little'))\n\n if every_t > 0:\n if time.time() - every_t > max_du:\n max_du = time.time() - every_t\n\n if time.time() - every_t < min_du:\n min_du = time.time() - every_t\n\n if time.time() - start_t > 1:\n print(\"du: \", time.time() - every_t, \", max_du: \", max_du, \", min_du: \", min_du)\n start_t = time.time()\n\n\n every_t = time.time()\n\n time.sleep(0.001)\n\n except KeyboardInterrupt:\n exit()\n","sub_path":"Scripts/socket_udp_send2.py","file_name":"socket_udp_send2.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"260557016","text":"\n\nimport turtle\nimport math\nimport random\n\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600 # setting up the size of the screen\n\nwindow = turtle.Screen() # creating the window\nwindow.setup(SCREEN_WIDTH + 220, SCREEN_HEIGHT + 20)\nwindow.title('Space Arena') # adding the title\nwindow.bgcolor('black') # adding the backgroundcolor\nwindow.tracer(0)\n\npen = turtle.Turtle()\npen.speed(0)\npen.shape('square')\npen.color('white')\npen.penup()\npen.hideturtle() # we won't see the drawed lines \n\nclass Game():\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.level = 1\n \n def start_level(self):\n sprites.clear() # clears all the sprites from the list\n\n # add the player \n sprites.append(player)\n\n # add missile\n sprites.append(missile)\n\n # add enemy per level\n for _ in range(self.level):\n x = random.randint(-self.width/2, self.width/2)\n y = random.randint(-self.height/2, self.height/2)\n dx = random.randint(-2, 2)\n dy = random.randint(-2, -2)\n sprites.append(Enemy(x, y, 'square', 'red'))\n sprites[-1].dx = dx # will give us the the last sprite what was added\n sprites[-1].dy = dy\n\n # add powerup per level\n for _ in range(self.level):\n x = random.randint(-self.width/2, self.width/2)\n y = random.randint(-self.height/2, self.height/2)\n dx = random.randint(-2, 2)\n dy = random.randint(-2, -2)\n sprites.append(Powerup(x, y, 'circle', 'blue'))\n sprites[-1].dx = dx # will give us the the last sprite what was added\n sprites[-1].dy = dy\n\n\n\n\n def render_border(self, pen, x_offset, y_offset):\n pen.color('white')\n pen.width(3)\n pen.penup()\n\n left = -self.width / 2 - x_offset# if the screen width is 800 like in our case its -400 left and 400 by the right side\n right = self.width / 2 - x_offset\n top = self.height / 2 - y_offset\n bottom = -self.height / 2 - y_offset\n\n pen.goto(left, top) # starting left top\n pen.pendown() # function needed so we can actually draw the border\n pen.goto(right, top)\n pen.goto(right, bottom)\n pen.goto(left, bottom)\n pen.goto(left, top)\n pen.penup()\n\nclass Sprite(): # the class for objects like player, enemy etc.\n # the constructor\n def __init__(self, x, y, shape, color):\n self.x = x\n self.y = y\n self.shape = shape\n self.color = color\n self.dx = 0 # horizontal speed (if dx is positiv the object moves to the right, if negative left)\n self.dy = 0 # vertical speed (if dy is positiv the object moves up, if negative down)\n self.heading = 0\n self.da = 0\n self.thrust = 0.0\n self.acceleration = 0.02\n self.health = 100\n self.max_health = 100\n self.width = 20\n self.height = 20\n self.state = 'active'\n self.radar = 200\n\n\n def is_collision(self, other):\n if self.x < other.x + other.width and\\\n self.x + self.width > other.x and\\\n self.y < other.y + other.height and\\\n self.y + self.height > other.y:\n return True\n else:\n return False\n \n def bounce(self, other):\n temp_dx = self.dx\n temp_dy = self.dy\n\n self.dx = other.dx\n self.dy = other.dy\n\n other.dx = temp_dx\n other.dy = temp_dy\n\n \n def update(self):\n self.heading += self.da # the heading is gonna change by the delta of the angle\n self.heading %= 360\n\n self.dx += math.cos(math.radians(self.heading)) * self.thrust\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\n \n self.x += self.dx\n self.y += self.dy\n\n self.border_check()\n \n def border_check(self):\n if self.x > game.width / 2 - 10:\n self.x = game.width /2 - 10\n self.dx *= -1 # the sprite bounces off the right wall\n \n elif self.x < -game.width / 2 + 10:\n self.x = -game.width /2 + 10\n self.dx *= -1 # the sprite bounces off the left wall \n\n if self.y > game.height / 2 - 10:\n self.y = game.height /2 - 10\n self.dy *= -1 # the sprite bounces off the top wall\n \n elif self.y < -game.height / 2 + 10:\n self.y = -game.height /2 + 10\n self.dy *= -1 # the sprite bounces off the bottom wall \n\n\n def render(self, pen, x_offset, y_offset):\n if self.state == 'active':\n pen.goto(self.x - x_offset, self.y - y_offset)\n pen.setheading(self.heading) # sets the orientation of the turle to east\n pen.shape(self.shape)\n pen.color(self.color)\n pen.stamp() # puts the pen on the screen\n\n self.render_health_meter(pen, x_offset, y_offset)\n\n \n def render_health_meter(self, pen, x_offset, y_offset):\n # Draw health\n pen.goto(self.x - x_offset -10, self.y - y_offset + 20)\n pen.width(3)\n pen.pendown()\n pen.setheading(0)\n\n if self.health/self.max_health < 0.3:\n pen.color('red') # if the health reaches under 30% the pen color changes to red\n elif self.health/self.max_health < 0.7:\n pen.color('yellow')\n else:\n pen.color('green')\n \n pen.fd(20 * (self.health/self.max_health))\n\n if self.health != self.max_health: # if function neccessary to get rid of the grey dots at the start\n pen.color('grey')\n pen.fd(20 * ((self.max_health - self.health)/self.max_health))\n \n pen.penup()\n\nclass Player(Sprite): # inherets the attributes from the parent class\n def __init__(self, x, y, shape, color):\n Sprite.__init__(self, 0, 0, shape, color)\n self.lives = 3 # only the player has lives and score\n self.score = 0\n self.heading = 90 #player goes up\n self.da = 0 # changing the angle\n\n def rotate_left(self):\n self.da = 5\n\n def rotate_right(self):\n self.da = -5\n\n def stop_rotation(self):\n self.da = 0\n \n def accelerate(self):\n self.thrust += self.acceleration\n \n def deaccelerate(self):\n self.thrust = 0.0\n \n def fire(self):\n missile.fire(self.x, self.y, self.heading, self.dx, self.dy) # missile starting on the same position as the player sprites\n \n def update(self):\n if self.state == 'active':\n self.heading += self.da # the heading is gonna change by the delta of the angle\n self.heading %= 360\n self.dx += math.cos(math.radians(self.heading)) * self.thrust\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\n self.x += self.dx\n self.y += self.dy\n self.border_check()\n # Check health\n if self.health <= 0:\n self.reset()\n \n def reset(self): # resetting everything to the default numbers\n self.x = 0\n self.y = 0\n self.health = self.max_health\n self.heading = 90\n self.dx = 0\n self.dy = 0\n self.lives -= 1\n\n def render(self, pen, x_offset, y_offset):\n pen.shapesize(0.5, 1.0, None)\n pen.goto(self.x - x_offset, self.y - y_offset)\n pen.setheading(self.heading) # sets the orientation of the turle to east\n pen.shape(self.shape)\n pen.color(self.color)\n pen.stamp() # puts the pen on the screen\n\n pen.shapesize(1.0, 1.0, None)\n\n self.render_health_meter(pen, x_offset, y_offset)\n\nclass Missile(Sprite): # inherets the attributes from the parent class\n def __init__(self, x, y, shape, color):\n Sprite.__init__(self, x, y, shape, color)\n self.state = 'ready'\n self.thrust = 8.0\n self.max_fuel = 200\n self.fuel = self.max_fuel\n self.height = 4\n self.width = 4\n\n def fire(self, x, y, heading, dx, dy):\n if self.state == 'ready':\n self.state = 'active'\n self.x = x\n self.y = y\n self.heading = heading\n self.dx = dx\n self.dy = dy\n\n self.dx += math.cos(math.radians(self.heading)) * self.thrust # taking the current dx (which is from playwer) and adds own thrust\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\n\n def update(self):\n if self.state == 'active':\n self.fuel -= self.thrust\n if self.fuel <= 0:\n self.reset()\n self.heading += self.da # the heading is gonna change by the delta of the angle\n self.heading %= 360\n \n self.x += self.dx\n self.y += self.dy\n \n self.border_check()\n \n def reset(self): # once its resets we set the fuel back to max fuel and state to ready\n self.fuel = self.max_fuel\n self.dx = 0\n self.dy = 0\n self.state = 'ready'\n\n\n def render(self, pen, x_offset, y_offset): # only renders if its active\n if self.state == 'active':\n pen.shapesize(0.2, 0.2, None)\n pen.goto(self.x - x_offset, self.y - y_offset)\n pen.setheading(self.heading) # sets the orientation of the turle to east\n pen.shape(self.shape)\n pen.color(self.color)\n pen.stamp() # puts the pen on the screen\n \n pen.shapesize(1.0, 1.0, None)\n\nclass Enemy(Sprite): # inherets the attributes from the parent class\n def __init__(self, x, y, shape, color):\n Sprite.__init__(self, x, y, shape, color)\n self.max_health = 20\n self.health = self.max_health\n\n def update(self):\n if self.state == 'active':\n self.heading += self.da # the heading is gonna change by the delta of the angle\n self.heading %= 360\n\n self.dx += math.cos(math.radians(self.heading)) * self.thrust\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\n\n self.x += self.dx\n self.y += self.dy\n\n self.border_check()\n\n # Check health\n if self.health <= 0:\n self.reset()\n \n def reset(self):\n self.state = 'inactive'\n\nclass Powerup(Sprite): # inherets the attributes from the parent class\n def __init__(self, x, y, shape, color):\n Sprite.__init__(self, x, y, shape, color)\n\nclass Camera():\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \n def update(self, x, y):\n self.x = x\n self.y = y\n\nclass Radar():\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n \n def render(self, pen, sprites):\n\n # Draw radar circle\n pen.setheading(90)\n pen.goto(self.x + self.width / 2, self.y)\n pen.pendown()\n pen.circle(self.width / 2)\n pen.penup()\n\n # Draw the sprites\n for sprite in sprites:\n if sprite.state == 'active': # just want to use the active sprites\n radar_x = self.x + (sprite.x - player.x) * (self.width / game.width)\n radar_y = self.y + (sprite.y - player.y) * (self.height / game.height)\n pen.goto(radar_x, radar_y)\n pen.color(sprite.color) # getting the actual color of the sprite displayed on radar\n pen.shape(sprite.shape)\n pen.setheading(sprite.heading)\n pen.shapesize(0.1, 0.1, None)\n\n distance = ((player.x - sprite.x) ** 2 + (player.y - sprite.y) ** 2) ** 0.5\n if distance < player.radar:\n pen.stamp() # stamps a copy of the turtle shape at the current turtle position\n \n\n\n# Create the border\ngame = Game(600, 400)\n\n# Create the radar\nradar = Radar(400, -200, 200, 200)\n\n# Creating the player sprite as a spaceship\nplayer = Player(0,0, 'triangle', 'white') # putting the player in the center\n\n# Creating the Camera\ncamera = Camera(player.x, player.y)\n\n# Creating missile object\nmissile = Missile(0, 100, 'circle', 'yellow')\n\n#enemy = Enemy(0,100, 'square', 'red')\n#enemy.dx = -1\n#enemy.dy = -0.3\n#\n#enemy2 = Enemy(-100,100, 'square', 'red')\n#enemy2.dx = 1\n#enemy2.dy = 0.3\n\n#powerup = Powerup(0,100, 'circle', 'blue')\n#powerup.dy = 1\n#powerup.dx = 0.1\n#\n#powerup2 = Powerup(-100,100, 'circle', 'blue')\n#powerup2.dy = -1\n#powerup2.dx = -0.1\n\n# Sprites list\nsprites = []\n#sprites.append(player)\n#sprites.append(enemy)\n#sprites.append(powerup)\n#sprites.append(missile)\n#sprites.append(enemy2)\n#sprites.append(powerup2)\n\n# setup the level\ngame.start_level()\n\n# Keyboard bindings\nwindow.listen()\nwindow.onkeypress(player.rotate_left, 'Left')\nwindow.onkeypress(player.rotate_right, 'Right')\n\nwindow.onkeyrelease(player.stop_rotation, 'Left') # the moment you dont press left or right it will stop rotating!\nwindow.onkeyrelease(player.stop_rotation, 'Right')\n\nwindow.onkeypress(player.accelerate, 'Up')\nwindow.onkeyrelease(player.deaccelerate, 'Up')\n\nwindow.onkeypress(player.fire, 'space')\n\n# Main Loop\nwhile True:\n # Clear the screen\n pen.clear()\n\n # Update the Sprites to move around the screen\n for sprite in sprites:\n sprite.update()\n \n # check for collision\n for sprite in sprites:\n if isinstance(sprite, Enemy) and sprite.state == 'active':\n if player.is_collision(sprite):\n sprite.health -= 10\n player.health -= 10\n player.bounce(sprite)\n\n if missile.state == 'active' and missile.is_collision(sprite):\n sprite.health -= 10\n missile.reset()\n \n if isinstance(sprite, Powerup):\n if player.is_collision(sprite):\n sprite.x = 100\n sprite.y = 100\n\n if missile.state == 'active' and missile.is_collision(sprite):\n sprite.x = 100\n sprite.y = -100\n missile.reset()\n\n\n # Render the Sprites\n for sprite in sprites:\n sprite.render(pen, camera.x + 100, camera.y)\n\n # Render the borders\n game.render_border(pen, camera.x + 100, camera.y)\n\n # Check for end of the level\n end_of_level = True\n for sprite in sprites:\n # First look if an enemy sprite is still active\n if isinstance(sprite, Enemy) and sprite.state == 'active':\n end_of_level = False\n \n if end_of_level:\n game.level += 1\n game.start_level()\n \n # Updating the camera\n camera.update(player.x, player.y)\n\n # Render the radar\n radar.render(pen, sprites)\n\n # Update the Screen\n window.update()\n\n","sub_path":"Space_Project/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":14790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"291540476","text":"from __future__ import absolute_import, division, print_function\n\nimport scipy as sp\nimport pytest\nimport xarray as xr\n\nfrom xrscipy import integrate\nfrom xrscipy.docs import DocParser\nfrom .testings import get_obj\n\n\n_trapz_funcs = [integrate.trapz]\n_trapz_names = ['trapz']\n_cumtrapz_names = ['cumtrapz']\n_simps_names = ['simps']\n_romb_names = ['romb']\nif hasattr(integrate, 'trapezoid'): # scipy >= 1.6.0\n _trapz_funcs += [integrate.trapezoid]\n _trapz_names += ['trapezoid']\n _cumtrapz_names += ['cumulative_trapezoid']\n _simps_names += ['simpson']\n\n\n@pytest.mark.parametrize('mode', [1, 1])\n@pytest.mark.parametrize('func', _trapz_names + _cumtrapz_names)\n@pytest.mark.parametrize('dim', ['x', 'time'])\ndef test_integrate(mode, func, dim):\n da = get_obj(mode)\n\n axis = da.get_axis_num(da[dim].dims[0])\n actual = getattr(integrate, func)(da, dim)\n kwargs = {}\n if func in _cumtrapz_names:\n kwargs['initial'] = 0\n expected = getattr(sp.integrate, func)(da.values, x=da[dim].values,\n axis=axis, **kwargs)\n assert (actual.values == expected).all()\n\n # make sure the original data does not change\n da.values.ndim == get_obj(mode).ndim\n\n # make sure the coordinate is propagated\n for key, v in da.coords.items():\n if 'x' not in v.dims:\n assert da[key].identical(actual[key])\n\n\n@pytest.mark.parametrize('trapz_func', _trapz_funcs)\ndef test_integrate_dataset(trapz_func):\n ds = get_obj(mode=3)\n\n actual = trapz_func(ds, coord='z')\n assert actual['a'].identical(ds['a'])\n assert actual['b'].identical(integrate.trapz(ds['b'], coord='z'))\n\n\n@pytest.mark.parametrize('trapz_func', _trapz_funcs)\ndef test_integrate_error(trapz_func):\n # not sorted\n da = xr.DataArray([0, 1, 2], dims=['x'], coords={'x': [2, 3, 0]})\n with pytest.raises(ValueError):\n trapz_func(da, 'x')\n\n # wrong argument\n with pytest.raises(TypeError):\n trapz_func(da, axis='x')\n\n\n@pytest.mark.parametrize(\n 'func',\n _trapz_names + _cumtrapz_names + _simps_names + _romb_names)\ndef test_doc_all(func):\n parser = DocParser(func.__doc__)\n\n not_included_keys = ['x', 'axis', 'dx']\n for k in not_included_keys:\n assert k not in parser.parameters.keys()\n\n\n@pytest.mark.parametrize('trapz_func', _trapz_funcs)\ndef test_doc(trapz_func):\n parser = DocParser(trapz_func.__doc__)\n\n not_included_keys = ['x', 'axis', 'dx']\n for k in not_included_keys:\n assert k not in parser.parameters.keys()\n","sub_path":"xrscipy/tests/test_integrate.py","file_name":"test_integrate.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"230969947","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.corpus import subjectivity\nfrom nltk.sentiment import SentimentAnalyzer\nfrom nltk.sentiment.util import *\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom elasticsearch import Elasticsearch\nimport os\nimport datetime\nimport json\nimport subprocess\n\n\n# set environment variable PYSPARK_SUBMIT_ARGS\nos.environ['PYSPARK_SUBMIT_ARGS'] = '--jars /Users/StevenSYT/Documents/Academic/18_Spring/Big_Data/Homework/HW3/Elastic_Kibana/elasticsearch-hadoop-6.2.3/dist/elasticsearch-spark-20_2.11-6.2.3.jar pyspark-shell'\n\n\n\nTCP_IP = 'localhost'\nTCP_PORT = 3000\n\n# Pyspark\n# # create spark configuration\nconf = SparkConf()\n# conf.setAppName('TwitterApp')\n# conf.setMaster('local[4]')\n# create spark context with the above configuration\nsc = SparkContext(conf=conf)\n\n# use accumulator for id generation\naccum = 0\n\n# create the Streaming Context from spark context with interval size 6 seconds\nssc = StreamingContext(sc, 8)\nssc.checkpoint(\"checkpoint_TwitterApp\")\n# read data from port 9001\ndataStream = ssc.socketTextStream(TCP_IP, TCP_PORT)\n\n# create a sentiment analyzer\nsid = SentimentIntensityAnalyzer()\n\n# connect to our cluster\nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\nes_write_conf = {\n# specify the node that we are sending data to (this should be the master)\n\"es.nodes\" : 'localhost',\n\n# specify the port in case it is not the default port\n\"es.port\" : '9200',\n\n# specify a resource in the form 'index/doc-type'\n\"es.resource\" : 'tweetmap/tweet',\n\n# is the input JSON?\n\"es.input.json\" : \"yes\",\n\n# # is there a field in the mapping that should be used to specify the ES document ID\n# \"es.mapping.id\": \"doc_id\"\n}\n\nmappings = {\n \"mappings\": {\n \"tweet\": {\n \"properties\": {\n \"location\": {\n \"type\": \"geo_point\"\n }\n }\n }\n }\n}\n\nes.indices.create(index='tweetmap', body=mappings)\n######### your processing here ###################\ndataStream.pprint()\n\n\n\n# sentiment analysis [tweet,\"location.latitude,location.longitude\", str(UID)]\ndef senAnalysis(line):\n ss = sid.polarity_scores(line[0])\n result = line[0] + ' -- has '\n if ss['compound'] > 0:\n sentiment = 'positive'\n result += 'positive sentiment \\n'\n elif ss['compound'] == 0:\n sentiment = 'neutral'\n result += 'neutral sentiment \\n'\n else:\n sentiment = 'negative'\n result += 'negative sentiment \\n'\n return (result, (line[0], sentiment, line[1], line[2]))\n\n# formatData from senResults\ndef formatData(line):\n jsonLike = {'tweet' : line[1][0], 'sentiment' : line[1][1], 'location' : line[1][2], 'timeStamp' : str(datetime.datetime.now().isoformat())}\n\n return (line[1][3], json.dumps(jsonLike))\n\ndef sendDataToES(rdd):\n rdd.saveAsNewAPIHadoopFile(\n path='',\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\n keyClass=\"org.apache.hadoop.io.NullWritable\",\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\n\n # critically, we must specify our `es_write_conf`\n conf=es_write_conf)\n\n# generate the lineArray\ntweets = dataStream.map(lambda x: x.split(\"\\t\"))\n\n#senResults contains (printresults, (tweet, sentiment, geolocation, timeStamp))\nsenResults = tweets.map(senAnalysis)\n\n# print out the results of sentiment\nsenScores = senResults.map(lambda x: x[0])\nsenScores.pprint()\n\n# map the OutPut json format for ES input\ntweetOutPut = senResults.map(formatData)\ntweetOutPut.pprint()\n\n#send data to ES\ntweetOutPut.foreachRDD(sendDataToES)\n\n# tweetTexts.pprint()\n# words = tweets.flatMap(lambda x: x[0].split(' '))\n# wordcount = words.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)\n# wordcount.pprint()\n\n\n#################################################\n\nssc.start()\nssc.awaitTermination()\n\n# subprocess, shell daemon\n","sub_path":"spark.py","file_name":"spark.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"308832610","text":"n = int(input())\nword = input()\nlist = []\nredacted_list = []\nfor i in range(n):\n list.append(input())\nprint(list)\nfor i in range(n-1, -1, -1):\n element = list[i]\n if word not in element:\n list.remove(element)\nprint(list)","sub_path":"2_fund_python/03_lists_basics_lab/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"267019357","text":"import os\n\nfrom django.contrib import admin\nfrom django.contrib.admin.util import unquote\nfrom django import forms\nfrom django.conf import settings\n\nfrom mptt.admin import MPTTModelAdmin\nfrom ostinato.statemachine.forms import sm_form_factory\nfrom ostinato.pages.models import Page, PageWorkflow\nfrom ostinato.pages.registry import page_content\n\n\nGRAPPELLI = 'grappelli' in settings.INSTALLED_APPS\n\n\ndef content_inline_factory(page):\n content_model = page.get_content_model()\n\n class PageContentInline(admin.StackedInline):\n model = content_model\n extra = 1\n max_num = 1\n can_delete = False\n fk_name = 'page'\n\n ## Check for a custom form and try to load it\n content_form = getattr(content_model.ContentOptions, 'form', None)\n if content_form:\n module_path, form_class = content_form.rsplit('.', 1)\n\n form = __import__(module_path, locals(), globals(),\n [form_class], -1).__dict__[form_class]\n\n return PageContentInline\n\n\n## Admin Models\nclass PageAdminForm(sm_form_factory(sm_class=PageWorkflow)): # <3 python\n\n template = forms.ChoiceField()\n \n def __init__(self, *args, **kwargs):\n super(PageAdminForm, self).__init__(*args, **kwargs)\n self.fields['template'].choices = page_content.get_template_choices()\n\n class Meta:\n model = Page\n\n\nclass PageAdmin(MPTTModelAdmin):\n save_on_top = True\n form = PageAdminForm\n\n list_display = ('title', 'reorder', 'slug', 'template', 'author',\n 'page_state', 'show_in_nav', 'show_in_sitemap', 'publish_date')\n\n list_filter = ('template', 'author', 'show_in_nav', 'show_in_sitemap',\n 'state')\n\n list_editable = ('show_in_nav', 'show_in_sitemap')\n\n search_fields = ('title', 'short_title', 'slug', 'author')\n date_hierarchy = 'publish_date'\n inlines = ()\n\n fieldsets = (\n (None, {\n 'fields': (\n ('title', 'short_title'), 'slug',\n 'template', 'redirect', 'parent',\n ('show_in_nav', 'show_in_sitemap'),\n ),\n }),\n\n ('Publication', {\n 'fields': ('state', 'author', 'publish_date'),\n }),\n\n )\n prepopulated_fields = {'slug': ('title',)}\n\n if GRAPPELLI:\n change_list_template = 'admin/mptt_grappelli_change_list.html'\n\n class Media:\n static_prefix = lambda p: os.path.join(settings.STATIC_URL, '%s' % p)\n\n css = {\n 'all': (\n static_prefix('ostinato/css/smoothness/jquery-ui-1.8.18.custom.css'),\n static_prefix('pages/css/pages_admin.css'),\n ),\n }\n\n js = (\n static_prefix('ostinato/js/jquery-1.7.1.min.js'),\n static_prefix('ostinato/js/jquery-ui-1.8.18.custom.min.js'),\n static_prefix('pages/js/page_admin.js'),\n )\n\n def page_state(self, obj):\n sm = PageWorkflow(instance=obj)\n return sm.state\n page_state.short_description = 'State'\n\n def reorder(self, obj):\n \"\"\" A List view item that shows the movement actions \"\"\"\n return '''\n Move\n Before\n After\n Inside\n Cancel\n \n ''' % (obj.id)\n reorder.short_description = 'Re-order'\n reorder.allow_tags = True\n\n\n def add_view(self, request, form_url='', extra_context=None):\n # We need to clear the inlines. Django keeps it cached somewhere\n self.inlines = ()\n return super(PageAdmin, self).add_view(request, form_url, extra_context)\n\n\n def change_view(self, request, object_id, form_url='', extra_context=None):\n \"\"\"\n We need to dynamically create the inline models since it\n changes based on the template.\n \"\"\"\n self.inlines = ()\n\n if object_id:\n page = self.get_object(request, unquote(object_id))\n\n if page.template:\n self.inlines = (content_inline_factory(page),)\n\n content_model = page.get_content_model()\n if hasattr(content_model.ContentOptions, 'page_inlines'):\n for inline in content_model.ContentOptions.page_inlines:\n self.inlines += (inline,)\n\n return super(PageAdmin, self).change_view(\n request, object_id, form_url, extra_context)\n\n\nadmin.site.register(Page, PageAdmin)\n\n","sub_path":"ostinato/pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"559389157","text":"import xmldict\n\n\nclass XMLSerializer(object):\n content_type = 'application/xml'\n\n ITEM_TAG = 'item'\n\n def to_string(self, data):\n serialize_data_dict = {}\n for k, v in data.viewitems():\n if isinstance(v, (list, tuple, set)):\n v = {self.ITEM_TAG: v}\n elif isinstance(v, str):\n v = v.decode('utf-8')\n serialize_data_dict[k] = v\n return xmldict.dict_to_xml({\n 'root': serialize_data_dict\n })\n\n def from_string(self, str_data):\n load_dict = xmldict.xml_to_dict(\n str_data\n ).get('root', {})\n result_dict = {}\n\n for k, v in load_dict.viewitems():\n if isinstance(v, dict) and [self.ITEM_TAG] == v.keys():\n v = v.values()[0]\n result_dict[k] = v\n\n for k, v in result_dict.viewitems():\n if v in ['true', 'false']:\n result_dict[k] = v == 'true'\n\n return result_dict\n","sub_path":"butler/jobs/serialization/serializers/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"195024360","text":"#!/usr/bin/env python3\n\nimport OpenGL.GL as GL\n\nfrom core.shader import Shader\nfrom core.mesh import Mesh\nfrom core.texture import Cubemap\nfrom core.transform import identity, rotate\n\n\nVERTEX_SHADER_NAME = 'skybox/skybox.vert'\nFRAGMENT_SHADER_NAME = 'skybox/skybox.frag'\nTEXTURES_BACK_NAME = ('../assets/skybox/back/{}.png'.format(name)\n for name in ('side', 'side', 'top', 'top', 'front', 'side'))\nTEXTURES_FRONT_NAME = ('../assets/skybox/front/{}.png'.format(name)\n for name in ('right', 'left', 'top', 'top', 'front', 'back'))\nCLOUDS_ANGULAR_VELOCITY = 0.5\n\n\nclass Skybox(Mesh):\n def __init__(self):\n shader = Shader(VERTEX_SHADER_NAME, FRAGMENT_SHADER_NAME)\n\n position = [(1.0, -1.0, 1.0), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (1.0, 1.0, 1.0),\n (-1.0, -1.0, -1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (-1.0, -1.0, 1.0)]\n index = [2, 1, 0, 0, 3, 2,\n 4, 5, 7, 7, 5, 6,\n 2, 3, 5, 5, 3, 6,\n 0, 1, 4, 4, 7, 0,\n 0, 7, 3, 3, 7, 6,\n 1, 2, 4, 4, 2, 5]\n\n super().__init__(shader, (position,), index)\n\n self.add_locations('tex_back', 'tex_front')\n\n self.back = Cubemap(*TEXTURES_BACK_NAME)\n self.front = Cubemap(*TEXTURES_FRONT_NAME)\n\n self.angle = 0\n self.rotation = identity()\n\n def update(self, delta_time):\n self.angle += CLOUDS_ANGULAR_VELOCITY * delta_time\n self.rotation = rotate((0, 1, 0), -self.angle)\n\n def draw(self, projection, view, model, normal_matrix, camera):\n GL.glUseProgram(self.shader.glid)\n\n self.back.bind(0)\n GL.glUniform1i(self.locations['tex_back'], 0)\n self.front.bind(1)\n GL.glUniform1i(self.locations['tex_front'], 1)\n\n super().draw(projection, view, self.rotation, self.rotation, camera)\n","sub_path":"src/skybox/skybox.py","file_name":"skybox.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"353261687","text":"import re\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\n \nurl = 'https://www.navitime.co.jp/diagram/stops/00000112/806200ac/?node=00004995&year=2022&month=11&day=07&from=timetable'\nhtml_text = requests.get(url).text\nsoup = BeautifulSoup(html_text, 'html.parser')\nfor page in soup.find_all(class_=\"diagram-link\"):\n time.sleep(5)\n url = page.find('a').get('href')+\"&trainType=普通\"\n html_text = requests.get(url).text\n soup = BeautifulSoup(html_text, 'html.parser')\n title = soup.select_one(\"#body-left > div.station-frame > h2 > ruby > rb\").text\n title = title.replace(\"(静岡県)\",\"\")\n count = 0\n for direction in soup.select(\".diagram-frame\"):\n count += 1\n if count <=2:\n if count == 1:\n f = open('./'+title+'_s.csv', 'w',encoding='UTF-8')\n if count == 2:\n f = open('./'+title+'_h.csv', 'w',encoding='UTF-8')\n for line in direction.select(\"dl\"):\n hour = line.find(class_=\"diagram-frame__hour\").text\n if hour[0] == '0':\n hour = hour[1:]\n for cell in line.find_all(class_=\"time-frame\"):\n f.writelines(hour+\",\"+cell.find(class_=\"time\").text+\", \"+cell.find(class_=\"ruby-dest\").text[0]+\",\\n\")\n f.close()\n","sub_path":"DATA2/station.py","file_name":"station.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"172498101","text":"#!/usr/bin/env python\n\n#\n# LSST Data Management System\n# Copyright 2008, 2009, 2010 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\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 3 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 LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\nfrom __future__ import print_function\nfrom builtins import range\nfrom builtins import object\nimport os\nimport sys\nimport optparse\nimport lsst.pex.policy as pol\n\n\nclass CondorJobInfo(object):\n\n class PipelineJob(object):\n\n def __init__(self, scratchDir, wfName, pipelineName, pipelineNumber):\n self.wfName = wfName\n self.pipelineName = pipelineName\n self.pipelineNumber = pipelineNumber\n\n self.pipelineIndexedName = \"%s_%s\" % (pipelineName, pipelineNumber)\n self.wfScratchDir = os.path.join(scratchDir, self.wfName)\n\n def getWorkflowName(self):\n return self.wfName\n\n def getPipelineName(self):\n return self.pipelineName\n\n def getPipelineNumber(self):\n return int(self.pipelineNumber)\n\n def getFileName(self):\n pipelineDir = os.path.join(self.wfScratchDir, self.pipelineIndexedName)\n pipelineWorkDir = os.path.join(pipelineDir, \"work\")\n pipelineJobDir = os.path.join(pipelineWorkDir, self.pipelineIndexedName)\n pipelineJobFile = os.path.join(pipelineJobDir, \"%s.job\" % self.pipelineIndexedName)\n return pipelineJobFile\n\n class GlideinJob(object):\n\n def __init__(self, scratchDir, wfName):\n self.scratchDir = scratchDir\n self.wfName = wfName\n wfScratchDir = os.path.join(scratchDir, wfName)\n self.glideinFileName = os.path.join(wfScratchDir, \"glidein.job\")\n\n def getWorkflowName(self):\n return self.wfName\n\n def getFileName(self):\n return self.glideinFileName\n\n def __init__(self, prodPolicy, runid):\n self.prodPolicy = prodPolicy\n self.runid = runid\n\n ##\n # @brief given a list of pipelinePolicies, number the section we're\n # interested in based on the order they are in, in the productionPolicy\n #\n def getPipelineJobs(self):\n wfPolicies = self.prodPolicy.getArray(\"workflow\")\n expanded = []\n for wfPolicy in wfPolicies:\n wfShortName = wfPolicy.get(\"shortName\")\n pipelinePolicies = wfPolicy.getArray(\"pipeline\")\n localScratch = self.getLocalScratch(wfPolicy)\n for policy in pipelinePolicies:\n runCount = 1 # default to 1, if runCount doesn't exist\n if policy.exists(\"runCount\"):\n runCount = policy.get(\"runCount\")\n for i in range(runCount):\n pipelineShortName = policy.get(\"shortName\")\n pipelineJob = self.PipelineJob(localScratch, wfShortName, pipelineShortName, i+1)\n expanded.append(pipelineJob)\n return expanded\n\n ##\n # @brief given a list of pipelinePolicies, number the section we're\n # interested in based on the order they are in, in the productionPolicy\n #\n def getGlideinJobs(self):\n wfPolicies = self.prodPolicy.getArray(\"workflow\")\n glideinJobs = []\n for wfPolicy in wfPolicies:\n localScratch = self.getLocalScratch(wfPolicy)\n wfShortName = wfPolicy.get(\"shortName\")\n glideinJob = self.GlideinJob(localScratch, wfShortName)\n glideinJobs.append(glideinJob)\n return glideinJobs\n\n def getLocalScratch(self, wfPolicy):\n configurationPolicy = wfPolicy.get(\"configuration\")\n condorDataPolicy = configurationPolicy.get(\"condorData\")\n localScratch = condorDataPolicy.get(\"localScratch\")\n\n return os.path.join(localScratch, self.runid)\n\n\nclass JobKiller(object):\n\n def __init__(self, workflowName, pipelineName, pipelineNumber):\n self.workflowName = workflowName\n self.pipelineName = pipelineName\n self.pipelineNumber = pipelineNumber\n return\n\n # TODO: make this read multiple lines\n def killJob(self, filename):\n print(\"killJob: \", filename)\n try:\n input = open(filename, 'r')\n except Exception:\n # couldn't find that file, so pass\n return\n line = input.readline()\n line = line.strip('\\n')\n cmd = [\"condor_rm\", line]\n\n pid = os.fork()\n if not pid:\n os.execvp(cmd[0], cmd)\n os.wait()[0]\n return\n\n def processGlideinJob(self, job):\n jobFile = job.getFileName()\n if self.workflowName is None:\n self.killJob(jobFile)\n elif self.workflowName == job.getWorkflowName():\n self.killJob(jobFile)\n return\n\n def processPipelineJob(self, job):\n jobFile = job.getFileName()\n\n if self.workflowName is None:\n self.killJob(jobFile)\n elif self.workflowName == job.getWorkflowName():\n if self.pipelineName is None:\n self.killJob(jobFile)\n elif self.pipelineName == job.getPipelineName():\n if self.pipelineNumber is None:\n self.killJob(jobFile)\n elif self.pipelineNumber == job.getPipelineNumber():\n self.killJob(jobFile)\n return\n\n\nif __name__ == \"__main__\":\n usage = \"\"\"usage %prog [-g] [-w workflow[-p pipeline [-n pipelineNum]] productionPolicyFile runId\"\"\"\n\n parser = optparse.OptionParser(usage)\n\n parser.add_option(\"-g\", \"--glidein\", action=\"store_true\",\n dest=\"killglidein\", default=False, help=\"kill the glidein\")\n parser.add_option(\"-w\", \"--workflow\", action=\"store\", dest=\"workflowArg\",\n default=None, help=\"workflow shortname\")\n parser.add_option(\"-p\", \"--pipeline\", action=\"store\", dest=\"pipelineArg\",\n default=None, help=\"pipeline shortname\")\n parser.add_option(\"-n\", \"--pipelineNum\", action=\"store\",\n dest=\"pipelineNumArg\", default=None, help=\"pipeline number\")\n\n parser.opts = {}\n parser.args = []\n\n (parser.opts, parser.args) = parser.parse_args()\n\n workflowArg = parser.opts.workflowArg\n pipelineArg = parser.opts.pipelineArg\n pipelineNumArg = None\n if parser.opts.pipelineNumArg is not None:\n pipelineNumArg = int(parser.opts.pipelineNumArg)\n killGlidein = parser.opts.killglidein\n\n if len(parser.args) < 2:\n print(usage)\n raise RuntimeError(\"Missing args: productionPolicyFile runId\")\n\n prodPolicyFile = parser.args[0]\n runid = parser.args[1]\n\n prodPolicy = pol.Policy.createPolicy(prodPolicyFile, False)\n\n jobInfo = CondorJobInfo(prodPolicy, runid)\n\n killer = JobKiller(workflowArg, pipelineArg, pipelineNumArg)\n\n if killGlidein:\n glideinJobs = jobInfo.getGlideinJobs()\n for job in glideinJobs:\n killer.processGlideinJob(job)\n sys.exit(0)\n\n pipelineJobs = jobInfo.getPipelineJobs()\n for job in pipelineJobs:\n killer.processPipelineJob(job)\n","sub_path":"bin.src/killcondor.py","file_name":"killcondor.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"414407135","text":"# Problem from UVA 12207\tThat is Your Queue\n# https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3359\n\n# Your government has finally solved the\n# problem of universal health care! Now\n# everyone, rich or poor, will finally have\n# access to the same level of medical care.\n# Hurrah!\n# There’s one minor complication. All\n# of the country’s hospitals have been condensed\n# down into one location, which can\n# only take care of one person at a time.\n# But don’t worry! There is also a plan\n# in place for a fair, efficient computerized\n# system to determine who will be admitted.\n# You are in charge of programming\n# this system.\n# Every citizen in the nation will be assigned\n# a unique number, from 1 to P\n# (where P is the current population). They will be put into a queue, with 1 in front of 2, 2 in front of\n# 3, and so on. The hospital will process patients one by one, in order, from this queue. Once a citizen\n# has been admitted, they will immediately move from the front of the queue to the back.\n# Of course, sometimes emergencies arise; if you’ve just been run over by a steamroller, you can’t wait\n# for half the country to get a routine checkup before you can be treated! So, for these (hopefully rare)\n# occasions, an expedite command can be given to move one person to the front of the queue. Everyone\n# else’s relative order will remain unchanged.\n# Given the sequence of processing and expediting commands, output the order in which citizens will\n# be admitted to the hospital.\n\n# Input\n# Input consists of at most ten test cases. Each test case starts with a line containing P, the population\n# of your country (1 ≤ P ≤ 1000000000), and C, the number of commands to process (1 ≤ C ≤ 1000).\n# The next C lines each contain a command of the form ‘N’, indicating the next citizen is to be\n# admitted, or ‘E x’, indicating that citizen x is to be expedited to the front of the queue.\n# The last test case is followed by a line containing two zeros.\n# Output\n# For each test case print the serial of output. This is followed by one line of output for each ‘N’ command,\n# indicating which citizen should be processed next. Look at the output for sample input for details.\n# Sample Input\n# 3 6\n# N\n# N\n# E 1\n# N\n# N\n# N\n# 10 2\n# N\n# N\n# 0 0\n\n# Sample Output\n# Case 1:\n# 1\n# 2\n# 1\n# 3\n# 2\n# Case 2:\n# 1\n# 2\n\n\nclass Node:\n def __init__(self, data_val=None):\n self.data_val = data_val\n self.next_node = None\n\n\nclass MyLinkedList:\n def __init__(self):\n self.head_node = None\n self.tail_node = self.head_node\n\n def print_list(self):\n print_node = self.head_node\n while True:\n if print_node.next_node is None:\n print(print_node.data_val, end='')\n break\n else:\n print(print_node.data_val, end=' ')\n print_node = print_node.next_node\n print('---')\n\n def add_node(self, value=None):\n new_node = Node(value)\n if self.tail_node is not None:\n self.tail_node.next_node = new_node\n self.tail_node = new_node\n else:\n self.head_node = new_node\n self.tail_node = new_node\n\n def remove_head(self):\n head_value = self.head_node.data_val\n if self.head_node == self.tail_node:\n self.head_node = None\n self.tail_node = None\n else:\n self.head_node = self.head_node.next_node\n return head_value\n\n def remove_node(self, val_to_remove):\n cur_node = self.head_node\n cur_pre_node = None\n while True:\n if cur_node is None:\n return\n if cur_node.data_val == val_to_remove:\n if cur_pre_node is not None:\n cur_pre_node.next_node = cur_node.next_node\n else:\n self.head_node = cur_node.next_node\n if cur_node.next_node is None:\n self.tail_node = cur_pre_node\n return\n else:\n cur_pre_node = cur_node\n cur_node = cur_node.next_node\n\n def add_head(self, val_to_add):\n new_node = Node(val_to_add)\n if self.head_node is not None:\n new_node.next_node = self.head_node\n self.head_node = new_node\n else:\n self.head_node = new_node\n self.tail_node = new_node\n\n\nresults = []\nwhile True:\n P, C = map(int, input().split())\n\n if P == 0:\n break\n P = min(P, C)\n\n cur_queue = MyLinkedList()\n for i in range(P):\n cur_queue.add_node(i + 1)\n cur_result = []\n for i in range(C):\n Ci = input()\n if Ci is 'N':\n cur_treating = cur_queue.remove_head()\n cur_result.append(cur_treating)\n cur_queue.add_node(cur_treating)\n else:\n expedited_index = int(Ci.split()[1])\n cur_queue.remove_node(expedited_index)\n cur_queue.add_head(expedited_index)\n\n results.append(cur_result)\n\nfor i in range(len(results)):\n print('Case %d:' %(i + 1))\n print(*results[i], sep='\\n')\n","sub_path":"Blue/Session 04 - Stack and Queue/UVA_12207 - That is Your Queue.py","file_name":"UVA_12207 - That is Your Queue.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"250133196","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 25 19:22:08 2015\n\n@author: user\n\"\"\"\nimport csv\n\n\nmovies = ['tt0111161', 'tt1856010', 'tt0096694', 'tt0088763', 'tt1375666']\n\nnumbers = [];\nfor i in movies:\n numbers.append(i[2:])\nprint(numbers)\n\nnumbers2 = [int(i[1:]) for i in movies];\nprint(numbers2)\n\nint_numbers = [int(i) for i in numbers2];\nsum(int_numbers[0:3])\nsum(int_numbers)\n\n#####################\n\nf = open('airlines.csv', 'rU')\nfile_string = f.read()\nf.close()\n\nwith open('airlines.csv', 'rU') as f:\n file_nested_list = [row for row in csv.reader(f)]\n \nheader = file_nested_list[0]\ndata = file_nested_list[1:]\n\n\navg_incidents_yr = [(float(airline[2]) + float(airline[5]))/30 for airline in data]\nname_clean = [airline[0].replace('*','') for airline in data]\nname_star = [0 if airline[0].find('*') == -1 else 1 for airline in data]\ndict_airlines = dict(zip(name_clean, avg_incidents_yr))\n\n##################### HW\n\n# cd ~/Desktop/DAT8/data\nimport csv\nwith open('chipotle.tsv', 'rU') as f:\n #dialect = csv.Sniffer().sniff(f.read(1024))\n \n file_nested_list = [row for row in csv.reader(f, delimiter='\\t')]\n\nheader = file_nested_list[0]\ndata = file_nested_list[1:]\n\nlst_prices = [float(i[4][1:]) for i in data]\nsum_prices = sum(lst_prices)\nlst_order_ids = [int(i[0]) for i in data]\nnum_orders = len(set(lst_order_ids))\navg_order_price = sum_prices/num_orders\n\nlst_canned = [item_order[3] for item_order in data if item_order[2].lower().find('canned') >= 0]\nlst_canned_unique = set(lst_canned)\n\nlst_burrito_topping = [item_order[3] for item_order in data if item_order[2].lower().find('burrito') >= 0]\ncount_burrito_topping = [i.count(',') + 1 for i in lst_burrito_topping]\navg_burrito_topping = float(sum(count_burrito_topping))/len(lst_burrito_topping)\n\nlst_chip_names = set([item_order[2] for item_order in data if item_order[2].lower().find('chip') >= 0])\n\nlst_chip_count = []\n \nfor chip_name in lst_chip_names:\n print(chip_name)\n int_chip_count = 0\n for item_order in data:\n if item_order[2] == chip_name:\n int_chip_count += 1 * int(item_order[1])\n lst_chip_count.append(int_chip_count)\n \ndict_chip_count = dict(zip(lst_chip_names, lst_chip_count))\n\n#set([i[3] for i in data])\n# lst_item_name = [i[2].lower() for i in data]\n'''\nfor item_order in data:\n int_chip_count = 0\n for chip_name in lst_chip_names:\n if item_order[2] == chip_name:\n int_chip_count += 1\n lst_chip_count.append(int_chip_count)\n'''","sub_path":"code/own_code/class3.py","file_name":"class3.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"129787526","text":"\nfrom mysetup import * #setup code for these sets of simulations\n\nh.dt = 0.1 # set some parameters - dt is time-step in milliseconds\nh.tstop = 400 # tstop is duration of simulation in milliseconds\n\nallsec = [] # list of sections\n\nsoma = h.Section(name=\"soma\") # make a section named soma\nsoma.L = 10 # length in microns \nsoma.diam = 10 # diameter in microns\nsoma.nseg = 1 # number of segments\nallsec.append(soma)\n\ncable = h.Section(name=\"cable\") # make the cable\ncable.L = 10000\ncable.diam = 1\ncable.nseg = 1001\nallsec.append(cable)\n\nsoma.connect(cable,1,0) # connect soma to the cable\n\nhaveHH = False # whether to add a HH channel to soma\n\n# add a passive/leak channel\nfor sec in allsec:\n sec.insert('pas') \n sec.e_pas = -65 # mV\n sec.g_pas = 1/20e3 # 0.1e-3 # S/cm2 \n if sec == soma and haveHH:\n # optionally, add a hodgkin-huxley type channel\n soma.insert('hh')\n\nlvec = [] # list of vectors for recording\n \nvvolt = h.Vector(int(h.tstop/h.dt)+1) # make a Vector \nvvolt.record(soma(0.5)._ref_v) # to record voltage from the section\nvvolt.label(\"soma(0.5).v\") # give the vector a label - shows up in plot\nlvec.append(vvolt) # save the vvolt Vector to a list\n\ng = [] # Graphs for plotting the output\nfor i in xrange(0,2):\n g.append(h.Graph())\n\n# setup space plot\ng.append(h.Graph(0))\ng[2].size(0,10000,-80,-20) # sets viewing size\ng[2].view(0, -80, 10000, 60, 0, 374, 300.48, 200.32)\nh.flush_list.append(g[2]) # makes sure graph gets updated during run\nrvp = h.RangeVarPlot(\"v\") # make it a RangeVarPlot\nrvp.begin(0)\nrvp.end(1)\nrvp.origin(0)\ng[2].addobject(rvp, 2, 1, 0.8, 0.9)\nh.doNotify() # make sure graphics updated during run\n\nasy = h.AlphaSynapse(cable(0.5)) # alpha synapse at soma(0.5)\nasy.onset = 10 # time at which synapse is activated\nasy.tau = 20 # synaptic time constant\nasy.gmax = 0.015 # maximum conductance\nasy.e = 0 # synapse reversal potential\n\nvisy = h.Vector(int(h.tstop/h.dt)+1)\nvisy.record(asy._ref_i) # record synaptic current from the asy AlphaSynapse\nvisy.label(\"asy.i\") # give the vector a label - shows up in plot\nlvec.append(visy) # save the visy Vector to a list\n\n# plot the output\ndef plotout ():\n for i in xrange(0,2):# clear Graph contents\n g[i].erase_all()\n lvec[i].plot(g[i],h.dt,i+1,2) #\n g[i].exec_menu(\"View = plot\") # set Graph view to what was drawn\n\n# myrun function - runs sim and plots output\ndef myrun ():\n h.run() # run\n plotout() # plot the output\n\nmyrun()\n","sub_path":"sam_code/onesecalpha.py","file_name":"onesecalpha.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"258462025","text":"from django.urls import path\r\nfrom .views import *\r\nfrom . import views\r\n\r\n\r\napp_name = 'app'\r\n\r\nurlpatterns = [\r\n #path('', HomeView.as_view(), name='home'),you_seller\r\n path('', home , name='home'),\r\n path('search/', SearchPage, name='search_result'),\r\n\r\n path('checkout/', CheckoutView.as_view(), name='checkout'),\r\n path('payment//', PaymentView.as_view(), name='payment'),\r\n path('paymentcod//', PaymentCOD.as_view(), name='payment-cod'), \r\n\r\n path('products/', products, name='products'),\r\n path('profile/', views.view_profile, name='view_profile'),\r\n path('profile_edit/', views.update_profile, name='edit_profile'),\r\n\r\n path('you-seller/', you_seller , name='you-seller'),\r\n path('seller-register/', seller_register.as_view() , name='seller-register'),\r\n path('seller-account/', seller_account , name='seller-account'),\r\n path('sharing/', sharing, name='sharing'),\r\n path('renting/', renting, name='renting'),\r\n #path('seller-register/phone-verification/', phone_verification.as_view(), name='phone-verification'),\r\n path('phone-verification/', ValidatePhoneSendOTP.as_view(), name='phone-verification'),\r\n path('ValidateOTP//', ValidateOTP.as_view(), name='ValidateOTP'),\r\n path('seller-details/', seller_details.as_view() , name='seller-details'),\r\n\r\n path('product//', ItemDetailView, name='product'),\r\n path('add-to-cart//', add_to_cart,name='add-to-cart'),\r\n path('remove-from-cart//', remove_from_cart,name='remove-from-cart'),\r\n\r\n path('increase-rent-time-interval//', increase_rent_time_interval,name='increase-rent-time-interval'),\r\n path('reduce-rent-time-interval//', reduce_rent_time_interval,name='reduce-rent-time-interval'),\r\n\r\n path('order-summary/', OrderSummaryView.as_view(), name='order-summary'),\r\n path('ordered-summary/', OrderedSummaryView.as_view(), name='ordered-summary'),\r\n path('share-summary/', ShareSummaryView.as_view(), name='share-summary'),\r\n path('remove-single-item-from-cart/', remove_single_item_from_cart, name='remove-single-item-from-cart'),\r\n\r\n\r\n path('image_upload/', sharing, name = 'image_upload'), \r\n path('success/', success, name = 'success'),\r\n #path('sharing/', AuthorCreate.as_view(), name = \"sharing\"),\r\n #path('distance//', get_distance, name = 'get-distance'),\r\n\r\n]\r\n\r\n","sub_path":"nearbyshops/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"75537491","text":"from hello import hello\nfrom hello.logger import BuiltinLogger\n\n_g_logger = BuiltinLogger(\"User Test Script\")\n\ndef test_2053(app):\n \n n2i = \"n2_i_time_(min)\"\n n2d = \"n2_d_time (min)\"\n do_db = \"Deadband (DO%)\"\n n2_am = \"n2 Auto max (%)\"\n n2_P = \"n2 p gain (%/DO%)\"\n \n # backup settings\n _g_logger.info(\"Backing up config settings\")\n app.login()\n cfg = app.getConfig()\n old_cfg = {}\n old_cfg[n2i] = cfg['DO'][n2i]\n old_cfg[n2d] = cfg['DO'][n2d]\n old_cfg[do_db] = cfg['DO'][do_db]\n old_cfg[n2_am] = cfg['DO'][n2_am]\n old_cfg[n2_P] = cfg['DO'][n2_P]\n \n # set test settings\n _g_logger.info(\"Setting test settings\")\n app.setconfig('DO', n2i, 0)\n app.setconfig('DO', n2d, 0)\n app.setconfig('DO', do_db, 0)\n app.setconfig('DO', n2_am, 100)\n app.setconfig('DO', n2_P, -5)\n \n do_pv = app.getdopv()\n app.setdo(0, do_pv - 10)\n \n input(\"Press enter when done\")\n \n _g_logger.info(\"Restoring old config\")\n for k, v in old_cfg:\n app.setconfig('DO', k, v)\n ","sub_path":"func_test/user_tests/setups.py","file_name":"setups.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"137039938","text":"from random import randrange\nimport pandas as pd\nimport time\nimport random\nimport numpy as np\nfrom datetime import date\nfrom connection import MySQLDatabase\n\n# Input\n#print(\"What's the name of the excel?\")\n#excel_name = input()\n\nexcel_name = \"messages.csv\"\n\n# Read the csv\n# print(excel_name)\ndf = pd.read_csv(excel_name)\n\n\n# Convert dataframe to dict()\nhashmap = df.to_dict('records')\n\ntotalPoints = 0\n# Loop through dictionary\nfor entry in hashmap:\n totalPoints += entry['Total Points']\n\n# print(totalPoints)\n\nfor entry in hashmap:\n entry['probability'] = entry['Total Points'] / totalPoints\n\n\ndef get_winner(winning_probability):\n cumulative_probability = 0\n for entry in hashmap:\n cumulative_probability = cumulative_probability + \\\n entry['probability']\n if winning_probability <= cumulative_probability and cumulative_probability != 0:\n return entry['First Name']\n\n return \"no winner\"\n\n\ndef convertTuple(winner_tuple):\n winner_tuple_in_str = \"\"\n winner_tuple_in_str = winner_tuple_in_str.join(str(winner_tuple))\n return winner_tuple_in_str\n\n\n# Update in database\nx = MySQLDatabase()\nfor entry in hashmap:\n if (pd.isnull(entry['First Name'])):\n entry['First Name'] = \"\"\n x.add_user(entry['First Name'], entry['Email'],\n entry['Total Points'], entry['probability'])\n\n\n# Compute the winner\nrandom.seed(a=date.today(), version=2)\nwinning_probability = random.uniform(0, 1)\nname_of_winner = get_winner(winning_probability)\nwinner_tuple = x.retrieve_user(name_of_winner)\nx.add_luckydrawrecord(name_of_winner)\nwinner_tuple_in_str = convertTuple(winner_tuple)\n\n\n# Store in database\nx = MySQLDatabase()\n#print(\"The winner is :\", winner_tuple_in_str)\n\n\ndef countdown(t):\n\n while t:\n mins, secs = divmod(t, 60)\n timer = '{:02d}:{:02d}'.format(mins, secs)\n print(timer, end=\"\\r\")\n time.sleep(1)\n t -= 1\n\n print(\"The winner is :\", winner_tuple[1])\n\n\ncountdown(5)\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"70798749","text":"import os\nimport sys\nimport re\nimport webbrowser\nimport tkinter\nfrom http.server import HTTPServer,SimpleHTTPRequestHandler\nhost = \"localhost\"\nport = 8000\nurl=host+r\":\"+str(port)\nargc=sys.argv\nif len(argc) > 1:\n\tif os.path.exists(argc[1]):\n\t\tos.chdir(os.path.dirname(argc[1]))\n\t\tif os.path.isfile(argc[1]):\n\t\t\turl=url+\"/\"+os.path.basename(argc[1])\n\t\telse:\n\t\t\tos.chdir(os.path.basename(argc[1]))\nhttpd = HTTPServer((host,port),SimpleHTTPRequestHandler)\nprint(url)\nprint('exit to \"Ctrl + c\"')\nif os.path.exists(\"C:\\\\Program Files (x86)\\\\Mozilla Firefox\\\\firefox.exe\"):\n\twebbrowser.get('\"C:\\\\Program Files (x86)\\\\Mozilla Firefox\\\\firefox.exe\" %s').open_new_tab(url)\nhttpd.serve_forever()","sub_path":"simulator/2015/localserver.py","file_name":"localserver.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"407521908","text":"from flask_restful import Resource\nfrom models.entity import EntityModel\nfrom schemas.entity import EntitySchema\n\nentity_schema = EntitySchema()\nentity_list_schema = EntitySchema(many=True)\n\n\nclass Entity(Resource):\n @classmethod\n def get(cls, name):\n entity = EntityModel.find_by_name(name)\n if entity:\n return entity_schema.dump(entity), 200\n return {'message': 'entity not found'}, 404\n\n @classmethod\n def post(cls, name):\n if EntityModel.find_by_name(name):\n return {'message': \"A Handler with name '{}' already exists.\".format(name)}, 400\n\n entity = EntityModel(name=name)\n try:\n entity.save_to_db()\n except:\n return {'message': 'An error occurred while creating the store.'}, 500\n\n return entity_schema.dump(entity), 201\n\n @classmethod\n def delete(cls, name):\n entity = EntityModel.find_by_name(name)\n if entity:\n entity.delete_from_db()\n return {'message': \"Handler '{}' deleted.\".format(name)}\n\n\nclass EntityList(Resource):\n @classmethod\n def get(cls):\n return {'handlers': entity_list_schema.dump(EntityModel.find_all())}\n","sub_path":"resources/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"500918420","text":"import string;\r\ndef limpartela():\r\n print (\"\\n\"*15)\r\n\r\ndef criptografrar(mensagem,chave):\r\n if mensagem.isdigit()==True: #Verifica se é numero\r\n if chave>0:\r\n mensagem = list(mensagem)\r\n numeros = str(string.digits)\r\n num = list(numeros)\r\n key = len(mensagem)\r\n for numero_verificar in range(0,len(num)):\r\n for numero_mensagem in range(0,len(mensagem)):\r\n if (numero_mensagem == numero_verificar):\r\n mensagem[numero_mensagem] = ((chave+(key+numero_verificar)) + (int(mensagem[numero_mensagem])))\r\n print(\"Dados criptografados : \",end=\"\")\r\n for i in range(0,len(mensagem)):\r\n print((mensagem[i]),end=\",\")\r\n else:\r\n print(\"Digite um valor numerico\")\r\n else:\r\n alfabeto = list(string.ascii_lowercase*chave)\r\n mensagem = list(mensagem)\r\n for i in range(0,len(mensagem)):\r\n for x in range(0,len(alfabeto)):\r\n if i<(len(alfabeto)-chave):\r\n if (mensagem[i]==alfabeto[x])and(mensagem[i]!=\"\"):\r\n mensagem[i] = alfabeto[(x+chave)]\r\n break\r\n else:\r\n if (mensagem[i]==alfabeto[x])and(mensagem[i]!=\"\"):\r\n mensagem[i] = alfabeto[(x-chave)]\r\n break\r\n print(\"Dados criptografados : \",end=\"\")\r\n for i in range(0,len(mensagem)):\r\n print((mensagem[i]),end=\"\")\r\ndef decode(opcao,chave):\r\n if (opcao.lower()==\"numero\"):\r\n mais = \"sim\"\r\n i=0\r\n mensagem = list()\r\n while (mais.lower() == \"sim\"):\r\n mensagem.append ((input(\"Digite o Numero: \")))\r\n mais = input(\"Há mais Numeros ? Sim ou Nao ? \") \r\n i=i+1\r\n numeros = str(string.digits)\r\n num = list(numeros)\r\n key = len(mensagem)\r\n for numero_verificar in range(0,len(num)):\r\n for numero_mensagem in range(0,len(mensagem)):\r\n if (numero_mensagem == numero_verificar):\r\n mensagem[numero_mensagem] = ((int(mensagem[numero_mensagem]))-((key+numero_verificar)+chave))\r\n limpartela()\r\n print(\"Dados descriptografados : \",end=\"\")\r\n for i in range(0,len(mensagem)):\r\n print((mensagem[i]),end=\"\")\r\n elif (opcao.lower()==\"texto\"):\r\n alfabeto = list(string.ascii_lowercase*chave)\r\n\r\n mensagem = list(input(\"Digite a mensagem: \"))\r\n for i in range(0,len(mensagem)):\r\n for x in range(0,len(alfabeto)):\r\n if i<(len(alfabeto)-chave):\r\n if (mensagem[i]==alfabeto[x])and(mensagem!=\"\"):\r\n mensagem[i] = alfabeto[(x-chave)]\r\n break\r\n else:\r\n if (mensagem[i]==alfabeto[x])and(mensagem!=\"\"):\r\n mensagem[i] = alfabeto[(x+chave)]\r\n break\r\n print(\"Dados descriptografados : \",end=\"\")\r\n for i in range(0,len(mensagem)):\r\n print((mensagem[i]),end=\"\")\r\n else:\r\n print(\"Opção Desconhecida\")\r\n pass\r\ncontinuar = \"sim\"\r\nwhile (continuar.lower()==\"sim\"): #Enquanto o o usuario digitar sim para continuar\r\n print(\"\\n----------------------------------------------------\")\r\n print(\"1 - Criptografrar dados\")\r\n print(\"2 - Descriptografar dados\")\r\n print(\"3 - Sair\")\r\n print(\"----------------------------------------------------\")\r\n i_opcao = int(input())\r\n if (i_opcao==1):\r\n limpartela()\r\n criptografrar(input(\"Mensagem: \"),(int(input(\"Digite a chave: \"))))\r\n elif (i_opcao==2):\r\n limpartela()\r\n decode(input(\"Deseja Descriptografar Texto ou Numero ?\\n\"),int(input(\"Digite a Chave: \")))\r\n elif(i_opcao==3):\r\n break\r\n else:\r\n limpartela()\r\n print(\"Opcão Não Conhecida tente novamente\")\r\n continuar = \"sim\"\r\n","sub_path":"Criptografia1.6.py","file_name":"Criptografia1.6.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"436463950","text":"from flask import Flask, render_template, request, redirect\r\nfrom flask_mail import Mail, Message\r\n\r\napp=Flask(__name__)\r\n\r\nmail_settings={\r\n \"MAIL_SERVER\": 'smtp.gmail.com',\r\n \"MAIL_PORT\": 465,\r\n \"MAIL_USE_TLS\": False,\r\n \"MAIL_USE_SSL\": True,\r\n \"MAIL_USERNAME\": 'rlgbluet3c6@gmail.com',\r\n \"MAIL_PASSWORD\": '15793*82'\r\n}\r\n\r\napp.config.update(mail_settings)\r\nmail=Mail(app)\r\n\r\nclass Contato:\r\n def __init__(self, nome, email, mensagem):\r\n self.nome=nome\r\n self.email=email\r\n self.mensagem=mensagem\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/contactform', methods=['GET', 'POST'])\r\ndef send():\r\n if request.method=='POST':\r\n formContato=Contato(\r\n request.form['name'],\r\n request.form['email'],\r\n request.form['message']\r\n )\r\n\r\n msg=Message(\r\n subject=\"Contato do seu portfólio\",\r\n sender=app.config.get(\"MAIL_USERNAME\"),\r\n recipients=[app.config.get(\"MAIL_USERNAME\")],\r\n body=f'''{formContato.nome} enviou a seguinte mensagem\r\n {formContato.mensagem}'''\r\n )\r\n mail.send(msg)\r\n return render_template('contactform.html',\r\n formContato=formContato)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","sub_path":"Projeto02-Portfolio/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"284148800","text":"from gmplot import gmplot\n\n# PLOTTER CONSTANTS\nCITY = \"Porto Alegre\"\nZOOM = 14\n\n# SCATTER CONSTANTS\nSCATTER_SIZE = 8\nSCATTER_COLOR = \"#3B0B39\"\n\n# HEATMAP CONSTANTS\nRADIUS = 40\nTHRESHOLD = 5\n\n\ndef plot_scatter(latitudes, longitudes, year):\n # Place map\n gmap = gmplot.GoogleMapPlotter.from_geocode(CITY, zoom=ZOOM)\n\n gmap.scatter(latitudes, longitudes, SCATTER_COLOR, size=SCATTER_SIZE, marker=False)\n\n # Draw\n gmap.draw(\"results/scatter/\" + str(year) + \".html\")\n\n\ndef plot_heatmap(latitudes, longitudes, year):\n # Place map\n gmap = gmplot.GoogleMapPlotter.from_geocode(CITY, zoom=ZOOM)\n\n gmap.heatmap(latitudes, longitudes, radius=RADIUS, threshold=THRESHOLD)\n\n # Draw\n gmap.draw(\"results/heatmaps/\" + str(year) + \".html\")\n","sub_path":"maps_plotting.py","file_name":"maps_plotting.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"469479646","text":"# coding:utf-8\n\nimport os\nimport pickle\n\nimport torch\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom typing import Dict\nfrom collections import defaultdict\nfrom torch.utils.data import Dataset\n\nfrom transformers import (\n BertTokenizer,\n DataCollatorForLanguageModeling,\n DataCollatorForWholeWordMask,\n PreTrainedTokenizer,\n BertConfig,\n BertForMaskedLM\n)\nfrom transformers.utils import logging\n\nfrom simple_trainer import Trainer\nfrom pretrain_args import TrainingArguments\n\nwarnings.filterwarnings('ignore')\nlogger = logging.get_logger(__name__)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef read_data(config, train_file_path, test_file_path, tokenizer: BertTokenizer) -> dict:\n train_df = pd.read_csv(train_file_path, header=None, sep='\\t')\n test_df = pd.read_csv(test_file_path, header=None, sep='\\t')\n\n pretrain_df = pd.concat([train_df, test_df], axis=0)\n\n inputs = defaultdict(list)\n for i, row in tqdm(pretrain_df.iterrows(), desc=f'preprocessing pretrain data ... ...', total=len(pretrain_df)):\n sentence_a, sentence_b = row[0], row[1]\n inputs_dict = tokenizer.encode_plus(sentence_a, sentence_b, add_special_tokens=True,\n return_token_type_ids=True, return_attention_mask=True)\n inputs['input_ids'].append(inputs_dict['input_ids'])\n inputs['token_type_ids'].append(inputs_dict['token_type_ids'])\n inputs['attention_mask'].append(inputs_dict['attention_mask'])\n\n data_cache_path = config['data_cache_path']\n\n if not os.path.exists(os.path.dirname(data_cache_path)):\n os.makedirs(os.path.dirname(data_cache_path))\n with open(data_cache_path, 'wb') as f:\n pickle.dump(inputs, f)\n\n return inputs\n\n\nclass LineByLineTextDataset(Dataset):\n def __init__(self, tokenizer: PreTrainedTokenizer, train_file_path: str, test_file_path: str, block_size: int):\n assert os.path.isfile(train_file_path), f\"Input file path {train_file_path} not found\"\n logger.info(f\"Creating features from dataset file at {train_file_path}\")\n\n assert os.path.isfile(test_file_path), f\"Input file path {test_file_path} not found\"\n logger.info(f\"Creating features from dataset file at {test_file_path}\")\n\n with open(train_file_path, encoding=\"utf-8\") as f:\n train_lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]\n\n with open(test_file_path, encoding=\"utf-8\") as f:\n test_lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]\n\n lines = train_lines + test_lines\n\n batch_encoding = tokenizer(lines, add_special_tokens=True, truncation=True, max_length=block_size)\n self.examples = batch_encoding[\"input_ids\"]\n self.examples = [{\"input_ids\": torch.tensor(e, dtype=torch.long)} for e in self.examples]\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i) -> Dict[str, torch.tensor]:\n return self.examples[i]\n\n\ndef main():\n config = {\n 'pretrain_type': 'dynamic_mask', # dynamic_mask, whole_word_mask\n 'data_cache_path': '',\n 'train_data_path': '../data/train.txt',\n 'test_data_path': '../data/test.txt',\n }\n\n mlm_probability = 0.15\n num_train_epochs = 150\n seq_length = 100\n batch_size = 32\n learning_rate = 6e-5\n save_steps = 5000\n seed = 2021\n\n \"\"\"\n if use bert, replace NeZhaForMaskedLM -> BertForMaskedLM, \n NeZhaConfig -> BertConfig\n model_name -> your pretrain_model name\n\n example: \n >> model_name = bert-base-uncased\n model_path = '../pretrain_model/' + model_name + '/pytorch_model.bin'\n config_path = '../pretrain_model/' + model_name + '/config.json'\n vocab_file = '../pretrain_model/' + model_name + '/vocab.txt'\n ... ...\n model_config = BertConfig.from_pretrained(config_path)\n BertForMaskedLM.from_pretrained(pretrained_model_name_or_path=model_path,\n config=model_config)\n \"\"\"\n\n # put dowm your file path\n if config['pretrain_type'] == 'whole_word_mask':\n # https://huggingface.co/hfl/chinese-bert-wwm-ext\n model_name = 'chinese-bert-wwm-ext'\n else:\n # https://huggingface.co/hfl/chinese-macbert-base\n model_name = 'chinese-macbert-base'\n\n config['data_cache_path'] = '../user_data/pretrain/' + config['pretrain_type'] + '/data.pkl'\n\n model_path = '../pretrain_model/' + model_name + '/pytorch_model.bin'\n config_path = '../pretrain_model/' + model_name + '/config.json'\n\n vocab_file = '../pretrain_model/' + model_name + '/vocab.txt'\n tokenizer = BertTokenizer.from_pretrained(vocab_file)\n\n model_config = BertConfig.from_pretrained(config_path)\n\n if config['pretrain_type'] == 'dynamic_mask':\n data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer,\n mlm=True,\n mlm_probability=mlm_probability)\n model = BertForMaskedLM.from_pretrained(pretrained_model_name_or_path=model_path,\n config=model_config)\n model_save_path = 'mlm_model'\n\n if config['pretrain_type'] == 'whole_word_mask':\n data_collator = DataCollatorForWholeWordMask(tokenizer=tokenizer,\n mlm=True,\n mlm_probability=mlm_probability)\n model = BertForMaskedLM.from_pretrained(pretrained_model_name_or_path=model_path,\n config=model_config)\n model_save_path = 'whole_word_mask_model'\n\n dataset = LineByLineTextDataset(tokenizer=tokenizer,\n train_file_path=config['train_data_path'],\n test_file_path=config['test_data_path'],\n block_size=seq_length)\n\n training_args = TrainingArguments(\n output_dir='record',\n num_train_epochs=num_train_epochs,\n learning_rate=learning_rate,\n per_device_train_batch_size=batch_size,\n save_steps=save_steps,\n logging_steps=500,\n save_total_limit=5,\n prediction_loss_only=True,\n seed=seed\n )\n\n trainer = Trainer(\n model=model,\n args=training_args,\n data_collator=data_collator,\n train_dataset=dataset\n )\n\n trainer.train()\n trainer.save_model(model_save_path)\n tokenizer.save_pretrained(model_save_path)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pretrain_code/run_pretrain_bert.py","file_name":"run_pretrain_bert.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"493951179","text":"#!/usr/bin/env python3\n\nimport os\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\nFILENAME = '{}/../input.txt'.format(SCRIPT_PATH)\n\n# Read the challenge input\nwith open(FILENAME, 'r') as input_file:\n PUZZLE_INPUT = input_file.readlines()\n\n# Keypad layout\nlayout = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n\n# Initial position (number 5)\nstart = (1, 1)\ncode = []\n\nfor line in PUZZLE_INPUT:\n for char in line:\n if char == 'L':\n start = (start[0], max(start[1] - 1, 0))\n if char == 'U':\n start = (max(start[0] - 1, 0), start[1])\n if char == 'R':\n start = (start[0], min(start[1] + 1, 2))\n if char == 'D':\n start = (min(start[0] + 1, 2), start[1])\n\n code.append(layout[start[0]][start[1]])\n\nprint('The code for the bathroom is', code)\n","sub_path":"2016/day_02/python/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"9802996","text":"from django.urls import path\nfrom Customer.views import(\n CustomerCreateAPIView,\n CustomerListAPIView,\n CustomerDetailAPIView\n)\n\nurlpatterns = [\npath('create', CustomerCreateAPIView.as_view()),\npath('all', CustomerListAPIView.as_view()),\npath('detail/', CustomerDetailAPIView.as_view())\n]","sub_path":"Customer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"335309259","text":"import re\n\n\nclass StepFinder():\n def __init__(self, os_interface):\n self.os_interface = os_interface\n self.steps = []\n\n def find_all_steps(self):\n self.steps = []\n\n all_step_files = self.os_interface.get_files()\n for filename in all_step_files:\n self._find_steps_in_file(filename)\n\n return self.steps\n\n def match(self, text):\n matches = []\n for (step, index, filename) in self.steps:\n class SubstituteCounter:\n def __init__(self):\n self.count = 0\n\n def substitute_variable(self, m):\n self.count += 1\n return \"$\" + str(self.count)\n\n counter = SubstituteCounter()\n\n step_label = re.sub(r'^@(.*)\\([\"\\'](.*)[\"\\']\\)', r'\\1 \\2', step)\n step_usage = re.sub(r'\\{[^}]+\\}', counter.substitute_variable, step_label)\n if self._match_step_to_text(text, step_usage):\n matches.append((step_label, self._strip_to_text_placement(text, step_usage)))\n return sorted(matches)\n\n def _find_steps_in_file(self, filename):\n lines = self.os_interface.open(filename)\n for linenumber in range(len(lines)):\n match = self._line_is_a_step(lines[linenumber])\n if match:\n self.steps.append((match.group(), linenumber, filename))\n elif lines[linenumber].strip() and (linenumber + 1) < len(lines):\n line = self._double_line_is_a_step(lines[linenumber].strip() + lines[linenumber+1].strip())\n if line:\n self.steps.append((line, linenumber, filename))\n\n def _line_is_a_step(self, text):\n pattern = re.compile(r'(@(.+)(\\([\"\\'].+))[\"\\']\\)')\n return re.match(pattern, text)\n\n def _double_line_is_a_step(self, double_line):\n pattern = re.compile(r'@(.+)\\([\"\\'](.+)[\"\\'][\"\\'](.+)[\"\\']\\)')\n match = re.match(pattern, double_line)\n if match:\n return \"@{0}('{1}{2}')\".format(match.group(1), match.group(2), match.group(3))\n return False\n\n def _match_step_to_text(self, text, step_usage):\n step_usage_matcher = step_usage[:len(text)]\n return text.lower() == step_usage_matcher.lower()\n\n def _strip_to_text_placement(self, prefix, full_step):\n \"\"\" Remove last word from prefix \"\"\"\n if re.search(r'\\s', prefix):\n prefix = re.sub(r'(.*)\\s[^\\s]+$', r'\\1', prefix)\n return full_step[len(prefix):].strip()\n return full_step\n","sub_path":"step_finder.py","file_name":"step_finder.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"637875712","text":"import nltk\nimport pandas as pd\nimport pickle\nimport sys\nfrom collections import defaultdict\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.metrics.scores import precision, recall, f_measure\nfrom nltk.stem.porter import PorterStemmer\nfrom sklearn.naive_bayes import MultinomialNB,BernoulliNB\nfrom sklearn.linear_model import LogisticRegression,SGDClassifier\nfrom sklearn.svm import LinearSVC\nfrom random import shuffle\n\n\ninfile = open(f\"Test/all_freq_ngrams\", 'rb')\n\nfreq_ngrams = pickle.load(infile)\nword_features = [w for (w, f) in freq_ngrams.most_common(2000)]\ninfile.close()\n\ninfile = open(\"Test/train_all\", 'rb')\ntrain_ngrams = pickle.load(infile)\n'''tuple with essay_unigrams, essay_bigrams and essay_trigrams\nto access unigrams, just ngram_tuple[0][\"essay0\"]'''\ninfile.close()\n\ninfile = open(\"Test/dev_all\", 'rb')\ndev_ngrams = pickle.load(infile)\ninfile.close()\n\ndef label_func(l, cdl):\n if l == \"sex\" or cdl == \"white\":\n return cdl\n elif l == \"age\":\n if cdl <= 30:\n return \"u_30\"\n else:\n return \"o_30\"\n else:\n return \"n-white\"\n\ndef document_features(document):\n document_words = set(document)\n features = {}\n for word in word_features:\n features['contains({})'.format(word)] = (word in document_words)\n return features\n\ndef bayes(essay, label):\n train_features = [(document_features(t), label_func(label, class_dic[label])) for (t, class_dic) in train_ngrams[essay]]\n dev_features = [(document_features(t), label_func(label, class_dic[label])) for (t, class_dic) in dev_ngrams[essay]]\n shuffle(train_features)\n shuffle(dev_features)\n training_set, testing_set = train_features, dev_features\n classifier = nltk.NaiveBayesClassifier.train(training_set)\n print(\"Naive Bayes accuracy percent:\", (nltk.classify.accuracy(classifier, testing_set))*100)\n lab = set(classifier.most_informative_features(100))\n \n\n '''predictions, gold_labels = defaultdict(set), defaultdict(set)\n for i, (features, label) in enumerate(testing_set):\n predictions[classifier.classify(features)].add(i)\n gold_labels[label].add(i)\n for label in predictions:\n print(label, 'Precision:', precision(gold_labels[label], predictions[label]))\n print(label, 'Recall:', recall(gold_labels[label], predictions[label]))\n print(label, 'F1-Score:', f_measure(gold_labels[label], predictions[label]))\n print()\n \n MNB_classifier = SklearnClassifier(MultinomialNB())\n MNB_classifier.train(training_set)\n print(\"MNB_classifier accuracy percent:\", (nltk.classify.accuracy(MNB_classifier, testing_set))*100)\n\n BernoulliNB_classifier = SklearnClassifier(BernoulliNB())\n BernoulliNB_classifier.train(training_set)\n print(\"BernoulliNB_classifier accuracy percent:\", (nltk.classify.accuracy(BernoulliNB_classifier, testing_set))*100)\n\n LogisticRegression_classifier = SklearnClassifier(LogisticRegression(max_iter = 150))\n LogisticRegression_classifier.train(training_set)\n print(\"LogisticRegression_classifier accuracy percent:\", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set))*100)\n\n SGDClassifier_classifier = SklearnClassifier(SGDClassifier())\n SGDClassifier_classifier.train(training_set)\n print(\"SGDClassifier_classifier accuracy percent:\", (nltk.classify.accuracy(SGDClassifier_classifier, testing_set))*100)\n\n LinearSVC_classifier = SklearnClassifier(LinearSVC(max_iter=1200))\n LinearSVC_classifier.train(training_set)\n print(\"LinearSVC_classifier accuracy percent:\", (nltk.classify.accuracy(LinearSVC_classifier, testing_set))*100)'''\n return lab\n\ndef main():\n sex = bayes(\"essay4\", \"sex\")\n age = bayes(\"essay4\", \"age\")\n et = bayes(\"essay4\", \"ethnicity\")\n \n print(\"Intersection sex-age:\", sex.intersection(age))\n print(\"Intersection et-age:\", et.intersection(age))\n print(\"Intersection sex-et:\", sex.intersection(et))\n print(\"Intersection all:\", et.intersection(sex.intersection(age)))\n\nif __name__ == '__main__':\n main()","sub_path":"okcupidtest.py","file_name":"okcupidtest.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"278008676","text":"from pajbot.apiwrappers.base import BaseAPI\n\n\nclass TwitchTMIAPI(BaseAPI):\n def __init__(self):\n super().__init__(base_url=\"https://tmi.twitch.tv/\")\n\n def get_chatter_logins_by_login(self, login):\n response = self.get([\"group\", \"user\", login, \"chatters\"])\n all_chatters = []\n\n for chatter_category in response[\"chatters\"].values():\n all_chatters.extend(chatter_category)\n\n return all_chatters\n","sub_path":"pajbot/apiwrappers/twitch/tmi.py","file_name":"tmi.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"246160262","text":"import numpy as np\nimport pandas as pd\n\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\n\nimport re\nfrom scipy.sparse import hstack\n\nfrom sklearn import preprocessing, model_selection, metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import f1_score, make_scorer\n\nimport os\nprint(os.listdir(\"../input/\"))\n\n# Load Data\nprint(\"Loading data...\")\n\ntrain = pd.read_csv('../input/labeledTrainData.tsv', sep=\"\\t\")\nprint(\"Train shape:\", train.shape)\ntest = pd.read_csv('../input/testData.tsv', sep=\"\\t\")\nprint(\"Test shape:\", test.shape)\n\nsample = pd.read_csv('../input/sampleSubmission.csv', sep=\",\")\n\n\nprint(train.head())\nprint(test.head())\nprint(sample.head())\n\nprint(\"Value counts of sentiment class\", train['sentiment'].value_counts()) # balanced dataset\n\n# Check the first review\nprint('The first review is:\\n\\n',train[\"review\"][0])\n\n# clean description\nprint(\"Cleaning train data...\\n\")\ntrain['review'] = train['review'].map(lambda x: BeautifulSoup(x).get_text())\nprint(\"Cleaning test data...\")\ntest['review'] = test['review'].map(lambda x: BeautifulSoup(x).get_text())\n\n\n# function to clean data\n\nstops = set(stopwords.words(\"english\"))\ndef cleanData(text, lowercase = False, remove_stops = False, stemming = False):\n txt = str(text)\n txt = re.sub(r'[^A-Za-z0-9\\s]',r'',txt)\n txt = re.sub(r'\\n',r' ',txt)\n\n if lowercase:\n txt = \" \".join([w.lower() for w in txt.split()])\n\n if remove_stops:\n txt = \" \".join([w for w in txt.split() if w not in stops])\n\n if stemming:\n st = PorterStemmer()\n txt = \" \".join([st.stem(w) for w in txt.split()])\n\n return txt\n\ny = train['sentiment']\n\n# Bag of Words (word based)\nctv_word = CountVectorizer(analyzer='word',token_pattern=r'\\w{1,}',min_df = 200, max_features=5000,\n ngram_range=(1,2), stop_words = 'english')\n\nprint(\"Fitting Bag of Words Model on words...\\n\")\n# Fitting CountVectorizer to both training and test sets\nctv_word.fit(list(train['review']) + list(test['review']))\ntrain_ctv_word = ctv_word.transform(train['review'])\ntest_ctv_word = ctv_word.transform(test['review'])\n\nprint(\"Fitting Bag of Words Model on characters...\\n\")\n\n# Bag of words (charater based)\nctv_char = TfidfVectorizer(sublinear_tf=True, strip_accents='unicode',analyzer='char',\n stop_words='english', ngram_range=(2, 6), max_features=10000)\n\n# Fitting CountVectorizer to both training and test sets\nctv_char.fit(list(train['review']) + list(test['review']))\ntrain_ctv_char = ctv_char.transform(train['review'])\ntest_ctv_char = ctv_char.transform(test['review'])\n\n# TF - IDF (words)\n\nprint(\"Fitting TF-IDF Model on words...\\n\")\ntfv_word = TfidfVectorizer(min_df=150, max_features= 5000,\n strip_accents='unicode', analyzer='word',token_pattern=r'\\w{1,}',\n ngram_range=(1,2),\n stop_words = 'english')\n\n# Fitting TF-IDF to both training and test sets (semi-supervised learning)\ntfv_word.fit(list(train['review']) + list(test['review']))\ntrain_tfv_word = tfv_word.transform(train['review'])\ntest_tfv_word = tfv_word.transform(test['review'])\n\n# TF-IDF(char)\nprint(\"Fitting TF - IDF Model on characters...\\n\")\ntfv_char = TfidfVectorizer(sublinear_tf=True,strip_accents='unicode',analyzer='char',\n stop_words='english',ngram_range=(2, 6),max_features=10000)\ntfv_char.fit(list(train['review']) + list(test['review']))\ntrain_tfv_char = tfv_char.transform(train['review'])\ntest_tfv_char = tfv_char.transform(test['review'])\n\nprint(\"Combining Bag of words for words and characters...\\n\")\n# bag of words for training set (words + char)\ntrain_bow = hstack([train_ctv_word, train_ctv_char])\ntest_bow = hstack([test_ctv_word, test_ctv_char])\n\nprint(\"Combining TF-IDF for words and characters...\\n\")\n\n# TF-IDF for test set (words + char)\ntrain_tfidf = hstack([train_tfv_word, train_tfv_char])\ntest_tfidf = hstack([test_tfv_word, test_tfv_char])\n\nclf_lr = LogisticRegression() # Logistic Regression Model\n\n## 5-fold cross validation\nprint(cross_val_score(clf_lr, train_tfidf, y, cv=5, scoring=make_scorer(f1_score)))\n\n\"\"\"\nWe can see that we are achieving an validation accuracy of 89%.\n\"\"\"\n# Fit the logistic regression model\nclf_lr.fit(train_tfidf,y)\n\n# Make predictions on test data\npreds = clf_lr.predict(test_tfidf)\n\n# Make submission\n\nsample['sentiment'] = preds\nsample = sample[['id','sentiment']]\nsample.to_csv('submissions.csv',index=False)\n","sub_path":"Bag of Words Meets Bag of Popcorn/scripts/bowandtfidf_v1.py","file_name":"bowandtfidf_v1.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"556206113","text":"#!/usr/bin/env python3\n\nimport csv\nimport itertools as it\nimport os\nimport numpy as np\nfrom numpy.random import default_rng\nfrom sklearn.linear_model import Ridge, LinearRegression\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\n\ndef main():\n X, Y = get_wine_data()\n # X, Y = get_random_data()\n X, _ = normalize(X)\n A, c = RR(X, Y)\n print(pretty_function(c))\n print('Q =', quality(Y, A))\n\n alphas = []\n qualitiesR = []\n# qualitiesL = []\n# qL = quality(Y, LR(X, Y)[0])\n begin = 0.001\n end = 1.0\n steps = 100\n for i in range(steps):\n alpha = begin + (end - begin) / steps * i\n alphas.append(alpha)\n qualitiesR.append(quality(Y, RR(X, Y, alpha = alpha)[0]))\n# qualitiesL.append(qL)\n \n plt.figure(figsize=(15, 10))\n plt.plot(alphas, qualitiesR, color = 'magenta', label = 'Q over alpha')\n# plt.plot(alphas, qualitiesL, color = 'cyan', label = 'Q for LL')\n plt.legend(loc = 'upper right')\n plt.show()\n\ndef get_wine_data():\n # data_path = os.path.join(os.path.dirname(__file__), './LR_wine_data/winequality-red.csv')\n data_path = os.path.join(os.path.dirname(__file__), './LR_wine_data/winequality-white.csv')\n data_file = open(data_path,'r')\n data_reader = csv.reader(data_file, delimiter=';')\n\n header = data_reader.__next__()\n # print('header: ', header)\n wine_data = list(map(lambda c: [float(e) for e in c], data_reader))\n data_file.close()\n\n X = np.array(list(map(lambda c: c[:-1], wine_data)))\n Y = np.array(list(map(lambda c: c[-1], wine_data)))\n return X, Y\n\ndef get_random_data():\n n_samples = 500\n n_features = 5\n n_redundant = 2\n rng = default_rng()\n\n Y = rng.random(n_samples)\n X = np.zeros(shape = (n_samples, n_features + n_redundant))\n base = rng.random((n_samples, n_features))\n X[:n_samples, :n_features] = base\n\n for i in range(n_redundant):\n X[:, n_features + i] = X[:, i] + (-0.05 + rng.random(size = n_samples) * 0.1)\n\n return X, Y\n\ndef quality(A, B):\n n = len(A)\n\n err = 0.0\n for i in range(n):\n err += pow(A[i] - B[i], 2)\n \n return err\n\ndef normalize(X):\n scaler = MinMaxScaler()\n scaler.fit(X)\n return scaler.transform(X), scaler\n\ndef pretty_function(coefs):\n res = 'y = '\n res += ' + '.join([f'x{i+1} * {coefs[i]:.3f}' for i in range(len(coefs))])\n return res\n\ndef RR(X, Y, alpha = 1.0):\n model = Ridge(alpha = alpha, fit_intercept = False)\n model.fit(X, Y)\n \n return model.predict(X), model.coef_\n\n# def LR(X, Y):\n\n# model = LinearRegression()\n# model.fit(X, Y)\n\n# return model.predict(X), model.coef_\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"prac/RidgeRegression.py","file_name":"RidgeRegression.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"529931372","text":"import entities\r\nimport occ_grid\r\nimport math\r\n\r\n\r\ndef distance(rob, mon):\r\n return math.sqrt((rob.position.x-mon.position.x)**2+(rob.position.y-mon.position.y)**2)\r\n\r\ndef farthest(robber, moneys):\r\n far = robber\r\n for entitie in moneys:\r\n if distance(robber, entitie) > distance(robber, far):\r\n far = entitie\r\n return far\r\n\r\ndef nearest(robber, moneys):\r\n near = entities.Money(\"Dollar\", entities.Point(100000000,100000000))\r\n for entitie in moneys:\r\n if distance(robber, entitie) < distance(robber, near):\r\n near = entitie\r\n return near\r\n\r\ndef makeRobberGo(robbers, Money):\r\n if robbers.moving:\r\n if robbers.far:\r\n goto = robbers.wheretogo\r\n determineNewGathererPosition(robbers, goto)\r\n else:\r\n goto = robbers.wheretogo\r\n determineNewGathererPosition(robbers, goto)\r\n\r\ndef determineNewGathererPosition(Robbers, Money):\r\n if Robbers.position.x < Money.position.x:\r\n Robbers.position.x = Robbers.position.x + 1\r\n elif Robbers.position.x > Money.position.x:\r\n Robbers.position.x = Robbers.position.x - 1\r\n else:\r\n if Robbers.position.y < Money.position.y:\r\n Robbers.position.y = Robbers.position.y + 1\r\n elif Robbers.position.y > Money.position.y:\r\n Robbers.position.y = Robbers.position.y - 1\r\n \r\ndef robber_trail(grid):\r\n for x in range(0, 59):\r\n for y in range(0, 59):\r\n if occ_grid.get_cell(grid, entities.Point(x, y)) == occ_grid.GATHERER:\r\n occ_grid.set_cell(grid, entities.Point(x, y), occ_grid.TRAIL)","sub_path":"hw4/movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"371055462","text":"#App Engine Models\n\nfrom google.appengine.ext import db\nimport string\n\nclass Person(db.Model):\n \"\"\"Models a person in the RPI directory.\"\"\"\n first_name = db.StringProperty()\n middle_name = db.StringProperty()\n last_name = db.StringProperty()\n department = db.StringProperty()\n email = db.StringProperty()\n rcsid = db.StringProperty()\n year = db.StringProperty()\n major = db.StringProperty()\n title = db.StringProperty()\n phone = db.StringProperty()\n fax = db.StringProperty()\n homepage = db.StringProperty()\n office_location = db.StringProperty(multiline=True)\n campus_mailstop = db.StringProperty(multiline=True)\n mailing_address = db.StringProperty(multiline=True)\n date_crawled = db.DateTimeProperty(auto_now=True)\n directory_id = 0\n \n @staticmethod\n def buildPerson(d):\n person = Person()\n \n if 'email' in d:\n rcsid = string.rsplit(d['email'],'@',1)[0]\n person = Person(key_name = rcsid)\n person.rcsid = rcsid\n elif 'name' in d:\n person = Person(key_name = d['name'])\n person.rcsid = d['name']\n else:\n # No name for the person, no point in making them\n person = Person()\n return person\n \n if 'name' in d:\n names = d['name'].split()[:3]\n if len(names) > 0:\n person.first_name = names[0]\n if len(names) > 1:\n person.last_name = names[-1]\n #if len(names) > 2:\n #person.middle_name = names[1]\n if 'email' in d:\n person.email = d['email']\n person.key_name = d['email']\n if 'year' in d:\n person.year = d['year']\n if 'major' in d:\n person.major = d['major']\n if 'department' in d:\n person.department = d['department']\n if 'title' in d:\n person.title = d['title']\n if 'phone' in d:\n person.phone = d['phone']\n if 'fax' in d:\n person.fax = d['fax']\n if 'homepage' in d:\n person.homepage = d['homepage']\n if 'office_location' in d:\n person.office_location = d['office_location']\n if 'campus_mailstop' in d:\n person.campus_mailstop = d['campus_mailstop']\n if 'mailing_address' in d:\n person.mailing_address = d['mailing_address']\n if 'directory_id' in d:\n person.directory_id = d['directory_id']\n \n return person\n \n @staticmethod\n def buildMap(p):\n \n d = {}\n \n if p.email is not None:\n d['email'] = p.email\n if p.rcsid is not None:\n d['rcsid'] = p.rcsid\n \n name = ''\n if p.first_name is not None:\n name += p.first_name.title()\n #if p.middle_name is not None:\n #name += ' ' + p.middle_name.title()\n if p.last_name is not None:\n name += ' ' + p.last_name.title()\n if name is not \"\":\n d['name'] = name\n \n if p.year is not None:\n d['year'] = p.year.title()\n \n if p.major is not None:\n d['major'] = p.major.title()\n \n if p.department is not None:\n d['department'] = p.department.title()\n \n if p.title is not None:\n d['title'] = p.title.title()\n \n if p.phone is not None:\n d['phone'] = p.phone.title()\n \n if p.fax is not None:\n d['fax'] = p.fax.title()\n \n if p.homepage is not None:\n d['homepage'] = p.homepage.title()\n \n if p.office_location is not None:\n d['office_location'] = p.office_location.title()\n \n if p.campus_mailstop is not None:\n d['campus_mailstop'] = p.campus_mailstop.title()\n \n if p.mailing_address is not None:\n d['mailing_address'] = p.mailing_address.title()\n \n if p.directory_id is not None:\n d['directory_id'] = p.directory_id\n \n return d\n \n \n\nclass SearchPosition(db.Model):\n \"\"\"Model to store Crawler position.\"\"\"\n position = db.IntegerProperty()\n\n#class DepartmentKeyword(db.Model):\n #\"\"\"Model to store a single work from a major, for searching purposes\"\"\"\n #departments = db.ListProperty\n \n #@staticmethod\n #def buildKeywords(s):\n #for word in s.split():\n #d = DepartmentKeyword.get_by_key_name(word)\n #if not d:\n #w = DepartmentKeyword(key_name = word)\n #w.department = [s]\n #w.put()\n #elif s not in d.departments:\n #d.departments.append(s)\n #d.put()","sub_path":"appengine/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"109411359","text":"__author__ = 'ma0722'\nclass Solution:\n\n def print_range(self, nums, start, end):\n if start != end:\n return str(nums[start])+'->'+str(nums[end])\n else:\n return str(nums[start])\n\n # @param {integer[]} nums\n # @return {string[]}\n def summaryRanges(self, nums):\n list_range = []\n start = 0\n end = 0\n if len(nums)-1 == 0:\n list_range.append(self.print_range(nums,0,0))\n for i in range(0, len(nums)-1):\n if nums[i+1] != nums[i]+1:\n end = i\n list_range.append(self.print_range(nums,start,end))\n start = i+1\n if i == len(nums)-2:\n end = len(nums)-1\n list_range.append(self.print_range(nums,start,end))\n return list_range\n\nif __name__ == '__main__':\n s = Solution()\n print(s.summaryRanges([-1,0]))","sub_path":"ok_p_228.py","file_name":"ok_p_228.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"192992247","text":"__author__ = 'Administrator'\nimport cv2\nimport numpy as np\n\nfn=\"620.jpg\"\n\ndef get_EuclideanDistance(x,y):\n myx = np.array(x)\n myy = np.array(y)\n sum = np.sqrt(np.sum(myx-myy)*(myx-myy))\n return sum\n\nif __name__ == '__main__':\n\n print('loading %s ....'%fn)\n print('working')\n myimg1 = cv2.imread(fn)\n w = myimg1.shape[1]\n h = myimg1.shape[0]\n sz1=w\n sz0=h\n\n myimg2 = np.zeros((sz0,sz1,3),np.uint8)\n\n black = np.array([0,0,0])\n white = np.array([255,255,255])\n centercolor = np.array([125,125,125])\n for y in xrange(0,sz0-1):\n for x in xrange(0,sz1-1):\n\n mydown = myimg1[y+1,x,:]\n myright= myimg1[y,x+1,:]\n\n myhere = myimg1[y,x,:]\n lmyhere = myhere\n lmyright = myright\n lmydown = mydown\n if ((get_EuclideanDistance(lmyhere,lmydown)>16)-(get_EuclideanDistance(lmyhere,lmyright)>16)).all():\n myimg2[y,x:] = black\n elif ((get_EuclideanDistance(lmyhere,lmydown)<=16)-(get_EuclideanDistance(lmyhere,lmyright)<=16)).all():\n myimg2[y,x,:] = white\n else:\n myimg2[y,x,:] = centercolor\n\n print('.')\n\n cv2.namedWindow('img2')\n cv2.imshow('img2',myimg2)\n cv2.waitKey()\n cv2.destoryAllWindows()\n\n\n\n\n\n\n\n\n\n","sub_path":"remote_cal/org/xu/img/border/blkandwht.py","file_name":"blkandwht.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"307344744","text":"\nimport numpy as np\nimport chainer as ch\n\nclass Model:\n '''\n Base class for model objects.\n '''\n\n def __init__(self, name=None):\n self.name = name\n\n def l_imp(self, w=None, X=None, y=None, lamreg=None):\n return None\n \n def l_tr(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.l_imp(w=w, X=data.X_tr,\n y=data.y_tr,\n lamreg=lamreg)\n else:\n return self.l_imp(w=w, X=data.X_tr[n_idx,:],\n y=data.y_tr[n_idx,:],\n lamreg=lamreg)\n \n def l_te(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.l_imp(w=w, X=data.X_te,\n y=data.y_te,\n lamreg=lamreg)\n else:\n return self.l_imp(w=w, X=data.X_te[n_idx,:],\n y=data.y_te[n_idx,:],\n lamreg=lamreg)\n\n def g_imp(self, w=None, X=None, y=None, lamreg=None):\n return None\n \n def g_tr(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_imp(w=w, X=data.X_tr,\n y=data.y_tr,\n lamreg=lamreg)\n else:\n return self.g_imp(w=w, X=data.X_tr[n_idx,:],\n y=data.y_tr[n_idx,:],\n lamreg=lamreg)\n \n def g_te(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_imp(w=w, X=data.X_te,\n y=data.y_te,\n lamreg=lamreg)\n else:\n return self.g_imp(w=w, X=data.X_te[n_idx,:],\n y=data.y_te[n_idx,:],\n lamreg=lamreg)\n\n\nclass LinReg(Model):\n '''\n General-purpose linear regression model.\n No losses are implemented, just a predict()\n method.\n '''\n \n def __init__(self, data=None, name=None):\n super(LinReg, self).__init__(name=name)\n pass\n\n def predict(self, w, X):\n '''\n Predict real-valued response.\n w is a (d x 1) array of weights.\n X is a (k x d) matrix of k observations.\n Returns array of shape (k x 1) of predicted values.\n '''\n return X.dot(w)\n\n\nclass LinearL2(LinReg):\n '''\n Orthodox linear regression model, using squared\n error and regularization via the l2 norm.\n '''\n \n def __init__(self, data=None):\n super(LinearL2,self).__init__(data=data)\n\n \n def l_imp(self, w, X, y, lamreg=None):\n '''\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n y is a (k x 1) matrix of labels in {-1,1}.\n lamreg is a regularization parameter (l2 penalty).\n\n Output:\n A vector of length k with losses evaluated at k points.\n '''\n if lamreg is None:\n return (y-self.predict(w=w,X=X))**2/2\n else:\n penalty = lamreg * np.linalg.norm(w)**2\n return (y-self.predict(w=w,X=X))**2/2 + penalty\n \n \n def g_imp(self, w, X, y, lamreg=None):\n '''\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n y is a (k x 1) matrix of labels in {-1,1}.\n\n Output:\n A (k x numfeat) matrix of gradients evaluated\n at k points.\n '''\n if lamreg is None:\n return (y-self.predict(w=w,X=X))*(-1)*X\n else:\n penalty = lamreg*2*w.T\n return (y-self.predict(w=w,X=X))*(-1)*X + penalty\n\nclass LinearL1(LinReg):\n '''\n Orthodox linear regression model, using squared\n error and regularization via the l1 norm. Good for\n realizing sparsity without giving up convexity.\n '''\n \n def __init__(self, data=None):\n super(LinearL1,self).__init__(data=data)\n\n \n def l_imp(self, w, X, y, lamreg=None):\n '''\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n y is a (k x 1) matrix of labels in {-1,1}.\n lamreg is a regularization parameter (l2 penalty).\n\n Output:\n A vector of length k with losses evaluated at k points.\n '''\n if lamreg is None:\n return (y-self.predict(w=w,X=X))**2/2\n else:\n penalty = lamreg * np.abs(w).sum()\n return (y-self.predict(w=w,X=X))**2/2 + penalty\n\n \n def g_j_imp(self, j, w, X, y, lamreg=None):\n\n if lamreg is None:\n return (y-self.predict(w=w,X=X))*(-1)*np.take(a=X,\n indices=[j],\n axis=1)\n else:\n penalty = lamreg * np.sign(w[j,0])\n return (y-self.predict(w=w,X=X))*(-1)*np.take(a=X,\n indices=[j],\n axis=1) + penalty\n \n def g_j_tr(self, j, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_j_imp(j=j, w=w, X=data.X_tr,\n y=data.y_tr,\n lamreg=lamreg)\n else:\n return self.g_j_imp(j=j, w=w, X=data.X_tr[n_idx,:],\n y=data.y_tr[n_idx,:],\n lamreg=lamreg)\n \n def g_j_te(self, j, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_j_imp(j=j, w=w, X=data.X_te,\n y=data.y_te,\n lamreg=lamreg)\n else:\n return self.g_j_imp(j=j, w=w, X=data.X_te[n_idx,:],\n y=data.y_te[n_idx,:],\n lamreg=lamreg)\n\n\nimport models\n\nclass Classifier(models.Model):\n '''\n Generic classifier model, an object with methods\n for both training and evaluating classifiers.\n '''\n\n def __init__(self, data=None, name=None):\n super(Classifier, self).__init__(name=name)\n\n # If given data, collect information about labels.\n if data is not None:\n self.labels = self.get_labels(data=data) # all unique labels.\n self.nc = self.labels.size # number of unique labels.\n\n\n def onehot(self, y):\n '''\n A function for encoding y into a one-hot vector.\n Inputs:\n - y is a (k,1) array, taking values in {0,1,...,nc-1}.\n '''\n nc = self.nc\n k = y.shape[0]\n C = np.zeros((k,nc), dtype=y.dtype)\n\n for i in range(k):\n j = y[i,0] # assumes y has only one column.\n C[i,j] = 1\n\n return C\n \n\n def get_labels(self, data):\n '''\n Get all the (unique) labels that appear in the data.\n '''\n A = (data.y_tr is None)\n B = (data.y_te is None)\n\n if (A and B):\n raise ValueError(\"No label data provided!\")\n else:\n if A:\n out_labels = np.unique(data.y_te)\n elif B:\n out_labels = np.unique(data.y_tr)\n else:\n out_labels = np.unique(np.concatenate((data.y_tr,\n data.y_te), axis=0))\n count = out_labels.size\n return out_labels.reshape((count,1))\n\n\n def classify(self, X):\n '''\n Returns None by default.\n Must be implemented by sub-classes.\n '''\n return None\n\n\n def class_perf(self, y_est, y_true):\n '''\n Given class label estimates and true values,\n compute the fraction of correct classifications\n made for each label, yielding typical binary\n classification performance metrics.\n\n Input:\n y_est and y_true are (k x 1) matrices of labels.\n\n Output:\n Returns a dictionary with two components, (1) being\n the fraction of correctly classified labels, and\n (2) being a dict of per-label precison/recall/F1\n scores. \n '''\n \n # First, get the classification rate.\n k = y_est.size\n num_correct = (y_est == y_true).sum()\n frac_correct = num_correct / k\n frac_incorrect = 1.0 - frac_correct\n\n # Then, get precision/recall for each class.\n prec_rec = { i:None for i in range(self.nc) } # initialize\n\n for c in range(self.nc):\n\n idx_c = (y_true == c)\n idx_notc = (idx_c == False)\n\n TP = (y_est[idx_c] == c).sum()\n FN = idx_c.sum() - TP\n FP = (y_est[idx_notc] == c).sum()\n TN = idx_notc.sum() - FP\n\n # Precision.\n if (TP == 0 and FP == 0):\n prec = 0\n else:\n prec = TP / (TP+FP)\n\n # Recall.\n if (TP == 0 and FN == 0):\n rec = 0\n else:\n rec = TP / (TP+FN)\n\n # F1 (harmonic mean of precision and recall).\n if (prec == 0 or rec == 0):\n f1 = 0\n else:\n f1 = 2 * prec * rec / (prec + rec)\n\n prec_rec[c] = {\"P\": prec,\n \"R\": rec,\n \"F1\": f1}\n\n return {\"rate\": frac_incorrect,\n \"PRF1\": prec_rec}\n\n\nclass LogisticReg(Classifier):\n '''\n Multi-class logistic regression model.\n '''\n\n def __init__(self, data=None):\n \n # Given data info, load up the (X,y) data.\n super(LogisticReg, self).__init__(data=data)\n \n # Convert original labels to a one-hot binary representation.\n if data.y_tr is not None:\n self.C_tr = self.onehot(y=data.y_tr)\n if data.y_te is not None:\n self.C_te = self.onehot(y=data.y_te)\n \n \n def classify(self, w, X):\n '''\n Given learned weights (w) and a matrix of one or\n more observations, classify them as {0,...,nc-1}.\n\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n NOTE: k can be anything, the training/test sample size.\n\n Output:\n A vector of length k, housing labels in {0,...,nc-1}.\n '''\n \n k, numfeat = X.shape\n A = np.zeros((self.nc,k), dtype=np.float64)\n \n # Get activations, with last row as zeros.\n A[:-1,:] = w.reshape((self.nc-1, numfeat)).dot(X.T)\n \n # Now convert activations to conditional probabilities.\n A = np.exp(A)\n A = A / A.sum(axis=0) # (nc x k).\n \n # Assign classes with highest probability, (k x 1) array.\n return A.argmax(axis=0).reshape((k,1))\n\n\n def l_imp(self, w, X, C, lamreg=None):\n '''\n Implementation of the multi-class logistic regression\n loss function.\n\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n C is a (k x nc) matrix giving a binarized encoding of the\n class labels for each observation; each row a one-hot vector.\n lam is a non-negative regularization parameter.\n NOTE: k can be anything, the training/test sample size.\n\n Output:\n A vector of length k with losses evaluated at k points.\n '''\n \n k, numfeat = X.shape\n A = np.zeros((self.nc,k), dtype=np.float64)\n \n # Get activations, with last row as zeros.\n A[:-1,:] = w.reshape((self.nc-1, numfeat)).dot(X.T)\n \n # Raw activations of all the correct weights.\n cvec = (A*C.T).sum(axis=0)\n \n # Compute the negative log-likelihoods.\n err = np.log(np.exp(A).sum(axis=0))-cvec\n\n # Return the losses (all data points), with penalty if needed.\n if lamreg is None:\n return err\n else:\n penalty = lamreg * np.linalg.norm(W)**2\n return err + penalty\n \n \n def l_tr(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.l_imp(w=w, X=data.X_tr,\n C=self.C_tr,\n lamreg=lamreg)\n else:\n return self.l_imp(w=w, X=data.X_tr[n_idx,:],\n C=self.C_tr[n_idx,:],\n lamreg=lamreg)\n \n def l_te(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.l_imp(w=w, X=data.X_te,\n C=self.C_te,\n lamreg=lamreg)\n else:\n return self.l_imp(w=w, X=data.X_te[n_idx,:],\n C=self.C_te[n_idx,:],\n lamreg=lamreg)\n \n \n def g_imp(self, w, X, C, lamreg=0):\n '''\n Implementation of the gradient of the loss function used in\n multi-class logistic regression.\n\n Input:\n w is a (d x 1) matrix of weights.\n X is a (k x numfeat) matrix of k observations.\n C is a (k x nc) matrix giving a binarized encoding of the\n class labels for each observation; each row a one-hot vector.\n lamreg is a non-negative regularization parameter.\n NOTE: k can be anything, the training/test sample size.\n\n Output:\n A (k x d) matrix of gradients eval'd at k points.\n '''\n \n k, numfeat = X.shape\n A = np.zeros((self.nc,k), dtype=np.float64)\n \n # Get activations, with last row as zeros.\n A[:-1,:] = w.reshape((self.nc-1, numfeat)).dot(X.T)\n \n # Now convert activations to conditional probabilities.\n A = np.exp(A)\n A = A / A.sum(axis=0) # (nc x k).\n A = np.float32(A)\n \n # Initialize a large matrix (k x d) to house per-point grads.\n G = np.zeros((k,w.size), dtype=w.dtype)\n\n for i in range(k):\n # A very tall vector (i.e., just one \"axis\").\n G[i,:] = np.kron(a=(A[:-1,i]-C[i,:-1]), b=X[i,:])\n # Note we carefully remove the last elements.\n \n if lamreg is None:\n return G\n else:\n return G + lamreg*2*w.T\n \n\n def g_tr(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_imp(w=w, X=data.X_tr,\n C=self.C_tr,\n lamreg=lamreg)\n else:\n return self.g_imp(w=w, X=data.X_tr[n_idx,:],\n C=self.C_tr[n_idx,:],\n lamreg=lamreg)\n \n def g_te(self, w, data, n_idx=None, lamreg=None):\n if n_idx is None:\n return self.g_imp(w=w, X=data.X_te,\n C=self.C_te,\n lamreg=lamreg)\n else:\n return self.g_imp(w=w, X=data.X_te[n_idx,:],\n C=self.C_te[n_idx,:],\n lamreg=lamreg)\n\n\n# Chainer-related models.\n\n# FunctionNode sub-class, for implementing a fully connected linear layer.\n\nclass LinearFunction(ch.function_node.FunctionNode):\n '''\n FunctionNode object, defined on Variable objects,\n which is the basis for a linear transformation to\n be wrapped up as a Link object.\n \n Take d-dimensional inputs x, and using array W of\n shape (k,d), map this input to k outputs. That is,\n we have a fully-connected layer with d input units\n and k output units.\n '''\n \n def forward(self, inputs):\n '''\n Forward computation for both CPU and GPU.\n '''\n \n # Unpack the tuple of inputs.\n if len(inputs) == 3:\n x, W, b = inputs\n else:\n (x, W), b = inputs, None\n\n y = x.dot(W.T).astype(x.dtype, copy=False)\n \n # Add a bias term, if relevant.\n if b is not None:\n y += b\n \n # Since backward() depends only on x and W,\n # we need only retain these two.\n self.retain_inputs((0,1))\n \n # Must return the output as a tuple.\n return (y,)\n\n def backward(self, indices, grad_outputs):\n '''\n General-purpose computation for both CPU/GPU.\n '''\n \n x, W = self.get_retained_inputs()\n gy, = grad_outputs # written as gamma in their docs.\n \n # Docs say that backward() must return a tuple, but\n # looking at their source code for linear.py, it\n # seems like lists are fine.\n out = []\n if 0 in indices:\n gx = gy @ W\n out.append(ch.functions.cast(gx, x.dtype))\n if 1 in indices:\n gW = gy.T @ x\n out.append(ch.functions.cast(gW, W.dtype))\n if 2 in indices:\n # Summing here is simple: for n observations,\n # gy has shape (n,k), where k is the number of\n # layer outputs. Summing over axis=0 is summing\n # over OBSERVATIONS, not over outputs.\n gb = ch.functions.sum(gy, axis=0)\n \n # Return just the relevant gradients we appended.\n return out\n\n\ndef linear(x, W, b):\n '''\n A nice thin wrapper for our linear FunctionNode on\n Variable objects.\n '''\n \n if b is None:\n args = (x, W)\n else:\n args = (x, W, b)\n \n # Don't forget to unpack from the tuple.\n y, = LinearFunction().apply(args)\n return y\n\n\n# Link object for our linear FunctionNode.\n\nclass Linear(ch.Link):\n '''\n A Link class for our linear transformation, implemented\n in the LinearFunction class.\n '''\n def __init__(self,\n in_size, out_size,\n init_W=None, init_b=None,\n init_delta=None,\n nobias=False):\n super(Linear, self).__init__()\n \n # Here we initialize and \"register\" the parameters\n # of interest. This is critical because when we\n # call __call__(x) and apply the underlying affine\n # transformations to input x (both forward pass and\n # backward pass), the optimization algorithms knows\n # that we want to optimize W and maybe b, but not x.\n\n with self.init_scope():\n \n # If provided an ndarray, use it.\n if init_W is not None:\n self.W = ch.Parameter(initializer=np.copy(init_W))\n \n # Else, use a built-in initializer.\n else:\n W_initializer = ch.initializers.Uniform(scale=init_delta,\n dtype=np.float32)\n self.W = ch.Parameter(initializer=W_initializer,\n shape=(out_size, in_size))\n \n if nobias:\n self.b = None\n else:\n if init_b is not None:\n self.b = ch.Parameter(initializer=np.copy(init_b))\n else:\n self.b = ch.Parameter(initializer=0,\n shape=(out_size,))\n \n def __call__(self, x):\n '''\n This method actually applies the linear layer to\n inputs x.\n '''\n return linear(x, self.W, self.b)\n\n\n# Chain object, composed of Link objects. This is a proper model in the\n# sense that it can be fed to optimizers.\n\nclass MyChain(ch.Chain):\n '''\n Perhaps the simplest possible model, a\n feed-forward neural network without any\n hidden layers. Just one, fully-connected\n linear layer, aka a classical linear model.\n \n out_l0: number of outputs from layer 0.\n out_l1: number of outputs from layer 1.\n '''\n \n def __init__(self,\n out_l0,\n out_l1,\n init_W=None, init_b=None,\n init_delta=1.0,\n nobias=False):\n super(MyChain, self).__init__()\n \n with self.init_scope():\n self.l1 = Linear(in_size=out_l0,\n out_size=out_l1,\n init_W=init_W,\n init_b=init_b,\n init_delta=init_delta,\n nobias=True)\n\n def __call__(self, x):\n return self.l1(x) # parameters are managed by Links.\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":20505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"310143035","text":"import tensorflow as tf\nimport numpy as np\nfrom DQN import DQN\n\nclass DoubleDQN(DQN):\n def __init__(\n self,\n n_actions,\n n_features,\n sess,\n learning_rate=0.01,\n reward_decay=0.9,\n e_greedy=0.9,\n replace_target_iter=300,\n memory_size=500,\n batch_size=32,\n e_greedy_increment=None,\n store_q = False\n ):\n super(DoubleDQN, self). __init__(\n n_actions,\n n_features,\n sess,\n learning_rate,\n reward_decay,\n e_greedy,\n replace_target_iter,\n memory_size,\n batch_size,\n e_greedy_increment,\n store_q\n )\n \n def learn(self):\n s, a, r, s_ = self.sample()\n if self.learn_step_counter % self.replace_target_iter == 0:\n self.sess.run(self.replace_target_op)\n print('\\ntarget_params_replaced\\n')\n\n q_next, q_eval = self.sess.run(\n [self.q_next, self.q_eval],\n feed_dict={self.s_: s_, self.s: s}\n )\n q_target = q_eval.copy()\n\n batch_index = np.arange(self.batch_size)\n q_next_new = self.sess.run(self.q_eval, feed_dict={self.s: s_})\n max_actions = np.argmax(q_next_new, axis=1)\n q_target[batch_index, a] = r + self.gamma * q_next[batch_index, max_actions]\n\n _, self.cost = self.sess.run([self._train_op, self.loss], feed_dict={self.s: s, self.q_target: q_target})\n\n self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max\n self.learn_step_counter += 1\n\n\n\nif __name__ == '__main__':\n import gym\n import matplotlib.pyplot as plt\n\n env = gym.make(\"Pendulum-v0\")\n env.seed(1)\n MEMORY_SIZE = 3000\n ACTION_SPACE = 11\n\n sess = tf.Session()\n with tf.variable_scope(\"Natural_DQN\"):\n natural_DQN = DQN(\n n_actions=ACTION_SPACE,\n n_features=env.observation_space.shape[0],\n memory_size=MEMORY_SIZE,\n e_greedy_increment=0.001,\n sess=sess,\n store_q = True\n )\n\n with tf.variable_scope(\"Double_DQN\"):\n double_DQN = DoubleDQN(\n n_actions=ACTION_SPACE,\n n_features=env.observation_space.shape[0],\n memory_size=MEMORY_SIZE,\n e_greedy_increment=0.001,\n sess=sess,\n store_q=True\n )\n sess.run(tf.global_variables_initializer())\n\n def train(learner):\n total_steps = 0\n s = env.reset()\n \n while True:\n # env.render()\n\n a = learner.choose_action(s)\n f_action = (a - (ACTION_SPACE - 1) / 2) / ((ACTION_SPACE - 1) / 4)\n s_new, reward, done, info = env.step(np.array([f_action]))\n\n reward /= 10\n\n learner.store_transition(s, a, reward, s_new)\n\n if total_steps > MEMORY_SIZE:\n learner.learn()\n\n if total_steps - MEMORY_SIZE > 20000:\n break\n\n s = s_new\n total_steps += 1\n\n return learner.q\n\n q_natural = train(natural_DQN)\n q_double = train(double_DQN)\n\n plt.plot(np.array(q_natural), c='r', label='natural')\n plt.plot(np.array(q_double), c='b', label='double')\n plt.legend(loc='best')\n plt.ylabel('Q eval')\n plt.xlabel('training steps')\n plt.grid()\n plt.show()","sub_path":"Morvan_tutorial/rl/dqn/DDQN.py","file_name":"DDQN.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"579799529","text":"r\"\"\"\nGROMACS 2018.2\n\nContents:\n Ubuntu 16.04\n CUDA version 9.0\n GNU compilers (upstream)\n OFED (upstream)\n OpenMPI version 3.0.0\n\"\"\"\n# pylint: disable=invalid-name, undefined-variable, used-before-assignment\n# pylama: ignore=E0602\nimport os\nfrom hpccm.templates.CMakeBuild import CMakeBuild\nfrom hpccm.templates.git import git\n\ngromacs_version = USERARG.get('GROMACS_VERSION', '2018.2')\n\nStage0 += comment(__doc__.strip(), reformat=False)\nStage0.name = 'devel'\nStage0 += baseimage(image='nvidia/cuda:9.0-devel-ubuntu16.04', _as=Stage0.name)\n\nStage0 += python(python3=False)\n\nStage0 += gnu(fortran=False)\n\nStage0 += packages(ospackages=['ca-certificates', 'cmake', 'git'])\n\nStage0 += ofed()\n\nStage0 += openmpi(configure_opts=['--enable-mpi-cxx'],\n prefix=\"/opt/openmpi\", version='3.0.0')\n\ncm = CMakeBuild()\nbuild_cmds = [git().clone_step(\n repository='https://github.com/gromacs/gromacs',\n branch='v' + gromacs_version, path='/gromacs',\n directory='src'),\n cm.configure_step(directory='/gromacs/src',\n build_directory='/gromacs/build',\n opts=[\n '-DCMAKE_BUILD_TYPE=Release',\n '-DCMAKE_INSTALL_PREFIX=/gromacs/install',\n '-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda',\n '-DGMX_BUILD_OWN_FFTW=ON',\n '-DGMX_GPU=ON',\n '-DGMX_MPI=OFF',\n '-DGMX_OPENMP=ON',\n '-DGMX_PREFER_STATIC_LIBS=ON',\n '-DMPIEXEC_PREFLAGS=--allow-run-as-root',\n '-DREGRESSIONTEST_DOWNLOAD=ON']),\n cm.build_step(),\n cm.build_step(target='install'),\n cm.build_step(target='check')]\nStage0 += shell(commands=build_cmds)\n\n# Include examples if they exist in the build context\nif os.path.isdir('recipes/gromacs/examples'):\n Stage0 += copy(src='recipes/gromacs/examples', dest='/workspace/examples')\n\nStage0 += environment(variables={'PATH': '$PATH:/gromacs/install/bin'})\n\nStage0 += label(metadata={'com.nvidia.gromacs.version': gromacs_version})\n\nStage0 += workdir(directory='/workspace')\n\n######\n# Runtime image stage\n######\nStage1.baseimage('nvidia/cuda:9.0-runtime-ubuntu16.04')\n\nStage1 += Stage0.runtime(_from=Stage0.name)\n\nStage1 += copy(_from=Stage0.name, src='/gromacs/install',\n dest='/gromacs/install')\n\n# Include examples if they exist in the build context\nif os.path.isdir('recipes/gromacs/examples'):\n Stage1 += copy(src='recipes/gromacs/examples', dest='/workspace/examples')\n\nStage1 += environment(variables={'PATH': '$PATH:/gromacs/install/bin'})\n\nStage1 += label(metadata={'com.nvidia.gromacs.version': gromacs_version})\n\nStage1 += workdir(directory='/workspace')\n","sub_path":"recipes/gromacs/gromacs.py","file_name":"gromacs.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"217999219","text":"import os\nimport logging\n\nfrom rcGlobalEnv import rcEnv\nimport rcExceptions as ex\nimport rcStatus\nimport resources as Res\nimport time\nimport datetime\nimport resSyncSymclone as symclone\nfrom rcUtilities import which\n\nclass syncSymclone(symclone.syncSymclone):\n def dev_rescan(self, dev):\n dev = dev.replace('/dev/', '')\n sysdev = \"/sys/block/%s/device/rescan\"%dev\n self.log.info(\"echo 1>%s\"%sysdev)\n with open(sysdev, 'w') as s:\n s.write(\"1\")\n\n def refresh_multipath(self, dev):\n if which(rcEnv.syspaths.multipath) is None:\n return\n cmd = [rcEnv.syspaths.multipath, '-v0', '-r', dev]\n (ret, out, err) = self.vcall(cmd)\n if ret != 0:\n raise ex.excError\n\n def dev_ready(self, dev):\n cmd = ['sg_turs', dev]\n (ret, out, err) = self.vcall(cmd)\n if ret != 0:\n return False\n return True\n\n def wait_for_dev_ready(self, dev):\n delay = 1\n timeout = 5\n for i in range(timeout/delay):\n if self.dev_ready(dev):\n return\n if i == 0:\n self.log.info(\"waiting for device %s to become ready (max %i secs)\"%(dev,timeout))\n time.sleep(delay)\n self.log.error(\"timed out waiting for device %s to become ready (max %i secs)\"%(dev,timeout))\n raise ex.excError\n\n def wait_for_devs_ready(self):\n for pair in self.pairs:\n src, dst = self.split_pair(pair)\n dev = self.showdevs_etree[dst].find('Dev_Info/pd_name').text\n if \"Not Visible\" in dev:\n raise ex.excError(\"pd name is 'Not Visible'. please scan scsi buses and run symcfg discover\")\n self.dev_rescan(dev)\n self.wait_for_dev_ready(dev)\n self.refresh_multipath(dev)\n\n def __init__(self,\n rid=None,\n type=\"sync.symclone\",\n symid=None,\n pairs=[],\n precopy=True,\n consistent=True,\n **kwargs):\n symclone.syncSymclone.__init__(self,\n rid=rid,\n type=type,\n symid=symid,\n pairs=pairs,\n precopy=precopy,\n consistent=consistent,\n **kwargs)\n\n","sub_path":"lib/resSyncSymcloneLinux.py","file_name":"resSyncSymcloneLinux.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"175467279","text":"from django.db import models\n\nfrom django.core.validators import RegexValidator\n\nfrom prj001.utils.validators_custom import ValidatorModelYear\nfrom datetime import date\n\n\n# 一般基本信息\nclass GeneralInfo(models.Model):\n TITLE = (\n (u'主任医师', u'主任医师'),\n (u'副主任医师', u'副主任医师'),\n (u'主治医师', u'主治医师'),\n )\n NATION = (\n (u'汉族', u'汉族'),\n (u'蒙古族', u'蒙古族'),\n (u'回族', u'回族'),\n (u'藏族', u'藏族'),\n (u'维吾尔族', u'维吾尔族'),\n (u'苗族', u'苗族'),\n (u'彝族', u'彝族'),\n (u'壮族', u'壮族'),\n (u'布依族', u'布依族'),\n (u'朝鲜族', u'朝鲜族'),\n (u'满族', u'满族'),\n (u'侗族', u'侗族'),\n (u'瑶族', u'瑶族'),\n (u'白族', u'白族'),\n (u'土家族', u'土家族'),\n (u'哈尼族', u'哈尼族'),\n (u'哈萨克族', u'哈萨克族'),\n (u'傣族', u'傣族'),\n (u'黎族', u'黎族'),\n (u'傈傈族', u'傈傈族'),\n (u'佤族', u'佤族'),\n (u'畲族', u'畲族'),\n (u'高山族', u'高山族'),\n (u'拉祜族', u'拉祜族'),\n (u'水族', u'水族'),\n (u'东乡族', u'东乡族'),\n (u'纳西族', u'纳西族'),\n (u'景颇族', u'景颇族'),\n (u'科尔克孜族', u'科尔克孜族'),\n (u'土族', u'土族'),\n (u'达斡尔族', u'达斡尔族'),\n (u'仫佬族', u'仫佬族'),\n (u'羌族', u'羌族'),\n (u'布朗族', u'布朗族'),\n (u'撒拉族', u'撒拉族'),\n (u'毛难族', u'毛难族'),\n (u'仡佬族', u'仡佬族'),\n (u'锡伯族', u'锡伯族'),\n (u'阿昌族', u'阿昌族'),\n (u'普米族', u'普米族'),\n (u'塔吉克族', u'塔吉克族'),\n (u'怒族', u'怒族'),\n (u'乌孜别克族', u'乌孜别克族'),\n (u'俄罗斯族', u'俄罗斯族'),\n (u'鄂温克族', u'鄂温克族'),\n (u'崩龙族', u'崩龙族'),\n (u'保安族', u'保安族'),\n (u'裕固族', u'裕固族'),\n (u'京族', u'京族'),\n (u'塔塔尔族', u'塔塔尔族'),\n (u'独龙族', u'独龙族'),\n (u'鄂伦春族', u'鄂伦春族'),\n (u'赫哲族', u'赫哲族'),\n (u'门巴族', u'门巴族'),\n (u'珞巴族', u'珞巴族'),\n (u'基诺族', u'基诺族'),\n (u'其他', u'其他'),\n )\n CAREER = (\n (u'学生', u'学生'),\n (u'个体', u'个体'),\n (u'农民', u'农民'),\n (u'军人', u'军人'),\n (u'工人', u'工人'),\n (u'财会人员', u'财会人员'),\n (u'技术人员', u'技术人员'),\n (u'服务业', u'服务业'),\n (u'科教文卫', u'科教文卫'),\n (u'行政管理', u'行政管理'),\n (u'无业', u'无业'),\n (u'其它', u'其它'),\n )\n ENTRANCE = (\n (u'门诊', u'门诊'),\n (u'病房', u'病房'),\n )\n CULTURE = (\n (u'未接受国家教育(文盲)', u'未接受国家教育(文盲)'),\n (u'小学及以下', u'小学及以下'),\n (u'初中', u'初中'),\n (u'高中/中专', u'高中/中专'),\n (u'大专', u'大专'),\n (u'本科', u'本科'),\n (u'研究生及以上', u'研究生及以上'),\n )\n\n owner = models.ForeignKey('myuser.MyUser',\n related_name='mygi',\n on_delete=models.CASCADE)\n serial = models.CharField(verbose_name=u'问卷编码',\n max_length=13,\n unique=True,\n blank=True,\n help_text=\"问卷编码\")\n name = models.CharField(verbose_name=u'患者姓名',\n max_length=50,\n help_text=\"患者姓名\")\n recdate = models.DateField(verbose_name=u'就诊日期',\n default=date.today,\n help_text=\"就诊日期\")\n hospital = models.CharField(verbose_name=u'医院名称',\n max_length=100,\n help_text=\"医院名称\")\n telephone = models.CharField(verbose_name=u'电话',\n max_length=11,\n help_text=\"电话\")\n expert = models.CharField(verbose_name=u'填表专家姓名',\n max_length=50,\n help_text=\"填表专家姓名\")\n title = models.CharField(verbose_name=u'职称',\n choices=TITLE,\n max_length=30,\n help_text=\"职称\")\n\n # age = models.IntegerField(verbose_name=u'年龄',\n # help_text=\"年龄\")\n\n birth_year = models.CharField(verbose_name='出生年份',\n max_length=4,\n blank=True,\n null=True,\n validators=[RegexValidator(regex=r'^\\d{4}$',\n message='必须为4位数字',\n code='year'),\n ValidatorModelYear(4, 'year')],\n default=0000,\n help_text='出生年份')\n birth_month = models.CharField(verbose_name='出生月份',\n max_length=2,\n default=00,\n blank=True,\n null=True,\n validators=[RegexValidator(regex=r'^\\d{2}$',\n message='必须为2位数字',\n code='month'),\n ValidatorModelYear(2, 'month')],\n help_text='出生月份')\n\n height = models.DecimalField(verbose_name=u'身高cm',\n max_digits=4,\n default='0',\n decimal_places=0,\n help_text=\"身高cm\")\n weight = models.DecimalField(verbose_name=u'体重kg',\n max_digits=4,\n default='0',\n decimal_places=1,\n help_text=\"体重kg\")\n waistline = models.DecimalField(verbose_name=u'腰围cm',\n max_digits=4,\n default='0',\n decimal_places=1,\n help_text=\"腰围cm\")\n hipline = models.DecimalField(verbose_name=u'臀围cm',\n max_digits=4,\n default='0',\n decimal_places=1,\n help_text=\"臀围cm\")\n\n # blood_type = models.CharField(verbose_name=u'血型',\n # choices=BLOOD_TYPE,\n # max_length=10,\n # help_text=\"血型\")\n nation = models.CharField(verbose_name=u'民族',\n choices=NATION,\n max_length=25,\n help_text=\"民族(汉字)\")\n career = models.CharField(verbose_name=u'职业',\n choices=CAREER,\n max_length=20,\n help_text=\"职业\")\n\n # 一般情况-特殊工作环境\n gaowen = models.BooleanField(verbose_name='高温',\n default=False,\n help_text='高温', )\n diwen = models.BooleanField(verbose_name=u'低温',\n default=False,\n help_text=\"低温\")\n yeban = models.BooleanField(verbose_name='夜班/熬夜',\n default=False,\n help_text='夜班/熬夜')\n zaosheng = models.BooleanField(verbose_name=u'噪声',\n default=False,\n help_text=\"噪声\")\n fushe = models.BooleanField(verbose_name=u'辐射',\n default=False,\n help_text=\"辐射\")\n huagongyinran = models.BooleanField(verbose_name=u'化工印染',\n default=False,\n help_text=\"化工印染\")\n julieyundong = models.BooleanField(verbose_name=u'剧烈运动',\n default=False,\n help_text=\"剧烈运动\")\n qiyou = models.BooleanField(verbose_name=u'汽油',\n default=False,\n help_text=\"汽油\")\n gaokong = models.BooleanField(verbose_name=u'高空',\n default=False,\n help_text=\"高空\")\n wu = models.BooleanField(verbose_name=u'无',\n default=False,\n help_text=\"无\")\n\n address = models.CharField(verbose_name=u'病人现住址',\n max_length=150,\n help_text=\"病人住址\")\n entrance = models.CharField(verbose_name=u'病人来源',\n choices=ENTRANCE,\n max_length=10,\n help_text=\"病人来源\")\n culture = models.CharField(verbose_name=u'文化程度',\n choices=CULTURE,\n max_length=30,\n help_text=\"文化程度\")\n\n # 一般情况-饮食偏好\n wuteshu = models.BooleanField(\n verbose_name=u'无特殊', default=False, help_text=\"无特殊\")\n sushi = models.BooleanField(\n verbose_name=u'素食', default=False, help_text=\"素食\")\n suan = models.BooleanField(verbose_name=u'酸', default=False, help_text=\"酸\")\n tian = models.BooleanField(verbose_name=u'甜', default=False, help_text=\"甜\")\n xian = models.BooleanField(verbose_name=u'咸', default=False, help_text=\"咸\")\n xinla = models.BooleanField(\n verbose_name=u'辛辣', default=False, help_text=\"辛辣\")\n you = models.BooleanField(verbose_name=u'油', default=False, help_text=\"油\")\n shengleng = models.BooleanField(\n verbose_name=u'生冷', default=False, help_text=\"生冷\")\n kafei = models.BooleanField(\n verbose_name=u'含咖啡因食物或饮品', default=False, help_text=\"咖啡因\")\n qita = models.CharField(verbose_name=u'其它',\n null=True,\n blank=True,\n max_length=50,\n default=None,\n help_text=\"其他\")\n\n degree_of_completion = models.CharField(verbose_name='完成度',\n max_length=8,\n default='0%',\n help_text='完成度')\n\n CHECKED_CHOICE = (\n ('未审核', '未审核'),\n ('审核通过', '审核通过'),\n ('审核不通过', '审核不通过'),\n )\n is_checked = models.CharField(verbose_name='审核状态',\n max_length=5,\n choices=CHECKED_CHOICE,\n default='未审核',\n help_text='审核状态')\n\n reasons_for_not_passing = models.CharField(verbose_name='审核不通过原因',\n max_length=200,\n default=None,\n help_text='审核不通过原因',\n null=True,)\n\n def __int__(self):\n return self.name\n\n def __str__(self):\n return '%s' % self.serial\n\n class Meta:\n verbose_name = u'基本信息'\n ordering = ('-recdate', '-pk')\n permissions = (\n (\"prj001_operation\", \"prj001_self_permissions\"),\n ('prj001_patient', 'data_can_be_modified'),\n ('prj001_all', 'prj001_all_permissions'),\n )\n\n verbose_name_plural = verbose_name\n","sub_path":"prj001/models/geninfo.py","file_name":"geninfo.py","file_ext":"py","file_size_in_byte":12830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"317772877","text":"\"\"\"\nExamples of using extra turboworks features.\n\nIn this task, the calculation and optimization includes a categorical dimension, a function to fetch extra features\n(get_z), a custom predictor function, extra arguments to the workflow creator, duplicate checking enabled, and a custom\nstorage location for the optimization data.\nAlso, a demo of how to use the lpad kwarg to store optimization data based on a Firework's LaunchPad object.\n\"\"\"\n\nfrom fireworks.core.rocket_launcher import rapidfire\nfrom fireworks import Workflow, Firework, LaunchPad\nfrom turboworks.optimize import OptTask\nfrom calculate_task import MixedCalculateTask as CalculateTask\nimport random\n\n\n# use a wf_creator function with more arguments...\ndef wf_creator(x, launchpad, my_arg, my_kwarg=1):\n\n fw1_spec = {'A': x[0], 'B': x[1], 'C': x[2], 'D': x[3], '_x_opt': x}\n fw1_dim = [(1, 2), (1, 2), (1, 2), (\"red\", \"green\", \"blue\")]\n\n # CalculateTask writes _y_opt field to the spec internally.\n\n firework1 = Firework([CalculateTask(),\n OptTask(wf_creator='turboworks_examples.test_extras.wf_creator',\n dimensions=fw1_dim,\n get_z='turboworks_examples.test_extras.get_z',\n predictor='turboworks_examples.test_extras.example_predictor',\n max=True,\n lpad=launchpad,\n wf_creator_args=[launchpad, my_arg * 3],\n wf_creator_kwargs={'my_kwarg': my_kwarg * 2},\n duplicate_check=True,\n opt_label=\"opt_extras_example\",\n retrain_interval=5)],\n spec=fw1_spec)\n\n return Workflow([firework1])\n\n\n# An optional function which returns extra information 'z' from unique vector 'x'\ndef get_z(x):\n return [x[0] * 2, x[2] ** 3]\n\n# how an example custom optimization function could be used\n# replace the code inside example_predictor with your favorite optimizer\n\ndef example_predictor(X_tot, y, X_space_total):\n # custom optimizer code goes here\n return random.choice(X_space_total)\n\n\nif __name__ == \"__main__\":\n\n TESTDB_NAME = 'turboworks'\n launchpad = LaunchPad(name=TESTDB_NAME)\n launchpad.reset(password=None, require_password=False)\n launchpad.add_wf(wf_creator([1, 1, 2, \"red\"], launchpad, 3, my_kwarg=1))\n\n\n # if n_launches > 24 for this particular example, the search space will be exhausted and OptTask will throw\n # an exception\n rapidfire(launchpad, nlaunches=25, sleep_time=0)\n\n # tear down database\n # launchpad.connection.drop_database(TESTDB_NAME)","sub_path":"turboworks_examples/test_extras.py","file_name":"test_extras.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"525074351","text":"import rospy\nfrom sensor_msgs.msg import Joy\nfrom std_msgs.msg import Int32, Float64, Bool, Int16\nimport math\n\nbuttonA = 0 \nforwardPublisher = 0\n\nDEGREE_45 = 0.785398\nDEGREE_90 = 1.5708\nDEGREE_1 = 0.0174\n\nclass JoyNode:\n \"Xbox controller for AUV\"\n\n def __init__(self):\n \"JoyNode Constructor\"\n rospy.Subscriber('joy', Joy, self.joyCallBack)\n\n self.yaw_state = None\n self.depth_state = None\n self.yaw_setpoint = None\n self.depth_setpoint = None\n rospy.Subscriber('/yaw_control/state', Float64, self.yaw_state_callback)\n rospy.Subscriber('/depth_control/state', Float64, self.depth_state_callback)\n rospy.Subscriber('/yaw_control/setpoint', Float64, self.yaw_setpoint_callback)\n rospy.Subscriber('/depth_control/setpoint', Float64, self.depth_setpoint_callback)\n\n self.depthPublisher = rospy.Publisher('/depth_pwm', Int16, queue_size=10)\n self.forwardPublisher = rospy.Publisher('/yaw_pwm', Int16, queue_size=10)\n self.yawSetpointPublisher = rospy.Publisher('/yaw_control/setpoint', Float64, queue_size=10)\n self.depthSetpointPublisher = rospy.Publisher('/depth_control/setpoint', Float64, queue_size=10)\n \n self.depthPidPublisher = rospy.Publisher('/depth_control/pid_enable', Bool, queue_size=10)\n self.yawPidPublisher = rospy.Publisher('yaw_control/pid_enable', Bool, queue_size=10)\n\n # List of buttons and axes for the Microsoft XBox Wired Controller\n # http://wiki.ros.org/joy\n self.buttons = [False for i in range(11)] \n self.axes = [0 for i in range(8)]\n\n self.setpoint_button_toggle = False\n self.saved_angle = None\n\n def yaw_state_callback(self, msg):\n self.yaw_state = msg.data\n\n def depth_state_callback(self, msg):\n self.depth_state = msg.data\n\n def yaw_setpoint_callback(self, msg):\n self.yaw_setpoint = msg.data\n\n def depth_setpoint_callback(self, msg):\n self.depth_setpoint = msg.data\n\n def fix_yaw(self, yaw):\n if yaw >= 3.14:\n yaw -= 2 * 3.14\n elif yaw <= -3.14:\n yaw += 2 * 3.14\n return yaw\n\n def execute(self):\n buttonIncreaseDepth = self.buttons[0] # Button A\n buttonDecreaseDepth = self.buttons[3] # Button Y\n buttonRotateCounterClockwise = self.buttons[2] # Button X\n buttonRotateClockwise = self.buttons[1] # Button B\n\n triggerDepth = self.axes[2] # Axis Left Trigger\n triggerYaw = self.axes[5] # Axis Right Trigger\n\n axisStrafe = self.axes[6] # Axis Cross Key Left/Right\n axisForward = self.axes[7] # Axis Cross Key Up/Down\n\n if buttonIncreaseDepth: # Button A -- Increase depth setpoint\n print(\"Button A pressed\")\n if self.depth_state != None:\n new_depth = self.depth_state + 1\n depthObj = Float64()\n depthObj.data = new_depth\n print(\"Button A -- new depth: {}\".format(new_depth))\n self.depthSetpointPublisher.publish(depthObj)\n else:\n print(\"Button A -- depth state was not published\")\n\n if buttonRotateClockwise: # Button B -- Rotate clockwise\n print(\"Button B pressed\")\n # Increase setpoint clockwise\n if self.yaw_setpoint != None:\n new_yaw = self.yaw_setpoint + DEGREE_1 / 50.0\n new_yaw = self.fix_yaw(new_yaw)\n yawObj = Float64()\n yawObj.data = new_yaw\n print(\"Button B -- {}\".format(new_yaw))\n self.yawSetpointPublisher.publish(yawObj)\n else:\n print(\"Button B -- yaw setpoint was not published. Press the START button\")\n # else:\n # # Stop rotating by setting the setpoint to current rotation\n # if self.yaw_state != None:\n # yawObj = Float64()\n # yawObj.data = self.yaw_state\n # self.yawSetpointPublisher.publish(yawObj)\n\n\n if buttonRotateCounterClockwise: # Button X -- Rotate counter-clockwise\n print(\"Button X pressed\")\n # Increase setpoint counter-clockwise\n if self.yaw_setpoint != None:\n new_yaw = self.yaw_setpoint - DEGREE_1 / 50.0\n new_yaw = self.fix_yaw(new_yaw)\n yawObj = Float64()\n yawObj.data = new_yaw\n print(\"Button X -- {}\".format(new_yaw))\n self.yawSetpointPublisher.publish(yawObj)\n else:\n print(\"Button X -- yaw setpoint was not published. Press the START button\")\n\n # else:\n # # Stop rotating by setting the setpoint to current rotation\n # if self.yaw_state != None:\n # yawObj = Float64()\n # yawObj.data = self.yaw_state\n # self.yawSetpointPublisher.publish(yawObj)\n\n\n if buttonDecreaseDepth: # Button Y -- Decrease depth setpoint\n print(\"Button Y pressed\")\n if self.depth_state != None:\n new_depth = self.depth_state - 1\n depthObj = Float64()\n depthObj.data = new_depth\n print(\"Button Y -- new depth: {}\".format(new_depth))\n self.depthSetpointPublisher.publish(depthObj)\n else:\n print(\"Button Y -- depth state was not published\")\n\n\n if self.buttons[4]:\n # drop weight LB\n pass\n\n if self.buttons[5]:\n # torpedo launcher RB\n pass\n\n if self.buttons[6]: # Button BACK -- Disable PIDs\n print(\"Button BACK -- PIDs are disabled\")\n off = Bool()\n off.data = False\n zeroFloat = Float64()\n zeroFloat.data = 0.0\n zeroInt = Int16()\n zeroInt.data = 0\n self.depthPidPublisher.publish(off)\n self.yawPidPublisher.publish(off)\n self.forwardPublisher.publish(zeroInt)\n self.depthPublisher.publish(zeroInt)\n\n if self.buttons[7]: # Button START -- Enable PIDs\n print(\"Button START -- PIDs are enabled\")\n on = Bool()\n on.data = True\n self.depthPidPublisher.publish(on)\n self.yawPidPublisher.publish(on)\n if self.yaw_state != None:\n yaw = Float64()\n yaw.data = self.yaw_state\n self.yawSetpointPublisher.publish(yaw)\n else:\n print(\"Button START -- /yaw_control/state has not been published. Check that AHRS is running?\")\n\n # Left Trigger -- manually set depth pwm\n if triggerDepth:\n value = triggerDepth\n value -= 1 # adjust from [-1,1] to [-2,0], so can make default zero (depth)\n value *= -1 # adjust from [-2,0] to [0,2], had to do - 1 and * 1 so not using trigger posts \"0\" instead of \"2\"\n value /= 2 # scale from [0,2] to [0,1], so button value is a percent of max thrust\n value *= 150 # scale from [0,1] to [0,150], so thrust scales from 0 to our desired max\n\n depth_pwm = Int16()\n depth_pwm = value\n print(\"Trigger DEPTH -- setting depth_pwm to \" + str(value))\n self.depthPublisher.publish(depth_pwm)\n \n \n # Right Trigger -- manually set yaw forward pwm\n if triggerYaw:\n value = triggerYaw\n value -= 1 # adjust from [-1,1] to [-2,0], so can make default zero (depth)\n value *= -1 # adjust from [-2,0] to [0,2], had to do - 1 and * 1 so not using trigger posts \"0\" instead of \"2\"\n value /= 2 # scale from [0,2] to [0,1], so button value is a percent of max thrust\n value *= 150 # scale from [0,1] to [0,150], so thrust scales from 0 to our desired max\n\n yaw_pwm = Int16()\n yaw_pwm = value\n print(\"Trigger YAW_FORWARD -- setting yaw to \" + str(value))\n self.forwardPublisher.publish(yaw_pwm)\n \n \n # Left Stick -- Analog rotation about Y-axis\n x = -1 * self.axes[3] # axis goes from +1 to -1, so we flip the sign to change it to standard coordinate system\n y = self.axes[4]\n left_stick_magnitude = math.sqrt(x**2 + y**2)\n angle_radians = math.atan2(y,x)\n new_yaw = Float64()\n new_yaw.data = 0.0\n if left_stick_magnitude >= 0.95:\n new_yaw.data = angle_radians\n self.yawSetpointPublisher.publish(new_yaw)\n elif not self.saved_angle is None:\n new_yaw.data = self.saved_angle\n self.yawSetpointPublisher.publish(new_yaw)\n elif not self.yaw_state is None:\n new_yaw.data = self.yaw_state\n self.yawSetpointPublisher.publish(new_yaw)\n \n\n if self.buttons[8]:\n # nothing mapped Power\n pass\n\n if self.buttons[9]:\n # nothing mapped Button Stick Left\n pass\n\n self.setpoint_button_toggle = False\n if self.buttons[10]: # Button Stick Right -- toggle saved yaw setpoint\n if left_stick_magnitude >= 0.95:\n self.saved_angle = angle_radians\n else:\n self.saved_angle = None\n\n # AXES\n\n if self.axes[0]:\n # nothing mapped L/R Axis Stick Left\n pass\n\n if self.axes[1]:\n # camera rotation U/D Axis Stick Left\n pass\n\n if self.axes[3]:\n # rotation about y-axis L/R Axis Stick Right\n pass\n\n if self.axes[4]:\n # rotation about y-axis U/D Axis Stick Right\n pass\n\n if self.axes[6]:\n # nothing mapped Cross Key L/R\n pass\n\n def joyCallBack(self, joy):\n #\"invoked every time a joystick message arrives\"\n global DEGREE_1, DEGREE_45, DEGREE_90\n \n for i in range(len(self.buttons)):\n self.buttons[i] = joy.buttons[i]\n for i in range(len(self.axes)):\n self.axes[i] = joy.axes[i]\n\nimport atexit\n\ndef kill_motors():\n print(\"killed motors\")\n\n off = Bool()\n off.data = False\n zeroInt = Int16()\n zeroInt.data = 0\n zeroFloat = Float64()\n zeroFloat.data = 0.0\n yaw_pub = rospy.Publisher('/yaw_pwm', Float64, queue_size=10)\n depth_pub = rospy.Publisher('/depth_pwm', Int16, queue_size=10)\n yaw_pid_pub = rospy.Publisher('yaw_control/pid', Bool, queue_size=10)\n depth_pid_pub = rospy.Publisher('/depth_control/pid', Bool, queue_size=10)\n yaw_pub.publish(zeroFloat)\n depth_pub.publish(zeroInt)\n yaw_pid_pub.publish(off)\n depth_pid_pub.publish(off)\n\natexit.register(kill_motors)\n\n\ndef main():\n rospy.init_node('joystickController')\n delay = rospy.Rate(20)\n\n joyObject = JoyNode()\n\n print(\"Python Project Running....\")\n while not rospy.is_shutdown():\n joyObject.execute()\n delay.sleep()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Mission Control/manual_control/joystickController.py","file_name":"joystickController.py","file_ext":"py","file_size_in_byte":10993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"484912195","text":"# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2016 Boundless Spatial\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 3 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#########################################################################\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom .models import CSWRecord, CSWRecordReference\n\nfield_attrs = {'required': '', 'class': 'form-control'}\n\n\nclass CSWRecordForm(forms.ModelForm):\n class Meta:\n model = CSWRecord\n fields = ('source', 'record_type', 'record_format', 'title', 'category', 'abstract',\n 'alternative', 'creator', 'contact_email', 'contact_phone', 'gold')\n\n widgets = {\n 'title': forms.TextInput(attrs=field_attrs),\n 'creator': forms.TextInput(attrs=field_attrs),\n 'abstract': forms.Textarea(attrs=field_attrs),\n 'alternative': forms.TextInput(attrs=field_attrs),\n 'source': forms.TextInput(attrs=field_attrs),\n 'contact_email': forms.TextInput(attrs=field_attrs),\n 'contact_phone': forms.TextInput(attrs=field_attrs),\n 'category': forms.Select(attrs=field_attrs),\n 'record_type': forms.HiddenInput(),\n 'record_format': forms.HiddenInput()\n }\n\n labels = {\n 'source': _('Service Url'),\n 'title': _('Title'),\n 'modified': _('Date Last Modified'),\n 'creator': _('Agency'),\n 'record_type': _('Type'),\n 'alternative': _('Layer Identifier'),\n 'abstract': _('Abstract'),\n 'record_format': _('Format'),\n 'bbox_upper_corner': _('Bounding Box: Upper Corner'),\n 'bbox_lower_corner': _('Bounding Box: Lower Corner'),\n 'contact_email': _('Contact Email'),\n 'contact_phone': _('Contact Phone'),\n 'gold': _('Gold'),\n 'category': _('Category')\n }\n\n help_texts = {\n 'source': _('e.g. http://example.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer'),\n 'alternative': 'The layer name or ID assigned to the dataset',\n 'bbox_upper_corner': _('Coordinates for upper left corner'),\n 'bbox_lower_corner': _('Coordinates for lower right corner'),\n }\n\n\nclass CSWRecordReferenceForm(forms.ModelForm):\n class Meta:\n model = CSWRecordReference\n widgets = {\n 'url': forms.TextInput(attrs={'class': 'form-control'}),\n 'scheme': forms.Select(attrs={'class': 'form-control'})\n }\n exclude = ()\n\n\nCSWRecordReferenceFormSet = forms.inlineformset_factory(CSWRecord, CSWRecordReference,\n form=CSWRecordReferenceForm, extra=1)\n","sub_path":"exchange/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"24211836","text":"from jenga.send_money import (\n SendMoney as BaseSendMoney,\n Recipient as BaseRecipient,\n Transaction as BaseTransaction\n)\n\n\nclass Recipient(BaseRecipient):\n def __init__(self, full_name: str, account_number: str, phone_number: str, bank_code: str,\n country_code: str = 'KE'):\n self.full_name = full_name\n self.account_number = account_number\n self.country_code = country_code\n self.bank_code = bank_code\n self.phone_number = phone_number\n\n def to_dict(self):\n return {\n \"type\": \"bank\",\n \"countryCode\": self.country_code,\n \"name\": self.full_name,\n \"accountNumber\": self.account_number,\n \"mobileNumber\": self.phone_number,\n \"bankCode\": self.bank_code\n }\n\n\nclass Transaction(BaseTransaction):\n def to_dict(self):\n return {\n \"type\": \"PesaLink\",\n \"amount\": str(self.amount),\n \"currencyCode\": self.currency_code,\n \"reference\": self.transaction_reference,\n \"date\": self.date,\n \"description\": self.description\n }\n\n\nclass SendMoney(BaseSendMoney):\n \"\"\"\n This web service enables an application to send money to a PesaLink participating bank.\n It is restricted to Kenya.\n \"\"\"\n transaction_class = Transaction\n recipient_class = Recipient\n\n def get_signature_string(self):\n return f\"{self.transaction.amount}{self.transaction.currency_code}\" \\\n f\"{self.transaction.transaction_reference}{self.recipient.full_name}\" \\\n f\"{self.sender.account_number}\"\n","sub_path":"jenga/send_money/pesalink/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"334559712","text":"# coding: utf-8\n\n\"\"\"\n FlashBlade REST API\n\n A lightweight client for FlashBlade REST API 2.10, developed by Pure Storage, Inc. (http://www.purestorage.com/).\n\n OpenAPI spec version: 2.10\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re\n\nimport six\nimport typing\n\nfrom ....properties import Property\nif typing.TYPE_CHECKING:\n from pypureclient.flashblade.FB_2_10 import models\n\nclass FileSession(object):\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 'name': 'str',\n 'authentication': 'str',\n 'client': 'FixedReferenceNameOnly',\n 'connection_time': 'int',\n 'idle_time': 'int',\n 'opens': 'int',\n 'port': 'int',\n 'protocol': 'str',\n 'time': 'int',\n 'user': 'UserNoId'\n }\n\n attribute_map = {\n 'name': 'name',\n 'authentication': 'authentication',\n 'client': 'client',\n 'connection_time': 'connection_time',\n 'idle_time': 'idle_time',\n 'opens': 'opens',\n 'port': 'port',\n 'protocol': 'protocol',\n 'time': 'time',\n 'user': 'user'\n }\n\n required_args = {\n }\n\n def __init__(\n self,\n name=None, # type: str\n authentication=None, # type: str\n client=None, # type: models.FixedReferenceNameOnly\n connection_time=None, # type: int\n idle_time=None, # type: int\n opens=None, # type: int\n port=None, # type: int\n protocol=None, # type: str\n time=None, # type: int\n user=None, # type: models.UserNoId\n ):\n \"\"\"\n Keyword args:\n name (str): Name of the object (e.g., a file system or snapshot).\n authentication (str): Describes how was the user authenticated. Valid values include `KRB` and `NTLMv2`.\n client (FixedReferenceNameOnly): Client that holds the session.\n connection_time (int): Connection time in milliseconds since UNIX epoch.\n idle_time (int): Duration in milliseconds that indicates how long the session has been idle.\n opens (int): Number of opens for the given session.\n port (int): Port number the client is connected from.\n protocol (str): The protocol utilized for obtaining and managing the session. Valid values include `nfs` and `smb`.\n time (int): Current time in milliseconds since UNIX epoch.\n user (UserNoId): The user who has created the session.\n \"\"\"\n if name is not None:\n self.name = name\n if authentication is not None:\n self.authentication = authentication\n if client is not None:\n self.client = client\n if connection_time is not None:\n self.connection_time = connection_time\n if idle_time is not None:\n self.idle_time = idle_time\n if opens is not None:\n self.opens = opens\n if port is not None:\n self.port = port\n if protocol is not None:\n self.protocol = protocol\n if time is not None:\n self.time = time\n if user is not None:\n self.user = user\n\n def __setattr__(self, key, value):\n if key not in self.attribute_map:\n raise KeyError(\"Invalid key `{}` for `FileSession`\".format(key))\n self.__dict__[key] = value\n\n def __getattribute__(self, item):\n value = object.__getattribute__(self, item)\n if isinstance(value, Property):\n return None\n else:\n return value\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 if hasattr(self, attr):\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(FileSession, 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, FileSession):\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":"pypureclient/flashblade/FB_2_10/models/file_session.py","file_name":"file_session.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"652262913","text":"from django.db import models\nfrom django.db.models import Q, F\nfrom property.models import Property, Council, LandUse, Cell, Village, Sector, District\nfrom citizen.models import Citizen\nfrom citizen.mappers.CitizenMapper import CitizenMapper\nfrom datetime import datetime, timedelta, date\nfrom django.utils.dateformat import DateFormat\nfrom django.utils.formats import get_format\nfrom dev1 import variables\nfrom asset.models import *\nfrom pmauth.models import *\nfrom decimal import Decimal\nfrom dev1 import ThreadLocal\nfrom jtax.shared_functions import calc_interest\nfrom dateutil.relativedelta import relativedelta\nproperty_decorator = property\nimport json\nimport cPickle as pickle\nfrom django.utils import timezone\n\n\n# This is the new IncompletePayment model #\n\nclass IncompletePaymentManager(models.Manager):\n\tdef get_query_set(self):\n\t\tuser = ThreadLocal.get_current_user()\n\t\tif user:\n\t\t\tif user.superuser:\n\t\t\t\treturn super(IncompletePaymentManager,self).get_query_set().all()\n\t\t\telse:\n\t\t\t\treturn super(IncompletePaymentManager,self).get_query_set().filter(district__in = District.objects.all(), sector__in = Sector.objects.all()).distinct()\n\t\telse:\n\t\t\treturn super(IncompletePaymentManager,self).get_query_set().none()\n\n\nclass IncompletePayment(models.Model):\n\ttax_type = models.CharField(choices=variables.tax_and_fee_types, max_length = 100, null = True, blank = True, verbose_name = 'Type of Tax')\n\ttin = models.CharField(max_length = 100, null = True, blank = True, verbose_name = 'TIN')\n\tbusiness = models.ForeignKey(Business, null=True, blank = True)\n\tsubbusiness = models.ForeignKey(SubBusiness, null=True, blank = True)\n\tpaid_amount = models.FloatField(null = True, blank = True, default = 0, verbose_name = \"Paid amount\")\n\tpaid_date = models.DateField(null=True, blank=True, verbose_name = \"Paid date\")\n\tperiod_from = models.DateField(null=True, blank=True)\n\tperiod_to = models.DateField(null=True, blank=True)\n\tbank = models.CharField(choices=variables.banks,max_length = 100, null = True, blank = True, verbose_name = 'Bank')\n\tbank_receipt = models.CharField(max_length = 100, null = True, blank = True, verbose_name = 'Bank Receipt')\n\tsector_receipt = models.CharField(max_length = 100, null = True, blank = True, verbose_name = 'Sector Receipt/manual receipt')\n\tdistrict = models.ForeignKey(District, null=True, blank=True, verbose_name = 'District')\n\tsector = models.ForeignKey(Sector, null = True, blank = True, verbose_name = 'Sector')\n\tcell = models.ForeignKey(Cell, null = True, blank = True, verbose_name = 'Cell')\n\tvillage = models.ForeignKey(Village, null = True, blank = True, verbose_name = 'Village')\n\tparcel_id = models.CharField(max_length = 100, null = True, blank=True, verbose_name = 'Plot/Parcel ID')\n\ttax_payer = models.CharField(max_length = 100, null = True, blank = True, verbose_name = 'Tax Payer')\n\tcitizen_id = models.CharField(max_length = 50, null = True, blank=True, verbose_name = 'Citizen ID')\n\tdate_of_birth = models.CharField(max_length = 50, null = True, blank=True, verbose_name = 'Date of Birth')\n\tphone = models.CharField(max_length = 100, null = True, blank=True, verbose_name = 'Phone')\n\temail = models.EmailField(max_length = 100, null = True, blank=True, verbose_name = 'Email')\n\tnote = models.TextField(null = True, blank=True, verbose_name = 'Reasons for incomplete payment')\n\tuser = models.ForeignKey(PMUser, null=True, blank = True)\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Entry has been entered into the database.',auto_now_add=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tobjects = IncompletePaymentManager()\n\tobjectsIgnorePermission = models.Manager()\n\n\tdef save(self, *args, **kwargs):\n\t\t\"\"\"\n\t\t1. set user to be the staff\n\t\t\"\"\"\n\t\tuser = ThreadLocal.get_current_user()\n\t\tself.user = user\n\t\tmodels.Model.save(self)\n\n\tdef __unicode__(self):\n\t\treturn \"Incomplete Payment \" + str(self.id)\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\nclass Historical(models.Model):\n\tcitizen = models.ForeignKey(Citizen, null=True, blank=True)\n\tbusiness = models.ForeignKey(Business, null=True, blank=True)\n\tfee_id = models.IntegerField(null=True, blank=True)\n\tfee_type = models.CharField(max_length=50)\n\tperiod_from = models.DateTimeField(null=True, blank=True)\n\tperiod_to = models.DateTimeField(null=True, blank=True)\n\tdue_date = models.DateTimeField(null=True, blank=True)\n\tamount_due = models.FloatField(null=True, blank=True)\n\tlate_paymemt_penalty = models.FloatField(default=0)\n\tlate_payment_interest = models.FloatField(default=0)\n\tis_paid = models.BooleanField(default = False)\n\tinvoince_no = models.CharField(max_length = 50, null=True, blank = True)\n\n\"\"\"\nThe DeclaredValue Models are based around Declared Values Supplied by Property Owners\nThese need to be checked against the Valuration system and checked if the supplied value is in line\nIf it is not it needs to be flaged and manually checked.\nThe Goverment / Council only has 6 months to Challange this value before it is automatticly accepted.\n\"\"\"\nclass DeclaredValue(models.Model):\n\t\"\"\"\n\tThis is the base class for the Delcated Values of a Plot of Land in Rwandap\n\t\"\"\"\n\t#plot_id = models.CharField(max_length = 50, help_text='This is the ID of the Plot that the Declared Value is for.')\n\t#citizen_id = models.CharField(max_length = 50, help_text='This is the Nation Id of the Cirizen Making the Delcared Value.')\n\tcitizen = models.ForeignKey(Citizen, null=True, blank=True)\n\tcommercial_amount = models.BigIntegerField(help_text='Commecial declared value', null=True, blank=True, default=0)\n\tresidential_amount = models.BigIntegerField(help_text='Residential Declared Value', null=True, blank=True, default=0)\n\tagriculture_amount = models.BigIntegerField(help_text='Agricultural declared value', null=True, blank=True, default=0)\n\tamount = models.BigIntegerField(help_text='This is the amount The Declared Value is been Made for.')\n\tcurrency = models.CharField(max_length=4,choices=variables.currency_types,help_text='This is the Currencey the Amount has been specified in.')\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Entry has been entered into the database.',auto_now_add=True)\n\t#staff_id = models.IntegerField(help_text='This is the Id of the Staff Member that Added the Declared Value for the Property.')\n\tuser = models.ForeignKey(PMUser, null=True, blank = True)\n\taccepted = models.CharField(max_length=20,choices=variables.declare_value_statuses,help_text='This is whether the declare Value has been Accepted, rejected, or needs review.')\n\tproperty = models.ForeignKey(Property, null=True, blank=True)\n\tdeclared_on = models.DateField(null=True)\n\n\tdef getLogMessage(self,old_data=None,new_data=None,action=None):\n\t\t\"\"\"\n\t\treturn tailored log message for different actions taken on this group\n\t\t\"\"\"\n\t\tif action == \"add\":\n\t\t\tcitizen = self.citizen\n\t\t\tcitizen_fullname = CitizenMapper.getDisplayName(citizen)\n\t\t\tproperty = self.property\n\t\t\tproperty_info = property.getDisplayName()\n\t\t\tmessage = \"approves Citizen [\"+citizen_fullname+ \"] to declare a value of \"+ self.currency + \" \" + str(self.amount) + \" on Property [\"+ property_info + \"]\"\n\t\t\treturn message\n\n\nclass DeclaredValueNotes(models.Model):\n\t\"\"\"\n\tThis is a table of notes Related to the Declared Values model\n\t\"\"\"\n\tdeclared_value = models.ForeignKey(DeclaredValue)\n\tcitizen = models.ForeignKey(Citizen, null=True, blank=True, help_text='The citizen who adds this note')\n\tuser = models.ForeignKey(PMUser, null=True, blank = True, help_text='The staff who adds this note.')\n\tnote = models.TextField(help_text='This is the Note that is been left for the Declared Value')\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Note was added to the Declared Value in the system.',auto_now_add=True)\n\nclass DeclaredValueMedia(models.Model):\n\t\"\"\"\n\tThis is a list of media files that have been attached to the Declared Value Application / Item directly.\n\t\"\"\"\n\tdeclared_value = models.ForeignKey(DeclaredValue)\n\tdescription = models.TextField(null=True, blank = True, help_text = 'Notes/Reminder')\n\tfile_name = models.CharField(max_length = 150)\n\tpath = models.CharField(max_length = 255)\n\tfile_type = models.CharField(max_length = 50)\n\tfile_size = models.CharField(max_length = 50)\n\tuser = models.ForeignKey(PMUser, null=True, blank = True, help_text='The staff who adds this note.')\n\tdate_time = models.DateTimeField(help_text='This is the date and time the file was uploaded',auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn str(self.file_name)\n\n\"\"\"\nThe Assigned Value models are for the assigned Values to a property, this would be the official price of the land/property accepted by the Goverment. All Tax Items based off Property Value should use this table.\nThese values are apparently accepted for 4 years from timme of acceptance.\n\"\"\"\nclass AssignedValue(models.Model):\n\t\"\"\"\n\tThis model is for the offically assigned Values of a plot for the purpose of taxation\n\t\"\"\"\n\tplot_id = models.IntegerField()\n\tamount = models.BigIntegerField(help_text='This is the Offical Property Price')\n\tdate_time = models.DateTimeField(help_text='This is the Date and time that the record for this assigned value was created', auto_now_add=True)\n\tcurrency = models.CharField(max_length=4,choices=variables.currency_types,help_text='this is the Currencey that the assigned Value Amount is in')\n\tstaff_id = models.IntegerField(help_text='This is the System Staff id of the staff member that entered the assigned value into the system.')\n\tcitizen_id = models.CharField(max_length=50,help_text='This is the ID of the Citizen That Provided the Delcared Value that was accepted')\n\tvalid_until = models.DateTimeField('This is when the Assigned Value Record Runs Out.')\n\ton_hold = models.CharField(max_length=4,choices=variables.on_hold,help_text='this will put the record on hold if needed.')\n\tproperty = models.ForeignKey(Property, null=True, blank=True)\n\nclass TaxType(models.Model):\n\tcode = models.CharField(max_length=50, null=True, blank=True)\n\tname = models.CharField(max_length=50)\n\nclass Bank(models.Model):\n\tcode = models.CharField(max_length=10, null=True, blank=True)\n\tname = models.CharField(max_length=50)\n\nclass Currency(models.Model):\n\tcode = models.CharField(max_length=10, null=True, blank=True)\n\tname = models.CharField(max_length=50)\n\n\nclass Tax(models.Model):\n\t\"\"\"\n\tplot_id = models.IntegerField(help_text='This is the ID of the Plot.')\n\ttax_type = models.ForeignKey(TaxType)\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount of tax item.\")\n\tremaining_amount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this tax item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this tax item is for.\")\n\tdue_date = models.DateField(help_text=\"The date this tax item is due.\")\n\tis_paid = models.BooleanField(help_text=\"Whether tax is payed.\")\n\tcreated = models.DateTimeField(help_text=\"The date this tax item is generated.\")\n\tproperty = models.ForeignKey(Property, null=True, blank=True)\n\tcitizen = models.ForeignKey(Citizen,null=True,blank=True)\n\tbusiness = models.ForeignKey(Business, null=True, blank=True, help_text=\"Business that have trading license to be taxed.\")\n\tsubbusiness = models.ForeignKey(SubBusiness, null=True, blank=True, help_text=\"SubBusiness that have trading license to be taxed.\")\n\tis_challenged = models.BooleanField(help_text=\"whether this tax item is challenged.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\tsubmit_details = models.CharField(max_length=500, null=True, blank=True)\n\tis_reviewed = models.BooleanField(help_text =\"whether this tax item is reviewed.\")\n\tis_accepted = models.BooleanField(help_text=\"whether this tax item is accepted.\")\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this property tax item.\", null=True, blank=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\t\"\"\"\n\tclass Meta:\n\t\tabstract = True\n\n\tdef calculatePaymentOld(self, pay_date=None, payment_amount=None):\n\t\tif not pay_date:\n\t\t\tpay_date = date.today()\n\n\t\tpayment = self.calculateTotalPayment(pay_date=pay_date, payment_amount=payment_amount)\n\t\tdue_date = payment['due_date']\n\t\tamount_due = payment['amount_due']\n\t\tinterest = payment['interest']\n\t\tsurcharge = payment['surcharge']\n\t\tlate_fees = payment['late_fees']\n\t\tinterest_rate = payment['interest_rate']\n\t\tmonths_late = payment['months_late']\n\t\tsurcharge_rate = payment['surcharge_rate']\n\t\tsurcharge_max = payment['surcharge_max']\n\t\ttotal = payment['total']\n\n\t\tdefault_installments = []\n\t\tinstallments = self.installments.all().order_by('due')\n\t\tlate_installments = [ installment for installment in installments if installment.due < pay_date and installment.paid < installment.amount ]\n\t\tif installments and not late_installments: # set the next installment date as due date\n\t\t\ttry:\n\t\t\t\tnext_installment = [ installment for installment in installments if installment.due > pay_date and installment.owed > 0 ][0]\n\t\t\t\tdue_date = next_installment.due\n\t\t\t\tamount_due = next_installment.owed\n\t\t\texcept IndexError:\n\t\t\t\tpass\n\n\t\ttotal_due = amount_due + Decimal(late_fees)\n\t\treturn { 'due_date':due_date, 'amount_due':amount_due, 'interest':interest, 'total':total,\n\t\t 'surcharge':surcharge, 'late_fees':late_fees, 'interest_rate':float(interest_rate * 100), 'total_due':total_due, 'months_late':months_late,\n\t\t 'surcharge_rate':surcharge_rate, 'surcharge_max':surcharge_max, 'installments':installments }\n\n\n\tdef calculatePayment(self, pay_date=None, payment_amount=None):\n\t\t\"\"\"\n\t\treturns the next payment amount, due date and interest payment information\n\t\t\"\"\"\n\t\tif not pay_date:\n\t\t\tpay_date = date.today()\n\n\t\tproperty_or_business = None\n\t\ttry:\n\t\t\tproperty_or_business = self.property\n\t\texcept AttributeError:\n\t\t\tpass\n\n\t\ttry:\n\t\t\tproperty_or_business = self.business\n\t\texcept AttributeError:\n\t\t\tpass\n\n\t\tif property_or_business:\n\t\t\tsector = property_or_business.sector\n\t\telse:\n\t\t\tsector = None\n\n\t\tdue_date = self.due_date\n\t\ttax_amount = self.amount or 0\n\t\tamount_paid = tax_amount - ( self.remaining_amount or 0)\n\t\tamount_due = tax_amount - amount_paid\n\t\tif amount_due < 0:\n\t\t\tamount_due = 0\n\n\t\tformula_data = []\n\t\tlate_fees = Decimal(0)\n\t\tmonths_late = Decimal(0)\n\t\ttotal_due = Decimal(0)\n\t\tinterest = Decimal(0)\n\t\tsurcharge = Decimal(0)\n\t\tprinciple = Decimal(0)\n\n\t\t# get the settings to calculate late fee\n\t\ttax_periods = Setting.getTaxPeriods(self.fee_setting, self.period_from, self.period_to, sector=sector)\n\t\ttax_setting = tax_periods[0][2]\n\n\t\tinterest_rate = Decimal(tax_setting['late_fee_interest_rate'])\n\t\tsurcharge_rate = Decimal(tax_setting['late_fee_surcharge_rate'])\n\t\tsurcharge_max = Decimal(tax_setting['late_fee_surcharge_max'])\n\n\t\tinstallments = self.installments.all().order_by('due')\n\t\tlate_installments = False\n\t\tpaid_amount = amount_paid\n\t\tunpaid_installments = []\n\n\t\tfor i in installments:\n\t\t\tif paid_amount < i.amount:\n\t\t\t\tpaid_amount = 0\n\t\t\t\tunpaid_installments.append(i)\n\t\t\telse: # already paid\n\t\t\t\tpaid_amount -= i.amount\n\n\t\tlate_installments = [ i for i in unpaid_installments if pay_date > i.due ]\n\n\t\tif not late_installments and unpaid_installments: # set the next installment date as due date\n\t\t\tdue_date = unpaid_installments[0].due\n\t\t\tamount_due = unpaid_installments[0].remaining\n\n\t\tif due_date and pay_date > due_date:\n\t\t\tlate_fees, months_late, interest, surcharge, principle = calc_interest(due_date, amount_due, surcharge_rate, surcharge_max, interest_rate, payment_amount, pay_date)\n\n\t\treturn { 'due_date':due_date, 'amount_due':amount_due, 'interest':interest,\n\t\t 'surcharge':surcharge, 'late_fees':late_fees, 'interest_rate':float(interest_rate * 100),\n\t\t 'months_late':months_late, 'principle':principle, 'amount_paid':amount_paid,\n\t\t 'surcharge_rate':float(surcharge_rate * 100), 'surcharge_max':surcharge_max }\n\n\n\tdef amount_owing(self, as_at=None):\n\t\tif not as_at:\n\t\t\tas_at = date.today()\n\t\tsector = None\n\t\tif hasattr(self, 'business'):\n\t\t\tsector = self.business.sector\n\t\telif hasattr(self, 'property'):\n\t\t\tsector = self.property.sector\n\n\t\ttax_periods = Setting.getTaxPeriods(self.fee_setting, self.period_from, self.period_to, sector=sector)\n\t\ttax_setting = tax_periods[0][2]\n\n\t\tinterest_rate = Decimal(tax_setting['late_fee_interest_rate'])\n\t\tsurcharge_rate = Decimal(tax_setting['late_fee_surcharge_rate'])\n\t\tsurcharge_max = Decimal(tax_setting['late_fee_surcharge_max'])\n\n\t\tlate_fees, months_late, interest, surcharge, principle = calc_interest(self.due_date, self.remaining_amount, surcharge_rate, surcharge_max, interest_rate, self.remaining_amount, as_at)\n\n\t\treturn self.remaining_amount, (late_fees or 0)\n\n\n\tdef get_installments(self):\n\t\tpaid = (self.amount or 0) - (self.remaining_amount or 0)\n\t\tinstallments = self.installments.all().order_by('due')\n\t\tfor i in installments:\n\t\t\tif paid < i.amount:\n\t\t\t\ti.paid = paid\n\t\t\t\tpaid = 0\n\t\t\telse: # already paid\n\t\t\t\tpaid = paid - i.amount\n\t\t\t\ti.paid = i.amount\n\t\t\ti.owed = i.amount - i.paid\n\t\treturn installments\n\n\n\tdef calculateRemainingAmount(self, amount):\n\t\tfrom django.db.models import Sum\n\t\t\"\"\"given a new amount, calculate the amount remaining\"\"\"\n\t\tif amount is None:\n\t\t\treturn None\n\t\tpaid_amount = self.payments.filter(amount__gt=0).aggregate(sum=Sum('amount'))['sum'] or 0\n\t\tremaining_amount = amount - paid_amount\n\t\treturn remaining_amount\n\n\tdef get_paid_amount(self):\n\t\tfrom django.db.models import Sum\n\t\tpaid = self.payments.filter(amount__gt=0).aggregate(amount=Sum('amount'), fines=Sum('fine_amount'))\n\t\ttotal = paid['amount'] or 0\n\t\tfines = paid['fines'] or 0\n\t\tcapital_amount = total - fines\n\t\treturn capital_amount, fines\n\n\n\tdef get_remaining_amount(self):\n\t\treturn (self.amount - self.get_paid_amount()[0])\n\n\n\tdef reset_tax(self):\n\t\tself.submit_date = None\n\t\tself.amount = self.remaining_amount = 0\n\t\tself.is_paid = False\n\t\tself.save()\n\t\ttry:\n\t\t\tself.formuladata.delete()\n\t\texcept:\n\t\t\tpass\n\n\n\t@property\n\tdef tax_type(self):\n\t\tif type(self) is PropertyTaxItem:\n\t\t\treturn 'fixed_asset_tax'\n\t\telif type(self) is RentalIncomeTax:\n\t\t\treturn 'rental_income_tax'\n\t\telif type(self) is TradingLicenseTax:\n\t\t\treturn 'trading_license_tax'\n\t\telif type(self) is Fee and 'land_lease' in self.fee_type:\n\t\t\treturn 'land_lease_fee'\n\t\telif type(self) is Fee:\n\t\t\treturn 'fee'\n\n\n\t@property\n\tdef fee_setting(self):\n\t\tif type(self) is PropertyTaxItem:\n\t\t\treturn 'fixed_asset_tax'\n\t\telse:\n\t\t\treturn 'general_fee'\n\n\tdef generateInstallments(self):\n\t\tamount = self.remaining_amount\n\t\tmonths = 3\n\t\tno_installments = 12/months\n\t\tif type(self.period_from) is datetime:\n\t\t\tdate_from = self.period_from.astimezone(timezone.get_default_timezone()).date()\n\t\tdue_date = date_from\n\t\tfor i in range(no_installments):\n\t\t\tdue_date = due_date + relativedelta(months=months-1) + relativedelta(day=31)\n\t\t\tamount = round(self.remaining_amount / no_installments)\n\t\t\tInstallment.objects.create(fee=self, amount=amount, paid=0, due=due_date)\n\t\treturn self.installments.all()\n\n\tdef pay_installment(self, amount, paid_on=None):\n\t\tinstallments = self.installments.filter(paid__lt=F('amount')).order_by('due')\n\t\tpaid_on = paid_on or date.today()\n\t\tfor installment in installments:\n\t\t\tunpaid = installment.amount - installment.paid\n\t\t\tif amount <= unpaid:\n\t\t\t\tinstallment.paid += amount\n\t\t\t\tinstallment.paid_on = paid_on\n\t\t\t\tinstallment.save()\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tinstallment.paid = installment.amount\n\t\t\t\tinstallment.paid_on = paid_on\n\t\t\t\tinstallment.save()\n\t\t\t\tamount -= unpaid\n\n\tdef next_outstanding_installment(self):\n\t\tinstallments = self.installments.filter(paid__lt=F('amount')).order_by('due')\n\t\tif installments:\n\t\t\treturn installments[0]\n\t\telse:\n\t\t\treturn None\n\n\tdef calc_tax_period(self):\n\t\tif type(self) is not Fee or type(self) is Fee and self.fee_type == 'land_lease':\n\t\t\tdate_from = date(self.date_from.year, 1, 1)\n\t\t\tdate_to = date(self.date_from.year, 12, 31)\n\t\telse:\n\t\t\tdate_from = self.date_from\n\t\t\tdate_to = self.date_to\n\n\t\towners = None\n\t\tdate_started = None\n\t\tif hasattr(self, 'subbusiness') and self.subbusiness:\n\t\t\towners = self.subbusiness.business.owners.filter(i_status='active').order_by('date_started')\n\t\t\tdate_started = self.subbusiness.business.date_started\n\t\tif hasattr(self, 'business') and self.business:\n\t\t\towners = self.business.owners.filter(i_status='active').order_by('date_started')\n\t\t\tdate_started = self.business.date_started\n\t\t\tif self.business.closed_date and self.business.closed_date < date_to:\n\t\t\t\tdate_to = self.business.closed_date\n\t\telif hasattr(self, 'property') and self.property:\n\t\t\towners = self.property.owners.filter(i_status='active').order_by('date_started')\n\t\tif date_started:\n\t\t\tif date_started > date_from and date_started <= date_to:\n\t\t\t\tdate_from = date_started\n\t\tif owners:\n\t\t\tdate_started = owners[0].date_started\n\t\t\tif date_started > date_from and date_started <= date_to:\n\t\t\t\tdate_from = date_started\n\n\t\t\"\"\"\n\t\tif self.months_exempted:\n\t\t\tdate_from = date_from + relativedelta(months=self.months_exempted)\n\t\t\tif date_from > date_to:\n\t\t\t\tdate_from = date_to\n\t\t\"\"\"\n\n\t\treturn date_from, date_to\n\n\n\"\"\"\nclass Payment(models.Model):\n\t# models.ForeignKey(Tax)\n\tbusiness_id = models.IntegerField(help_text=\"The business who pay this tax item.\", blank = True, null=True)\n\tcitizen_id = models.IntegerField(blank = True, null=True)\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True,auto_now=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\"\"\"\n\"\"\"\nLand Rental Tax Models\n\"\"\"\nclass LandRentalTax(models.Model):\n\tplot_id = models.IntegerField(help_text='This is the ID of the Plot.')\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount of tax item.\")\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this tax item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this tax item is for.\")\n\tdue_date = models.DateField(help_text=\"The date this tax item is due.\")\n\tis_paid = models.BooleanField(help_text=\"Whether tax is payed.\")\n\tdate_time = models.DateTimeField(help_text=\"The date this tax item is generated.\")\n\tproperty = models.ForeignKey(Property, null=True, blank=True)\n\n\nclass LandRentalTaxNotes(models.Model):\n\tland_rental_tax = models.ForeignKey('LandRentalTax')\n\tstaff_id = models.IntegerField(help_text='This is the Id of the Staff Member that created the note.')\n\tnote = models.TextField(help_text='This is the Note for the LandRental Tax Record Itself.')\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Note Was Created',auto_now_add=True)\n\nclass LandRentalTaxMedia(models.Model):\n\tland_rental_tax = models.ForeignKey('LandRentalTax')\n\n\"\"\"\nThe following Models are Related to the P = IncompletePayment.objects.all()\n\t\t\tsearch_iroperty Asset Tax Collection and Evalutional\n\"\"\"\n\nclass PropertyTaxItem(Tax):\n\tplot_id = models.CharField(max_length = 50, help_text = 'This is the ID of the Plot that the Declared Value is for.')\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount oIntegerFieldf property tax item.\", null=True, blank = True)\n\tremaining_amount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this property tax item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this property tax item is for.\")\n\tdate_from = models.DateField(null=True)\n\tdate_to = models.DateField(null=True)\n\tdue_date = models.DateField(help_text=\"The date this property tax item is due.\", null=True, blank=True, default=None)\n\tdate_time = models.DateTimeField(help_text=\"The date this propert tax item is generated.\", blank=True, default=None)\n\tis_paid = models.BooleanField(help_text=\"Whether tax is payed.\")\n\tis_chanllenged = models.BooleanField(help_text=\"whether this tax item is challenged.\")\n\tis_reviewed = models.BooleanField(help_text =\"whether this tax item is reviewed.\")\n\tis_accepted = models.BooleanField(help_text=\"whether this tax item is accepted.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\tsubmit_details = models.CharField(max_length=500, null=True, blank=True)\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this property tax item.\", null=True, blank=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tproperty = models.ForeignKey(Property, null=True, blank=True, related_name='fixed_asset_taxes')\n\texempt = models.BooleanField(default=False)\n\tmonths_deferred = models.IntegerField(default=0)\n\tland_use_types = models.ManyToManyField(LandUse)\n\tdeclared_value = models.ForeignKey(DeclaredValue, null=True, blank=True)\n\t#citizen_owners = models.ManyToManyField(Citizen)\n\t#business_owners = models.ManyToManyField(Business)\n\n\n\tdef __unicode__(self):\n\t\t#return 'sd ' + str(self.id)\n\t\tname = \"Property Tax Item (UPI: \" + str(self.property.getUPI()) + \") \"\n\t\tif self.date_from and self.date_to:\n\t\t\tname += \"[\" + DateFormat(self.date_from).format('d/m/Y') + \" - \" + DateFormat(self.date_to).format('d/m/Y') + \"]\"\n\t\treturn name\n\n\tdef calc_tax(self):\n\t\tproperty = self.property\n\t\tdeclared_value = property.declaredValue\n\t\tself.date_from, self.date_to = self.calc_tax_period()\n\n\t\tif declared_value and declared_value.declared_on and declared_value.amount is not None and property.land_use_types.count() > 0:\n\t\t\texpired_declared_value = declared_value.declared_on + relativedelta(years=4) < self.date_from\n\t\t\tif not expired_declared_value: # declared value has not expired, auto submit tax calc\n\t\t\t\tif declared_value.residential_amount + declared_value.agriculture_amount + declared_value.commercial_amount == declared_value.amount:\n\t\t\t\t\ttax_summary = Setting.calculateFixedAssetTax(self.date_from, self.date_to, residential=declared_value.residential_amount, commercial=declared_value.commercial_amount, agricultural=declared_value.agriculture_amount)\n\t\t\t\telse:\n\t\t\t\t\tland_use_codes = [land_use_type.code for land_use_type in property.land_use_types.all()]\n\t\t\t\t\tif 'RES' in land_use_codes:\n\t\t\t\t\t\ttax_summary = Setting.calculateFixedAssetTax(self.date_from, self.date_to, residential=declared_value.amount)\n\t\t\t\t\telif 'AGR' in land_use_codes:\n\t\t\t\t\t\ttax_summary = Setting.calculateFixedAssetTax(self.date_from, self.date_to, agricultural=declared_value.amount)\n\t\t\t\t\telif 'IND' in land_use_codes or 'QRY' in land_use_codes or 'COM' in land_use_codes: # industrial\n\t\t\t\t\t\ttax_summary = Setting.calculateFixedAssetTax(self.date_from, self.date_to, industrial=declared_value.amount)\n\t\t\t\t\telse:\n\t\t\t\t\t\traise Exception(\"Property ID %s does not contain a valid land use\" % property.pk)\n\t\t\t\tif tax_summary:\n\t\t\t\t\tif self.exempt:\n\t\t\t\t\t\tself.amount = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.amount = tax_summary['amount']\n\t\t\t\t\tself.remaining_amount = self.calculateRemainingAmount(self.amount)\n\t\t\t\t\tif self.remaining_amount <= 0:\n\t\t\t\t\t\tself.is_paid = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.is_paid = False\n\t\t\t\t\tself.due_date = tax_summary['due_date']\n\t\t\t\t\tself.save()\n\n\t\t\t\t\tfd, created = FormulaData.objects.get_or_create(property_item=self)\n\t\t\t\t\tfd.formula_data = tax_summary\n\t\t\t\t\tfd.save()\n\t\t\t\t\treturn tax_summary\n\t\tself.due_date = Setting.get_due_date('fixed_asset_tax', self.date_to)\n\t\tself.reset_tax()\n\t\treturn None\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\nclass ChallengePropertyTaxItem(models.Model):\n\tproperty_tax_item = models.ForeignKey(PropertyTaxItem)\n\tcitizen_id = models.IntegerField(help_text=\"The person who pay this tax item.\")\n\tstaff_id = models.IntegerField(help_text=\"The government staff who accepts the payment.\")\n\tperiod_from = models.DateTimeField(help_text=\"The date from which this tax item is challenged.\",auto_now_add=True)\n\tperiod_to = models.DateTimeField(help_text=\"The date till which this tax item is challenged.\")\n\nclass ChallengePropertyTaxItemNote(models.Model):\n\tchallenge_property_tax_item = models.ForeignKey(ChallengePropertyTaxItem)\n\tstaff_id = models.IntegerField(help_text=\"The government staff who records this challenge.\")\n\tnote = models.TextField(help_text=\"Note on why this property tax item is challenged.\")\n\nclass ChallengePropertyTaxItemMedia(models.Model):\n\tchallengepropertytaxitemid = models.ForeignKey(ChallengePropertyTaxItem)\n\tmediatype = models.CharField(max_length=4,choices=variables.media_types,help_text='This is the type of media the file is')\n\tmediafile = models.FileField(help_text='This is the location of the file on the file system.',upload_to='tmp')\n\tstaffid = models.IntegerField(help_text='The ID of the Staff Member who uploaded the file')\n\tmediadatetime = models.DateTimeField(help_text='This is the date and time the file was uploaded',auto_now_add=True)\n\nclass ReviewPropertyTaxItem(models.Model):\n\tchallengepropertytaxitemid = models.ForeignKey(ChallengePropertyTaxItem)\n\tstaffid = models.IntegerField(help_text=\"The government staff who review the challenge.\")\n\treviewdate = models.DateTimeField(help_text=\"The date when this tax item is reviewd.\",auto_now_add=True)\n\tnote = models.CharField(max_length=255, help_text=\"review result.\")\n\n\"\"\"\nThe following Models are Related to the Rental Income Tax Collection and Evalutional\n\"\"\"\nclass RentalIncomeTax(Tax):\n\tplot_id = models.CharField(max_length = 50, help_text='This is the ID of the Plot that the Declared Value is for.')\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount of tax item.\", null=True, blank = True)\n\tremaining_amount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this tax item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this tax item is for.\")\n\tdate_from = models.DateField(null=True)\n\tdate_to = models.DateField(null=True)\n\tdue_date = models.DateField(help_text=\"The date this tax item is due.\", null=True, blank=True)\n\tis_paid = models.BooleanField(help_text=\"Whether tax is payed.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\tsubmit_details = models.CharField(max_length=500, null=True, blank=True)\n\tdate_time = models.DateTimeField(help_text=\"The date this tax item is generated.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tproperty = models.ForeignKey(Property, null=True, blank=True, related_name='rental_income_taxes')\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this property tax item.\", null=True, blank=True)\n\texempt = models.BooleanField(default=False)\n\tmonths_deferred = models.IntegerField(default=0)\n\tdeclared_rental_income = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"Last year declared rental income.\", null=True, blank = True)\n\tdeclared_bank_interest = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"Last year bank interest paid\", null=True, blank = True)\n\t#citizen_owners = models.ManyToManyField(Citizen)\n\t#business_owners = models.ManyToManyField(Business)\n\n\tdef __unicode__(self):\n\t\tname = \"Rental Income Tax (UPI: \" + str(self.property.getUPI()) + \") \"\n\t\tif self.date_from and self.date_to:\n\t\t\tname += \"[\" + DateFormat(self.date_from).format('d/m/Y') + \" - \" + DateFormat(self.date_to).format('d/m/Y') + \"]\"\n\t\treturn name\n\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\tdef calc_tax(self):\n\t\tself.date_from, self.date_to = self.calc_tax_period()\n\t\tif self.declared_bank_interest and self.declared_rental_income:\n\t\t\ttax_summary = Setting.calculateRentalIncome(self.date_from, self.date_to, self.declared_rental_income, self.declared_bank_interest)\n\t\t\tif tax_summary:\n\t\t\t\tif self.exempt:\n\t\t\t\t\tself.amount = 0\n\t\t\t\telse:\n\t\t\t\t\tself.amount = tax_summary['amount']\n\t\t\t\tself.remaining_amount = self.calculateRemainingAmount(self.amount)\n\t\t\t\tif self.remaining_amount <= 0 and not self.exempt:\n\t\t\t\t\tself.is_paid = True\n\t\t\t\telse:\n\t\t\t\t\tself.is_paid = False\n\t\t\t\tself.due_date = tax_summary['due_date']\n\t\t\t\tself.save()\n\t\t\t\tfd, created = FormulaData.objects.get_or_create(rental_income=self)\n\t\t\t\tfd.formula_data = tax_summary\n\t\t\t\tfd.save()\n\t\t\t\treturn tax_summary\n\n\t\tself.due_date = Setting.get_due_date('rental_income_tax', self.date_to)\n\t\tself.reset_tax()\n\t\treturn None\n\n\nclass RentalIncomeTaxNotes(Tax):\n\trental_income_tax = models.ForeignKey('rentalIncomeTax')\n\tstaff_id = models.IntegerField(help_text='This is the Id of the Staff Member that created the note.')\n\tnote = models.TextField(help_text='This is the Note for the LandRental Tax Record Itself.')\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Note Was Created',auto_now_add=True)\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\"\"\"\nThe following Models are Related to the Trading License Tax Collection and Evalutional\n\"\"\"\nclass TradingLicenseTax(Tax):\n\tbusiness = models.ForeignKey(Business, null=True, blank=True, help_text=\"Business that have trading license to be taxed.\")\n\tsubbusiness = models.ForeignKey(SubBusiness, null=True, blank=True, help_text=\"SubBusiness that have trading license to be taxed.\")\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount of property tax item.\", null=True, blank = True)\n\tremaining_amount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this property tax item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this property tax item is for.\")\n\tdate_from = models.DateField(null=True)\n\tdate_to = models.DateField(null=True)\n\tdue_date = models.DateField(help_text=\"The date this property tax item is due.\", null=True, blank = True)\n\tis_paid = models.BooleanField(help_text=\"Whether tax is payed.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\tsubmit_details = models.CharField(max_length=500, null=True, blank=True)\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this property tax item.\", null=True, blank = True)\n\tdate_time = models.DateTimeField(help_text=\"The date this propert tax item is generated.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\texempt = models.BooleanField(default=False)\n\tturnover = models.DecimalField(max_digits=20, decimal_places=2, help_text=\"Declared Turnover\", null=True)\n\tmonths_deferred = models.IntegerField(default=0)\n\tactivity_data = models.TextField(blank=False, null=True)\n\n\n\tdef __unicode__(self):\n\t\tif self.business:\n\t\t\tname = \"Trading License Tax (TIN: \" + str(self.business.tin) + \") \"\n\n\t\telif self.subbusiness:\n\t\t\tname = \"Trading License Tax (TIN: \" + str(self.subbusiness.business.tin) + \",branch:\"+self.subbusiness.branch + \") [\" + DateFormat(self.period_from).format('d/m/Y') + \" - \" + DateFormat(self.period_to).format('d/m/Y') + \"]\"\n\t\t\tif self.date_from and self.date_to:\n\t\t\t\tname += \"[\" + DateFormat(self.date_from).format('d/m/Y') + \" - \" + DateFormat(self.date_to).format('d/m/Y') + \"]\"\n\t\treturn name\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\n\tdef calculateActivityTax(self, *args, **kwargs):\n\t\tif not self.activity_data:\n\t\t\tself.reset_tax()\n\t\t\treturn None\n\t\telse:\n\t\t\tactivity_data = pickle.loads(self.activity_data.decode('base64'))\n\t\ttax_due = 0\n\t\tdate_from = self.date_from\n\t\tdate_to = self.date_to\n\t\tdue_date = self.date_to\n\t\tformula_data = {}\n\t\tcurrent_year = date_from.year\n\t\ttotal_days_in_period = Decimal((date(current_year, 12, 31) - date(current_year, 1, 1)).days + 1)\n\t\tperiod = (date_from, date_to)\n\t\tdays_in_period = Decimal((date_to - date_from).days + 1)\n\t\tactivities = variables.activities\n\t\tformula_data = {}\n\t\tactivity_description = variables.activity_description\n\t\tfor activity, settings in activities:\n\t\t\tfor setting_name, rate in settings:\n\t\t\t\tunits = activity_data.get(\"%s_%s\" % (activity, setting_name), 0)\n\t\t\t\tif not units: continue\n\t\t\t\tamount= Decimal(units * rate).quantize(Decimal('0.01'))\n\t\t\t\ttax_due += amount\n\t\t\t\tformula_data[\"%s - %s\" % (activity_description[activity], setting_name)] = {'units':units, 'rate': rate, 'amount':amount }\n\n\t\ttax_due = Decimal(int(tax_due * days_in_period / total_days_in_period))\n\t\treturn { 'amount':tax_due, 'due_date': due_date, 'due': due_date, 'formula_data':formula_data, 'days':days_in_period, 'total_days':total_days_in_period, 'vat':False }\n\n\n\tdef calc_tax(self):\n\n\t\tif self.subbusiness:\n\t\t\tbusiness = self.subbusiness.business\n\t\telse:\n\t\t\tbusiness = self.business\n\n\t\tself.date_from, self.date_to = self.calc_tax_period()\n\n\t\tif business.vat_register:\n\t\t\tif self.turnover:\n\t\t\t\ttax_summary = Setting.calculateTradingLicenseTax(self.date_from, self.date_to, self.turnover,\n\t\t\t\t\tsector=business.sector)\n\t\t\telse:\n\t\t\t\ttax_summary = None\n\t\telse:\n\t\t\ttax_summary = self.calculateActivityTax()\n\n\t\tif tax_summary:\n\t\t\tif self.exempt:\n\t\t\t\tself.amount = 0\n\t\t\telse:\n\t\t\t\tself.amount = tax_summary['amount']\n\t\t\tself.remaining_amount = self.calculateRemainingAmount(self.amount)\n\t\t\tif self.remaining_amount <= 0:\n\t\t\t\tself.is_paid = True\n\t\t\telse:\n\t\t\t\tself.is_paid = False\n\t\t\tself.due_date = tax_summary['due_date']\n\t\t\tself.save()\n\t\telse:\n\t\t\tself.due_date = Setting.get_due_date('trading_license_tax', self.date_to)\n\t\t\tself.reset_tax()\n\t\t\treturn None\n\n\t\tfd, created = FormulaData.objects.get_or_create(trading_license=self)\n\t\tfd.formula_data = tax_summary\n\t\tfd.save()\n\t\tif self.exempt:\n\t\t\tself.amount = 0\n\t\tself.save()\n\t\treturn tax_summary\n\n\nclass FeeManager(models.Manager):\n\tdef get_query_set(self):\n\t\treturn super(FeeManager,self).get_query_set().filter(status__code='active')\n\n\nclass Fee(Tax):\n\tfee_type = models.CharField(max_length=25, choices=variables.fee_types)\n\t#name = models.CharField(max_length=50, null=True, blank=True)\n\tquantity = models.IntegerField(default=1, null=True, blank=True)\n\t#target = models.CharField(max_length=25, null = True, blank=True, help_text=\"Payer type.\")\n\t#target_id = models.IntegerField(null=True, blank=True, help_text=\"Who will pay.\")\n\t#target_branch_id = models.IntegerField(help_text=\"Branch of target. i.e., branch of business\", null=True, blank=True)\n\tamount = models.IntegerField(help_text=\"The amount of fee item.\")\n\tremaining_amount = models.IntegerField(help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tperiod_from = models.DateTimeField(help_text=\"The start date of a period that this fee item is for.\")\n\tperiod_to = models.DateTimeField(help_text=\"The end date of a period that this fee item is for.\")\n\tdate_from = models.DateField(null=True)\n\tdate_to = models.DateField(null=True)\n\tdue_date = models.DateField(help_text=\"The date this fee item is due.\", null=True, blank=True)\n\tis_paid = models.BooleanField(help_text=\"Whether fee is payed.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\t#submit_details = models.CharField(max_length=500, null=True, blank=True)\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this fee item.\", null=True, blank=True)\n\tdate_time = models.DateTimeField(help_text=\"The date this fee item is generated.\",auto_now_add=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tbusiness = models.ForeignKey(Business, null=True, blank=True, related_name='business_fees')\n\tsubbusiness = models.ForeignKey(SubBusiness,null=True, blank=True)\n\tproperty = models.ForeignKey(Property,null=True,blank=True, related_name='property_fees')\n\tcitizen = models.ForeignKey(Citizen,null=True,blank=True)\n\texempt = models.BooleanField(default=False)\n\tland_lease_type = models.ForeignKey(LandUse, null=True, blank=True, default=None)\n\t#citizen_owners = models.ManyToManyField(Citizen)\n\t#business_owners = models.ManyToManyField(Business)\n\tcategory = models.ForeignKey(CategoryChoice, related_name='fee_category')\n\tstatus = models.ForeignKey(CategoryChoice)\n\tobjects = FeeManager()\n\tall_objects = models.Manager()\n\n\tdef __unicode__(self):\n\t\tif self.category.code == 'land_lease':\n\t\t\treturn \"Land Lease %s - %s\" % (self.date_from.strftime('%d/%m/%Y'), self.date_to.strftime('%d/%m/%Y'))\n\n\t\tif self.category.code == 'cleaning':\n\t\t\treturn \"Cleaning Fee for %s\" % (self.date_from.strftime('%B %Y'))\n\n\t\telse:\n\t\t\tname = self.fee_type.title() + \" Fee \"\n\t\t\tif self.date_from and self.date_to:\n\t\t\t\tname += \"[\" + DateFormat(self.date_from).format('d/m/Y') + \" - \" + DateFormat(self.date_to).format('d/m/Y') + \"]\"\n\t\t\treturn name\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\n\tdef calc_tax(self):\n\t\tif self.fee_type in ('cleaning_fee', 'cleaning'):\n\t\t\treturn self.calc_cleaningFee()\n\t\telif self.fee_type in ('land_lease', 'land_lease_fee'):\n\t\t\traise Exception('not implemented')\n\t\telse:\n\t\t\treturn None\n\n\tdef calc_landlease(self):\n\t\tself.date_from, self.date_to = self.calc_tax_period()\n\t\tland_size = self.property.get_sq_m()\n\t\tif self.property.land_use_type and land_size:\n\t\t\ttax_summary = Setting.calculateLandLeaseFee(self.date_from, self.date_to, self.property.land_use_type, land_size, district=self.property.sector.district, sector=self.property.sector, cell=self.property.cell, village=self.property.village)\n\t\t\tif tax_summary:\n\t\t\t\tif self.exempt:\n\t\t\t\t\tself.amount = 0\n\t\t\t\telse:\n\t\t\t\t\tself.amount = tax_summary['amount']\n\t\t\t\tself.remaining_amount = self.calculateRemainingAmount(self.amount) or 0\n\t\t\t\tself.due_date = tax_summary['due_date']\n\n\t\t\t\tfd, created = FormulaData.objects.get_or_create(fee=self)\n\t\t\t\tfd.formula_data = tax_summary\n\t\t\t\tfd.save()\n\t\t\t\tself.save()\n\t\t\t\treturn tax_summary\n\n\t\tself.due_date = Setting.get_due_date('land_lease_fee', self.date_to)\n\t\tself.reset_tax()\n\t\treturn None\n\n\n\tdef calc_cleaningFee(self):\n\t\tif self.category.code == 'cleaning':\n\t\t\tbusiness = self.business\n\t\t\tif business.business_category is not None:\n\t\t\t\tif not self.is_paid:\n\t\t\t\t\tif business.business_category_id in range(1,7):\n\t\t\t\t\t\tself.amount = 10000\n\t\t\t\t\telif business.business_category_id == 7:\n\t\t\t\t\t\tself.amount = 5000\n\t\t\t\t\telif business.business_category_id == 8:\n\t\t\t\t\t\tself.amount = 3000\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.amount = 0\n\n\t\t\t\tself.remaining_amount = self.calculateRemainingAmount(self.amount) or 0\n\t\t\t\tif self.remaining_amount <= 0 and self.amount > 0:\n\t\t\t\t\tself.is_paid = True\n\t\t\t\telse:\n\t\t\t\t\tself.is_paid = False\n\n\t\t\t\tself.submit_date = datetime.now()\n\t\t\t\tdue_date = self.date_from + relativedelta(months=1)\n\t\t\t\tself.due_date = date(due_date.year, due_date.month, 5)\n\n\t\t\t\tif self.amount:\n\t\t\t\t\tself.i_status = 'active'\n\t\t\t\t\tself.status = CategoryChoice.objects.get(category__code='status', code='active')\n\t\t\t\tself.save()\n\t\t\t\treturn self.amount, self.due_date\n\n\t\t\tif self.pk:\n\t\t\t\tself.submit_date = None\n\t\t\t\tself.i_status = 'inactive'\n\t\t\t\tself.status = CategoryChoice.objects.get(category__code='status', code='inactive')\n\t\t\t\tself.is_paid = False\n\t\t\t\tself.save()\n\n\t\treturn (None, None)\n\n\tdef medias(self):\n\t\tfrom media.models import Media\n\t\treturn Media.objects.filter(tax_type__in=['cleaning_fee','cleaning','fee'], tax_id=self.pk)\n\n\nclass MiscellaneousFee(models.Model):\n\tfee_type = models.CharField(max_length=250)\n\tfee_sub_type = models.CharField(max_length=250)\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The amount of fee item.\")\n\tremaining_amount = models.DecimalField(max_digits = 20, decimal_places = 2, help_text=\"The remaining amount (subtracted past payments).\", null=True, blank = True)\n\tcurrency = models.CharField(max_length=4, choices=variables.currency_types)\n\tis_paid = models.BooleanField(help_text=\"Whether fee is paid.\")\n\tsubmit_date = models.DateTimeField(help_text=\"The date this fee item is submited.\", null=True, blank=True)\n\tsubmit_details = models.CharField(max_length=500, null=True, blank=True)\n\tstaff_id = models.IntegerField(help_text=\"The staff who generates this fee item.\", null=True, blank=True)\n\tdate_time = models.DateTimeField(help_text=\"The date this fee item is generated.\",auto_now_add=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tbusiness = models.ForeignKey(Business, null=True, blank=True)\n\tsubbusiness = models.ForeignKey(SubBusiness,null=True, blank=True)\n\tproperty = models.ForeignKey(Property,null=True,blank=True)\n\tcitizen = models.ForeignKey(Citizen,null=True,blank=True)\n\n\tdef __unicode__(self):\n\t\treturn self.fee_type.title() + \" - \" + self.fee_sub_type.title() + \" Miscellaneous Fee \"\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\"\"\"\nThe following Models is for saving payments for Tax Items\n\"\"\"\nclass PayRentalIncomeTax(models.Model):\n\trental_income_tax = models.ForeignKey(RentalIncomeTax, help_text=\"\", related_name=\"payments\")\n\tbusiness_id = models.IntegerField(help_text=\"The business who pay this tax item.\", blank = True, null=True)\n\tcitizen_id = models.IntegerField(blank = True, null=True)\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\n\tdef __unicode__(self):\n\t\treturn \"Rental Income Tax Payment\"\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\nclass PayTradingLicenseTax(models.Model):\n\tcitizen_id = models.IntegerField(blank = True, null=True)\n\tbusiness_id = models.IntegerField(help_text=\"The business who pay this tax item.\", blank = True, null=True)\n\t#staff_id = models.IntegerField(help_text=\"The government staff who accepts the payment.\")\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\ttrading_license_tax = models.ForeignKey(TradingLicenseTax, help_text=\"\", related_name=\"payments\")\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tdef __unicode__(self):\n\t\treturn \"Trading License Tax Payment\"\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\nclass PayFeeManager(models.Manager):\n\tdef get_query_set(self):\n\t\treturn super(PayFeeManager,self).get_query_set().filter(status__code='active')\n\nclass PayFee(models.Model):\n\tcitizen_id = models.IntegerField(blank = True, null=True)\n\tbusiness_id = models.IntegerField(help_text=\"The business who pay this tax item.\", blank = True, null=True)\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\tfee = models.ForeignKey(Fee, help_text=\"\", related_name=\"payments\")\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0,null=True, blank = True)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\treceipt_id = models.IntegerField(null=True)\n\tstatus = models.ForeignKey(CategoryChoice)\n\tobjects = PayFeeManager()\n\tall_objects = models.Manager()\n\n\tdef __unicode__(self):\n\t\treturn \"Fee Payment\"\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\n\nclass PayFixedAssetTax(models.Model):\n\tproperty_tax_item = models.ForeignKey(PropertyTaxItem, related_name=\"payments\")\n\tbusiness_id = models.IntegerField(help_text=\"The business who pay this tax item.\", blank = True, null=True)\n\tcitizen_id = models.IntegerField(help_text=\"The person who pay this tax item.\", blank = True, null=True)\n\t#staff_id = models.IntegerField(help_text=\"The government staff who accepts the payment.\")\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tdef __unicode__(self):\n\t\treturn \"Fixed Asset Tax Payment\"\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\nclass PayMiscellaneousFee(models.Model):\n\tbusiness = models.ForeignKey(Business, null=True, blank=True)\n\tcitizen = models.ForeignKey(Citizen,null=True,blank=True)\n\t#staff_id = models.IntegerField(help_text=\"The government staff who accepts the payment.\")\n\tstaff = models.ForeignKey(PMUser, help_text=\"\",blank = True, null=True)\n\tfee = models.ForeignKey(MiscellaneousFee, help_text=\"\", related_name=\"payments\")\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\treceipt_no = models.CharField(max_length = 50)\n\tbank = models.CharField(max_length = 100, choices=variables.banks)\n\tpaid_date = models.DateField(help_text=\"\",default=datetime.now)\n\tfine_amount = models.DecimalField(max_digits = 20, decimal_places = 2, default=0,null=True, blank = True)\n\tfine_description = models.TextField(null=True, blank = True)\n\tmanual_receipt = models.CharField(max_length = 50)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\n\tdef __unicode__(self):\n\t\treturn \"Fee Payment\"\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\n#Pending Payment\nclass PendingPayment(models.Model):\n\tpayment_id = models.CharField(max_length = 50)\n\ttax_type = models.CharField(max_length = 50)\n\ttax_id = models.CharField(max_length = 50)\n\treason = models.CharField(max_length = 250)\n\tnote = models.TextField(null=True, blank = True, help_text=\"note about this payment.\")\n\tuser = models.ForeignKey(PMUser, null=True, blank = True)\n\tdate_time = models.DateTimeField(help_text=\"The date when this payment is entered into the system.\",auto_now_add=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\n\tdef __unicode__(self):\n\t\treturn \"Pending Payment\"\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\nclass FormulaData(models.Model):\n\n\tdata = models.TextField()\n\tfee = models.OneToOneField(Fee, null=True)\n\tproperty_item = models.OneToOneField(PropertyTaxItem, null=True)\n\ttrading_license = models.OneToOneField(TradingLicenseTax, null=True)\n\trental_income = models.OneToOneField(RentalIncomeTax, null=True)\n\n\tdef get_pickle(self):\n\t\treturn pickle.loads(self.data.decode('base64'))\n\n\tdef set_pickle(self, value):\n\t\tself.data = pickle.dumps(value).encode('base64')\n\n\tdef del_pickle(self):\n\t\tself.data = None\n\n\tformula_data = property_decorator(get_pickle, set_pickle, del_pickle)\n\n\nclass CleaningSchedule(models.Model):\n\tvalid_from = models.DateField(help_text='Date this setting to be valid from.')\n\tcouncil = models.ForeignKey(Council, null=True, blank=True, help_text=\"The council that setting applied to.\")\n\tdistrict = models.ForeignKey(District, null=True, blank=True, help_text=\"\")\n\tsector = models.ForeignKey(Sector, null=True, blank=True, help_text=\"\")\n\tcell = models.ForeignKey(Cell, null=True, blank=True, help_text=\"\")\n\tamount = models.DecimalField(decimal_places=0, max_digits=9)\n\tdue_date = models.DateField(null=True, blank=True)\n\tbusiness_category = models.ForeignKey(BusinessCategory)\n\tmodified = models.DateTimeField(help_text=\"The date when this setting is entered into the system.\",auto_now_add=True)\n\n\nclass Setting(models.Model):\n\ttax_fee_name = models.CharField(max_length = 50, help_text=\"Tax / Fee Name\")\n\tsetting_name = models.CharField(max_length = 50, help_text=\"Tax / Fee Setting Name\")\n\tsub_type = models.CharField(max_length = 250, blank = True, help_text=\"Tax / Fee Setting Sub Catergories that differentiate the rate / fee\")\n\tvalue = models.CharField(max_length = 50, default='',help_text=\"Setting Value, can be fee/tax rate/date/etc\")\n\tdescription = models.TextField(null=True, blank = True, help_text=\"Description about this payment.\")\n\tvalid_from = models.DateField(help_text='Date this setting to be valid from.')\n\tvalid_to = models.DateField(help_text='Date this setting get deprecated.', null=True, blank = True)\n\tcouncil = models.ForeignKey(Council, null=True, blank=True, help_text=\"The council that setting applied to.\")\n\tdistrict = models.ForeignKey(District, null=True, blank=True, help_text=\"\")\n\tsector = models.ForeignKey(Sector, null=True, blank=True, help_text=\"\")\n\tcell = models.ForeignKey(Cell, null=True, blank=True, help_text=\"\")\n\tvillage = models.ForeignKey(Village, null=True, blank=True, help_text=\"\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\tdate_time = models.DateTimeField(help_text=\"The date when this setting is entered into the system.\",auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn \"ID:\" + str(self.id) + \" - \" + str(self.tax_fee_name) + \" \" + str(self.setting_name) + \" - \" + str(self.sub_type) + \"[ \" + str(self.value) + \" ] (\" + self.i_status + \")\"\n\n\tdef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\treturn getLogMessage(self,old_data,new_data, action)\n\n\n\t@classmethod\n\tdef calculateFixedAssetTax(cls, date_from, date_to, residential=0, commercial=0, agricultural=0, land_use_type=None, *args, **kwargs):\n\n\t\tif type(date_from) is datetime:\n\t\t\tdate_from = date_from.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(date_to) is datetime:\n\t\t\tdate_to = date_to.astimezone(timezone.get_default_timezone()).date()\n\n\t\ttax = Decimal(0)\n\n\t\tcurrent_year = date_from.year\n\t\ttotal_days_in_period = Decimal((date(current_year, 12, 31) - date(current_year, 1, 1)).days + 1)\n\t\tperiods = cls.getTaxPeriods('fixed_asset_tax', date_from, date_to, *args, **kwargs)\n\t\tif not periods:\n\t\t\traise Exception(\"No tax settings found for %s, %s\" % (date_from, date_to))\n\t\tdue_month, due_day = periods[0][2]['due_date'].split('-')\n\t\tdue_date = date(date_from.year, int(due_month), int(due_day))\n\n\t\tformula_data = {}\n\n\t\tfor date_from, date_to, period_setting in periods:\n\t\t\tperiod = (date_from, date_to)\n\t\t\tformula_data[period] = {}\n\t\t\tdays_in_period = Decimal((date_to - date_from).days + 1)\n\n\n\t\t\tresidential = residential - period_setting['residential_deduction']\n\t\t\tif residential < 0:\n\t\t\t\tresidential = 0\n\t\t\ttaxable = residential + commercial + agricultural\n\t\t\ttaxable = (Decimal(taxable) / 1000).quantize(Decimal(0)) * 1000\n\n\t\t\tif taxable > 0:\n\t\t\t\tamount = (days_in_period / total_days_in_period * period_setting['tax_rate'] * taxable).quantize(Decimal('.01'))\n\t\t\t\ttax += amount\n\t\t\t\tformula_data[period]['amount'] = amount\n\t\t\telse:\n\t\t\t\tformula_data[period]['amount'] = 0\n\t\t\tformula_data[period]['tax_rate'] = period_setting['tax_rate']\n\t\t\tformula_data[period]['days'] = days_in_period\n\t\t\tformula_data[period]['taxable'] = taxable\n\n\t\ttax = Decimal(int(tax))\n\t\treturn {'amount':tax, 'due':due_date, 'days':total_days_in_period, 'due_date':due_date, 'formula_data':formula_data, 'vat':True}\n\n\n\t@classmethod\n\tdef calculateRentalIncome(cls, date_from, date_to, last_year_rental_income, last_year_bank_interest, sector=None, cell=None, village=None, *args, **kwargs):\n\t\tlast_year_rental_income = Decimal(last_year_rental_income).quantize(Decimal('.01'))\n\t\tlast_year_bank_interest = Decimal(last_year_bank_interest).quantize(Decimal('.01'))\n\t\tif type(date_from) is datetime:\n\t\t\tdate_from = date_from.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(date_to) is datetime:\n\t\t\tdate_to = date_to.astimezone(timezone.get_default_timezone()).date()\n\n\t\tcurrent_year = date_from.year\n\t\ttotal_days_in_period = Decimal((date(current_year, 12, 31) - date(current_year, 1, 1)).days + 1)\n\t\tperiods = cls.getTaxPeriods('rental_income_tax', date_from, date_to, sector=sector, cell=cell, village=village, *args, **kwargs)\n\t\tif not periods:\n\t\t\traise Exception(\"No tax settings found for %s, %s, %s, %s\" % (date_from, date_to, sector, cell, village))\n\t\tdue_month, due_day = periods[0][2]['due_date'].split('-')\n\t\tdue_date = date(date_from.year, int(due_month), int(due_day))\n\t\ttax = Decimal(0)\n\n\t\tformula_data = {}\n\t\tfor date_from, date_to, period_setting in periods:\n\t\t\tperiod_total = Decimal(0)\n\t\t\tperiod = (date_from, date_to)\n\t\t\tformula_data[period] = {}\n\t\t\tdays_in_period = Decimal((date_to - date_from).days + 1)\n\t\t\tformula_data[period]['days'] = days_in_period\n\n\t\t\tif last_year_bank_interest > 0:\n\t\t\t\ttaxable = last_year_rental_income - ( last_year_rental_income * period_setting['rate_with_bank_interest']) - last_year_bank_interest\n\t\t\t\tformula_data[period]['taxable_rate'] = period_setting['rate_with_bank_interest']\n\t\t\telse:\n\t\t\t\ttaxable = last_year_rental_income - ( last_year_rental_income * period_setting['rate']) - last_year_bank_interest\n\t\t\t\tformula_data[period]['taxable_rate'] = period_setting['rate']\n\n\t\t\tformula_data[period]['taxable'] = taxable\n\t\t\ttax_ranges = period_setting['tax_ranges']\n\t\t\tamounts = []\n\t\t\tamount = Decimal(0)\n\t\t\tif taxable > 1000000:\n\t\t\t\ttaxable = taxable - 1000000\n\t\t\t\tamount = taxable * tax_ranges['>1000000']\n\t\t\t\tamounts.append({'taxable':taxable, 'rate':tax_ranges['>1000000'], 'amount':amount})\n\t\t\t\ttaxable = 1000000\n\t\t\t\tperiod_total += amount\n\t\t\tif taxable > 180000:\n\t\t\t\ttaxable = taxable - 180000\n\t\t\t\tamount = taxable * tax_ranges['180000-1000000']\n\t\t\t\tamounts.append({'taxable':taxable, 'rate':tax_ranges['180000-1000000'], 'amount':amount})\n\t\t\t\ttaxable = 180000\n\t\t\t\tperiod_total += amount\n\n\t\t\tamount = taxable * tax_ranges['0-180000']\n\t\t\tperiod_total += amount\n\t\t\tperiod_total = (days_in_period / total_days_in_period * period_total).quantize(Decimal('0.01'))\n\t\t\ttax += period_total\n\t\t\tamounts.append({'taxable':taxable, 'rate':tax_ranges['0-180000'], 'amount':amount})\n\n\t\t\tformula_data[period]['amount'] = period_total\n\t\t\tformula_data[period]['amounts'] = amounts\n\n\t\ttax = Decimal(int(tax))\n\t\treturn {'amount':tax, 'due':due_date, 'days':total_days_in_period, 'due_date':due_date, 'rental_income':last_year_rental_income, 'interest_paid':last_year_bank_interest, 'formula_data':formula_data}\n\n\n\t@classmethod\n\tdef calculateLandLeaseFee(cls, date_from, date_to, land_use_type, size, sector=None, cell=None, village=None, *args, **kwargs):\n\t\tif type(date_from) is datetime:\n\t\t\tdate_from = date_from.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(date_to) is datetime:\n\t\t\tdate_to = date_to.astimezone(timezone.get_default_timezone()).date()\n\n\t\tsize = Decimal(size).quantize(Decimal('.0001'))\n\t\tland_use_types = None\n\t\tif land_use_type == 'Agricultural':\n\t\t\tunits = 'hectares'\n\t\t\thectares = Decimal(size * 0.0001).quantize(Decimal('.0001'))\n\t\t\tif hectares > 35:\n\t\t\t\tland_use_types = 'Agricultural(>35 ha)'\n\t\t\telif hectares >= 2 and hectares <= 35:\n\t\t\t land_use_types = 'Agricultural(2-35 ha)'\n\t\t\telif hectares > 2:\n\t\t\t\tland_use_types = 'Agricultural(>2 ha)'\n\t\telif land_use_type == 'Residential':\n\t\t\tland_use_types = 'Residential'\n\t\telif land_use_type == 'Commericial':\n\t\t\tland_use_types = 'Commercial'\n\t\telif land_use_type == 'Industrial':\n\t\t\tland_use_types = 'Industries'\n\t\telif land_use_type == 'Quarry Purpose':\n\t\t\tland_use_types = 'Quarries Exploitation'\n\t\tformula_data = {}\n\t\ttax = Decimal(0)\n\t\tcurrent_year = date_from.year\n\t\ttotal_days_in_period = Decimal((date(current_year, 12, 31) - date(current_year, 1, 1)).days + 1)\n\t\tif land_use_types:\n\t\t\ttax_periods = cls.getTaxPeriods(['land_lease','land_lease_fee'], date_from, date_to, setting_name='area_and_fee_matches', sub_type=land_use_types, sector=sector, cell=cell, village=village, *args, **kwargs)\n\t\telse:\n\t\t\ttax_periods = [(date_from, date_to, { 'value':Decimal(0), 'region':'No Fee applicable' })]\n\t\tif not tax_periods:\n\t\t\ttax_periods = [(date_from, date_to, { 'value':Decimal(0), 'region':'No Fee Found' })]\n\t\tformula_data = {}\n\t\tfor date_from, date_to, values in tax_periods:\n\t\t\tperiod = (date_from, date_to)\n\t\t\trate = values['value']\n\t\t\tdays_in_period = (date_to - date_from).days + 1\n\t\t\tamount = (Decimal(days_in_period) / Decimal(total_days_in_period) * rate * size).quantize(Decimal('0.1'))\n\t\t\tformula_data[period] = { 'days':days_in_period, 'tax_rate':rate, 'amount':amount, 'size':size, 'region':values['region'] }\n\t\t\ttax += amount\n\n\t\tdue_date = date_to\n\t\ttax = Decimal(int(tax))\n\t\treturn {'amount':tax, 'due':due_date, 'due_date':due_date, 'days':total_days_in_period, 'formula_data':formula_data }\n\n\n\t@classmethod\n\tdef calculateCleaningFee(cls, period_date, business_type, area_type, sector=None, cell=None, village=None):\n\t\t#calculate due date\n\t\ttax_periods = cls.getTaxPeriods('general_fee', period_date, period_date, sector=sector, cell=cell, village=village)\n\t\tif not tax_periods:\n\t\t\traise Exception(\"No tax settings found for %s, %s, %s, %s\" % (period_date, sector, cell, village))\n\t\tfor date_from, date_to, period_setting in tax_periods:\n\t\t\tdue_date_day = period_setting.get('monthly_due_date')\n\t\tdue_date = period_date + relativedelta(months=1)\n\t\tdue_date = date(due_date.year, due_date.month, due_date_day)\n\n\t\t#calculate amount\n\t\tsub_type = \"%s-%s\" % (area_type, business_type)\n\t\ttax_periods = cls.getTaxPeriods('cleaning_fee', period_date, period_date, sector=sector, cell=cell, village=village)\n\t\tif not tax_periods:\n\t\t\traise Exception(\"No tax settings found for %s, %s, %s, %s\" % (period_date, sector, cell, village))\n\t\tif not tax_periods:\n\t\t\treturn None, None\n\t\tfor date_from, date_to, period_setting in tax_periods:\n\t\t\ttry:\n\t\t\t\trate = period_setting['fee_matches'][sub_type]\n\t\t\texcept KeyError:\n\t\t\t\trate = None\n\t\treturn rate, due_date\n\n\t@classmethod\n\tdef calculateTradingLicenseTax(cls, date_from, date_to, turnover, sector=None, *args, **kwargs):\n\t\tif type(date_from) is datetime:\n\t\t\tdate_from = date_from.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(date_to) is datetime:\n\t\t\tdate_to = date_to.astimezone(timezone.get_default_timezone()).date()\n\n\t\tturnover = Decimal(turnover).quantize(Decimal('0.01'))\n\t\tcurrent_year = date_from.year\n\t\ttotal_days_in_period = Decimal((date(current_year, 12, 31) - date(current_year, 1, 1)).days + 1)\n\t\ttax = Decimal(0)\n\t\ttax_periods = Setting.getTaxPeriods('trading_license_tax', date_from, date_to, sector=sector, *args, **kwargs)\n\n\t\tif not tax_periods:\n\t\t\traise Exception(\"No tax settings found for %s, %s, %s\" % (date_from, date_to, sector))\n\t\tformula_data = {}\n\t\tfor date_from, date_to, period_setting in tax_periods:\n\t\t\tdays_in_period = Decimal((date_to - date_from).days + 1)\n\t\t\tperiod = (date_from, date_to)\n\t\t\tformula_data[period] = { 'days':days_in_period }\n\t\t\tsettings = period_setting['business_yearly_turnover_and_tax_matches']\n\t\t\tif turnover <= 40000000:\n\t\t\t\trate = Decimal(settings.get('Up to 40,000000 Rwf'))\n\t\t\telif turnover > 40000000 and turnover <= 60000000:\n\t\t\t\trate = Decimal(settings.get('From 40,000,001 to 60,000,000'))\n\t\t\telif turnover > 60000000 and turnover <= 150000000:\n\t\t\t\trate = Decimal(settings.get('From 60,000,001 to 150,000,000'))\n\t\t\telse:\n\t\t\t\trate = Decimal(settings.get('Above 150 Million Rwf'))\n\t\t\tformula_data[period]['rate'] = rate\n\t\t\tamount = (days_in_period / total_days_in_period * rate).quantize(Decimal('0.01'))\n\t\t\tformula_data[period]['amount'] = amount\n\t\t\ttax += amount\n\t\ttax = Decimal(int(tax))\n\t\treturn {'amount':tax, 'due':date_to, 'due_date':date_to, 'days':total_days_in_period, 'turnover':turnover, 'formula_data':formula_data, 'vat':True}\n\n\t@classmethod\n\tdef get_due_date(cls, tax_fee_name, period_date, sector=None, district=None, *args, **kwargs):\n\t\tcurrent_date = date.today()\n\t\tif tax_fee_name in ('trading_license_tax', 'land_lease_fee'):\n\t\t\treturn date(period_date.year, 12, 31)\n\t\tdue_date = cls.getTaxSetting(tax_fee_name, 'due_date', current_date, current_date, sector, district, *args, **kwargs)\n\t\tdue_month, due_day = due_date.split('-')\n\t\treturn date(period_date.year, int(due_month), int(due_day))\n\n\n\t@classmethod\n\tdef getTaxSetting(cls, tax_fee_name, setting_name, date_from, date_to, sector=None, district=None, *args, **kwargs):\n\t\t\"\"\"gets the latest setting for a tax\"\"\"\n\t\tperiods = cls.getTaxPeriods(tax_fee_name, date_from, date_to, sector, district, *args, **kwargs)\n\t\tif not periods:\n\t\t\traise Exception(\"Could not find setting - %s from %s to %s\" % (tax_fee_name, date_from, date_to))\n\t\treturn periods[0][2][setting_name]\n\n\n\t@classmethod\n\tdef getFees(cls, district=None, sector=None, cell=None, village=None, *args, **kwargs):\n\t\t\"\"\"\n\t\treturns the relevant tax period info as a dictionary\n\t\tin the format: {(date_from, date_to), { setting_name1: value, setting_name2: value2 }, ...}\n\t\teg. {((2013,01,01), (2013,04,31)):{ 'tax_rate': 0.1, 'due_date': (2013,05,31), ...}, ... }\n\t\t( (date_from, date_to, {values}), (date_from, date_to, {values}) )\n\t\tThe order of precedence s Sector tax values, District tax values then\n\t\ttax values with no associated Sector or District\n\t\t\"\"\"\n\n\t\tif district and type(district) is int:\n\t\t\tdistrict = District.objectsIgnorePermission.get(pk=district)\n\n\t\tif sector and type(sector) is int:\n\t\t\tsector = Sector.objectsIgnorePermission.get(pk=sector)\n\n\t\tif cell and type(cell) is int:\n\t\t\tcell = Cell.objects.get(pk=cell)\n\n\t\tif village and type(village) is int:\n\t\t\tvillage = Village.objects.get(pk=village)\n\n\t\tsettings = cls.objects.filter(tax_fee_name='misc_fee', i_status='active')\n\n\t\tif village:\n\t\t\tsettings = settings.filter(Q(village__isnull=True) | Q(village=village))\n\t\t\tcell = village.cell\n\t\telse:\n\t\t\tsettings = settings.filter(village__isnull=True)\n\n\t\tif cell:\n\t\t\tsettings = settings.filter(Q(cell__isnull=True) | Q(cell=cell))\n\t\t\tsector = cell.sector\n\t\telse:\n\t\t\tsettings = settings.filter(cell__isnull=True)\n\n\t\tif sector:\n\t\t\tsettings = settings.filter(Q(sector__isnull=True) | Q(sector=sector))\n\t\t\tdistrict = sector.district\n\t\telse:\n\t\t\tsettings = settings.filter(sector__isnull=True)\n\n\t\tif district:\n\t\t\tsettings = settings.filter(Q(district__isnull=True) | Q(district=district))\n\t\telse:\n\t\t\tsettings = settings.filter(district__isnull=True)\n\n\t\tsettings = settings.select_related('district','sector', 'cell', 'village').order_by('-valid_from', '-village', '-cell', '-sector', '-district', 'sub_type')\n\n\t\tfees = {}\n\t\tfor setting in settings:\n\t\t\tsetting_region = setting.village or setting.cell or setting.sector or setting.district\n\t\t\tcategory = fees.setdefault(setting.setting_name, {})\n\t\t\tsub_type = category.setdefault(setting.sub_type, { 'value': setting.value, 'description':setting.description, 'valid_from':setting.valid_from, 'region': setting_region })\n\t\t\tif setting_region == sub_type['region'] and setting.valid_from >= sub_type['valid_from'] and date.today() >= setting.valid_from or setting_region != sub_type['region']:\n\t\t\t\tsub_type['value'] = Decimal(setting.value)\n\t\t\t\tsub_type['description'] = setting.description\n\t\t\t\tsub_type['region'] = setting_region\n\t\t\t\tsub_type['pk'] = setting.pk\n\n\t\treturn fees\n\n\n\t@classmethod\n\tdef getTaxPeriods(cls, tax_fee_name, date_from, date_to, setting_name=None, sub_type=None, district=None, sector=None, cell=None, village=None, *args, **kwargs):\n\t\t\"\"\"\n\t\treturns the relevant tax period info as a dictionary\n\t\tin the format: {(date_from, date_to), { setting_name1: value, setting_name2: value2 }, ...}\n\t\teg. {((2013,01,01), (2013,04,31)):{ 'tax_rate': 0.1, 'due_date': (2013,05,31), ...}, ... }\n\t\t( (date_from, date_to, {values}), (date_from, date_to, {values}) )\n\t\tThe order of precedence s Sector tax values, District tax values then\n\t\ttax values with no associated Sector or District\n\t\t\"\"\"\n\n\t\tif district and type(district) is int:\n\t\t\tdistrict = District.objectsIgnorePermission.get(pk=district)\n\n\t\tif sector and type(sector) is int:\n\t\t\tsector = Sector.objectsIgnorePermission.get(pk=sector)\n\n\t\tif cell and type(cell) is int:\n\t\t\tcell = Cell.objects.get(pk=cell)\n\n\t\tif village and type(village) is int:\n\t\t\tvillage = Village.objects.get(pk=village)\n\n\t\tif type(date_from) is datetime:\n\t\t\tdate_from = date_from.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(date_to) is datetime:\n\t\t\tdate_to = date_to.astimezone(timezone.get_default_timezone()).date()\n\n\t\tif type(tax_fee_name) is not list:\n\t\t\ttax_fee_name = [tax_fee_name]\n\n\t\tsettings = cls.objects.filter(tax_fee_name__in=tax_fee_name, valid_from__lte=date_to, i_status='active')\n\n\t\tif setting_name:\n\t\t\tsettings = settings.filter(setting_name=setting_name)\n\n\t\tif sub_type:\n\t\t\tif not setting_name:\n\t\t\t\traise Exception(\"You must specify a setting name\")\n\t\t\tif hasattr(sub_type, \"__iter__\"):\n\t\t\t\tsettings = settings.filter(sub_type__in=sub_type)\n\t\t\telse:\n\t\t\t\tsettings = settings.filter(sub_type=sub_type)\n\n\t\tif village:\n\t\t\tsettings = settings.filter(Q(village__isnull=True) | Q(village=village))\n\t\t\tcell = village.cell\n\t\telse:\n\t\t\tsettings = settings.filter(village__isnull=True)\n\n\t\tif cell:\n\t\t\tsettings = settings.filter(Q(cell__isnull=True) | Q(cell=cell))\n\t\t\tsector = cell.sector\n\t\telse:\n\t\t\tsettings = settings.filter(cell__isnull=True)\n\n\t\tif sector:\n\t\t\tsettings = settings.filter(Q(sector__isnull=True) | Q(sector=sector))\n\t\t\tdistrict = sector.district\n\t\telse:\n\t\t\tsettings = settings.filter(sector__isnull=True)\n\n\t\tif district:\n\t\t\tsettings = settings.filter(Q(district__isnull=True) | Q(district=district))\n\t\telse:\n\t\t\tsettings = settings.filter(district__isnull=True)\n\n\t\tsettings = settings.order_by('-valid_from', '-village', '-cell', '-sector', '-district')\n\n\t\tsettings = [setting for setting in settings]\n\n\t\tif not settings:\n\t\t\treturn None\n\t\t\t# raise Exception(\"No Settings found for tax fee: %s, from %s to %s, setting name:%s, sub type: %s, district: %s, sector: %s, cell: %s, village: %s\" % (tax_fee_name, date_from, date_to, setting_name, sub_type, district, sector, cell, village))\n\n\t\t# set the most recent period\n\t\t#import pdb\n\t\t#pdb.set_trace()\n\t\tvalid_from = settings[0].valid_from\n\t\tvalid_to = date_to\n\n\t\tperiods = {}\n\t\tfor setting in settings:\n\t\t\tregion = setting.village or setting.cell or setting.sector or setting.district or None\n\t\t\tif region:\n\t\t\t\tregion_name = region.name\n\t\t\telse:\n\t\t\t\tregion_name = None\n\t\t\t# get the next period setting\n\t\t\tif setting.valid_from < valid_from:\n\t\t\t\tvalid_to = valid_from - timedelta(days=1)\n\t\t\t\t#stop if period is out of range\n\t\t\t\tif valid_to < date_from:\n\t\t\t\t\tbreak;\n\n\t\t\t# set the setting start range if less than date_from\n\t\t\tvalid_from = setting.valid_from\n\t\t\tif valid_from < date_from:\n\t\t\t\tstart_from = date_from\n\t\t\telse:\n\t\t\t\tstart_from = valid_from\n\n\t\t\tperiod = periods.setdefault((start_from, valid_to), {})\n\t\t\ttry:\n\t\t\t\tvalue = Decimal(setting.value)\n\t\t\texcept:\n\t\t\t\tvalue = setting.value\n\n\t\t\tperiod['region'] = region_name\n\t\t\tif sub_type:\n\t\t\t\tif hasattr(sub_type,'__iter__'):\n\t\t\t\t\tperiod[setting.sub_type] = value\n\t\t\t\telse:\n\t\t\t\t\tperiod['value'] = value\n\t\t\telif setting_name:\n\t\t\t\tif setting.sub_type:\n\t\t\t\t\tperiod[setting.sub_type] = value\n\t\t\t\telse: #setting_name provided, no setting.sub_type\n\t\t\t\t\tperiod['value'] = value\n\t\t\telse: # no setting name\n\t\t\t\tif setting.sub_type:\n\t\t\t\t\tst = period.setdefault(setting.setting_name, {})\n\t\t\t\t\tst[setting.sub_type] = value\n\t\t\t\telse:\n\t\t\t\t\tperiod[setting.setting_name] = value\n\n\t\tperiods = [ (dates[0], dates[1], values) for dates, values in periods.iteritems() ]\n\t\tperiods.sort(key=lambda x:x[0], reverse=True)\n\t\treturn periods\n\n\n# Model for Receipt of Multiple Tax/Fee payment\nclass MultipayReceipt(models.Model):\n\tamount = models.DecimalField(max_digits = 20, decimal_places = 2)\n\tuser = models.ForeignKey(PMUser, null=True, blank = True)\n\tdate_time = models.DateTimeField(help_text='This is the Date and Time the Entry has been entered into the database.',auto_now_add=True)\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\n\n# Model for Receipt of Multiple Tax/Fee payment\nclass MultipayReceiptPaymentRelation(models.Model):\n\tpayfee = models.ForeignKey(PayFee, related_name=\"receipt_relations\")\n\treceipt = models.ForeignKey(MultipayReceipt, related_name=\"payment_relations\")\n\ti_status = models.CharField(max_length = 10, choices = variables.status_choices, default='active', blank = True)\n\n\n\n#General functions used in many models\ndef getLogMessage(self,old_data=None,new_data=None, action=None):\n\t\"\"\"\n\treturn tailored log message for different actions taken on this citizen\n\t\"\"\"\n\tif action == \"view\":\n\t\treturn \"view \" + self.__class__.__name__ + \" [\" + self.__unicode__() + \"]\"\n\tif action == \"delete\":\n\t\treturn \"delete \" + self.__class__.__name__ + \" [\" + self.__unicode__() + \"]\"\n\tif action == \"add\":\n\t\treturn \"add \" + self.__class__.__name__ + \" [\" + self.__unicode__() + \"]\"\n\tif action == \"change\":\n\t\tmessage=\"\"\n\t\tcount = 0\n\t\tif old_data != None:\n\t\t\tfor key, value in old_data.iteritems():\n\t\t\t\tif old_data[key] != new_data[key]:\n\t\t\t\t\tif count != 0:\n\t\t\t\t\t\tmessage = message + \",\"\n\t\t\t\t\tcount = count + 1\n\t\t\t\t\tif type(value) is not list:\n\t\t\t\t\t\tmessage = message + \" change \"+key + \" from '\"+ str(value) + \"' to '\"+str(new_data[key])+\"'\"\n\t\tif message == \"\":\n\t\t\tmessage = \"No change made\"\n\t\tmessage = message + \" on \" + self.__class__.__name__ + \" [\" + self.__unicode__() + \"]\"\n\t\treturn message\n\n\n\nclass Installment(models.Model):\n\tamount = models.DecimalField(max_digits=20, decimal_places=2)\n\tdue = models.DateField()\n\tpropertyTaxItem = models.ForeignKey(PropertyTaxItem, null=True, blank=True, related_name=\"installments\")\n\trentalIncomeTax = models.ForeignKey(RentalIncomeTax, null=True, blank=True, related_name=\"installments\")\n\ttradingLicenseTax = models.ForeignKey(TradingLicenseTax, null=True, blank=True, related_name=\"installments\")\n\tfee = models.ForeignKey(Fee, null=True, help_text=\"\", related_name=\"installments\")\n\t# tax = models.ForeignKey(Tax, null=True, help_text=\"\", related_name=\"installments\")\n\n\tdef __unicode__(self):\n\t\tif hasattr(self, 'paid'):\n\t\t\treturn \"%s due on %s: %s paid\" % (self.amount, self.due, self.paid)\n\t\telse:\n\t\t\treturn \"%s due on %s\" % (self.amount, self.due)\n\n\t@staticmethod\n\tdef previewInstallments(amount, date_from):\n\t\tmonths = 3\n\t\tno_installments = 4\n\t\tinstallments = {}\n\t\tdue_date = date_from\n\n\t\tamount = (amount / no_installments).quantize(Decimal('.01'))\n\t\tfor i in range(no_installments):\n\t\t\tdue_date = due_date + relativedelta(months=months-1) + relativedelta(day=31)\n\t\t\tinstallments[due_date] = amount\n\t\treturn installments\n\n","sub_path":"jtax/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":78699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"364775612","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 23 17:01:57 2018\n\n@author: macgx\n\"\"\"\nimport pandas as pd\nfrom pandas.api.types import is_string_dtype, is_numeric_dtype\nfrom sklearn.preprocessing import LabelEncoder, scale\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport arff\nimport os\n\n\n\nclass PreprocessData():\n def __init__(self, dataname):\n self.dataname = dataname\n ## get dataset from UCI_data_arff directory\n current_script_path = os.path.dirname(os.path.abspath(__file__)).split('/')\n # os.path.dirname does not include file name\n # current_script_path.pop()\n current_script_path[-1] = 'UCI_data_arff'\n self.datapath = '/'.join(current_script_path) \n\n def test_preprocess(self):\n if self.dataname == 'pim':\n with open('{}/pima.arff'.format(self.datapath), 'r') as f1:\n data = arff.load(f1)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[8] = data[8].astype('int64')\n X = data[data.columns[:8]]\n y = data[data.columns[8]]\n\n return X, y\n\n def preprocess(self):\n if self.dataname == 'adlt':\n with open('{}/adult_train.arff'.format(self.datapath), 'r') as f1:\n data = arff.load(f1)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[14] = data[14].astype('int64')\n \n # with open('{}/adult_test.arff'.format(self.datapath), 'r') as f2:\n # data_test = arff.load(f2)\n # data_test = pd.DataFrame(data_test['data'])\n # data_test[14] = data_test[14].astype('int64')\n \n # data = data.append(data_test, ignore_index=True)\n X = data[data.columns[:14]]\n y = data[data.columns[14]]\n return X, y\n \n elif self.dataname == 'pim':\n with open('{}/pima.arff'.format(self.datapath), 'r') as f3:\n data = arff.load(f3)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[8] = data[8].astype('int64')\n\n X = data[data.columns[:8]]\n y = data[data.columns[8]]\n \n return X, y\n \n elif self.dataname == 'bnk':\n with open('{}/bank.arff'.format(self.datapath), 'r') as f4:\n data = arff.load(f4)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[16] = data[16].astype('int64')\n \n X = data[data.columns[:16]]\n y = data[data.columns[16]]\n return X, y \n \n elif self.dataname == 'car':\n # Characteristics: has missing value\n with open('{}/car.arff'.format(self.datapath), 'r') as f5:\n data = arff.load(f5)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[6] = data[6].astype('int64')\n \n X = data[data.columns[:6]]\n y = data[data.columns[6]]\n return X, y\n \n elif self.dataname == 'ches':\n with open('{}/chess-krvk.arff'.format(self.datapath), 'r') as f6:\n data = arff.load(f6)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[6] = data[6].astype('int64')\n \n X = data[data.columns[:6]]\n y = data[data.columns[6]] \n return X, y \n \n elif self.dataname == 'ltr':\n with open('{}/letter.arff'.format(self.datapath), 'r') as f7:\n data = arff.load(f7)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[16] = data[16].astype('int64')\n \n X = data[data.columns[:16]]\n y = data[data.columns[16]]\n return X, y \n \n elif self.dataname == 'mgic':\n with open('{}/magic.arff'.format(self.datapath), 'r') as f8:\n data = arff.load(f8)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[10] = data[10].astype('int64')\n \n X = data[data.columns[:10]]\n y = data[data.columns[10]]\n return X, y \n \n elif self.dataname == 'msk':\n with open('{}/musk-2.arff'.format(self.datapath), 'r') as f9:\n data = arff.load(f9)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[166] = data[166].astype('int64')\n \n X = data[data.columns[:166]]\n y = data[data.columns[166]]\n return X, y\n \n elif self.dataname == 'p-blk':\n with open('{}/page-blocks.arff'.format(self.datapath), 'r') as f10:\n data = arff.load(f10)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[10] = data[10].astype('int64')\n \n X = data[data.columns[:10]]\n y = data[data.columns[10]]\n return X, y\n\n elif self.dataname == 'sem':\n with open('{}/semeion.arff'.format(self.datapath), 'r') as f11:\n data = arff.load(f11)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[256] = data[256].astype('int64')\n \n X = data[data.columns[:256]]\n y = data[data.columns[256]] \n return X, y\n \n elif self.dataname == 'spam':\n with open('{}/spambase.arff'.format(self.datapath), 'r') as f12:\n data = arff.load(f12)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[57] = data[57].astype('int64')\n \n X = data[data.columns[:57]]\n y = data[data.columns[57]] \n return X, y\n \n elif self.dataname == 's-gc':\n with open('{}/statlog-german-credit.arff'.format(self.datapath), 'r') as f13:\n data = arff.load(f13)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[24] = data[24].astype('int64')\n \n X = data[data.columns[:24]]\n y = data[data.columns[24]]\n return X, y\n \n elif self.dataname == 's-im':\n with open('{}/statlog-image.arff'.format(self.datapath), 'r') as f14:\n data = arff.load(f14)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[18] = data[18].astype('int64')\n \n X = data[data.columns[:18]]\n y = data[data.columns[18]]\n return X, y\n \n elif self.dataname == 's-sh':\n #Approximately 80% of the data belongs to class 1. \n #Therefore the default accuracy is about 80%. \n #The aim here is to obtain an accuracy of 99 - 99.9%. \n with open('{}/statlog-shuttle_train.arff'.format(self.datapath), 'r') as f15:\n data = arff.load(f15)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[9] = data[9].astype('int64')\n \n X = data[data.columns[:9]]\n y = data[data.columns[9]] \n return X, y\n \n elif self.dataname == 's-pl':\n with open('{}/steel-plates.arff'.format(self.datapath), 'r') as f16:\n data = arff.load(f16)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[27] = data[27].astype('int64')\n \n X = data[data.columns[:27]]\n y = data[data.columns[27]] \n return X, y\n \n elif self.dataname == 'tita':\n with open('{}/titanic.arff'.format(self.datapath), 'r') as f17:\n data = arff.load(f17)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[3] = data[3].astype('int64')\n \n X = data[data.columns[:3]]\n y = data[data.columns[3]] \n return X, y\n \n elif self.dataname == 'thy':\n with open('{}/thyroid_train.arff'.format(self.datapath), 'r') as f18:\n data = arff.load(f18)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[21] = data[21].astype('int64')\n \n X = data[data.columns[:21]]\n y = data[data.columns[21]] \n return X, y\n \n elif self.dataname == 'wine':\n with open('{}/wine-quality-red.arff'.format(self.datapath), 'r') as f19:\n data = arff.load(f19)\n data = pd.DataFrame(data['data'])\n ## convert str to int for target variable, manually modify target column index\n data[11] = data[11].astype('int64')\n \n X = data[data.columns[:11]]\n y = data[data.columns[11]] \n return X, y\n\n elif self.dataname == '1_46':\n data = pd.read_csv('{}/splice_46.csv'.format(self.datapath), header=0, sep=',')\n data.drop(['Instance_name'], axis=1, inplace=True)\n \n ### my preprocessing strategy: convert categorical variables to [-1, 1]\n ### and standardize all attributes including previous converted-categorical \n # attribute_encoder = {'R': -1, 'S': -5 / 7, 'D': -3 / 7, 'N': 0, 'A': 1 / 7, 'G': 3 / 7, 'T': 5 / 7, 'C': 1}\n # target_encoder = {'N': 0, 'EI': 1, 'IE': 2}\n # for col in data.columns[:-1]:\n # data[col] = data[col].map(attribute_encoder) \n # data['Class'] = data['Class'].map(target_encoder)\n # # standardize all attributes\n # data[data.columns[:-1]] = scale(data[data.columns[:-1]])\n \n ### paper author's strategy: convert categorical variables to integer\n ### no standardization\n attribute_encoder = {'R': 1, 'S': 2, 'D': 3, 'N': 4, 'A': 5, 'G': 6, 'T': 7, 'C': 8}\n target_encoder = {'N': 0, 'EI': 1, 'IE': 2}\n for col in data.columns[:-1]:\n data[col] = LabelEncoder().fit_transform(data[col])\n \n data['Class'] = data['Class'].map(target_encoder)\n \n #TODO: another strategy: data[col] = data[col].map(attribute_encoder) \n X = data[data.columns[:-1]]\n y = data['Class']\n return X, y\n\n # TODO: URL ID 184 is kropt, which is same with UCI chess-krvk\n # URL ID 180 but datafile 184 is covertype.txt\n elif self.dataname == '2_184':\n ## OpenML dataset 184 is same as UCI chess-krvk\n ## paper author's strategy: no standardization\n with open('{}/dataset_188_kropt.arff'.format(self.datapath), 'r') as f20:\n data = arff.load(f20)\n data = pd.DataFrame(data['data'])\n \n attribute_encoder = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8}\n for col in data.columns[:6]:\n if col in [1,3,5]: ## convert str to int \n data[col] = data[col].astype('int64')\n else:\n data[col] = data[col].map(attribute_encoder) \n y = LabelEncoder().fit_transform(data[6])\n X = data[data.columns[:6]] \n return X, y\n\n elif self.dataname == '3_389':\n with open('{}/fbis.wc.arff'.format(self.datapath), 'r') as f21:\n data = arff.load(f21)\n data = pd.DataFrame(data['data'])\n y = LabelEncoder().fit_transform(data[data.columns[-1]])\n X = data[data.columns[:-1]]\n # X = scale(data[data.columns[:-1]])\n return X, y\n\n elif self.dataname == '4_772':\n # Characteristics: no missing value\n data = pd.read_csv('{}/quake_772.csv'.format(self.datapath), header=0, sep=',')\n # X = scale(data[data.columns[:-1]])\n X = data[data.columns[:-1]]\n y = LabelEncoder().fit_transform(data[data.columns[-1]])\n return X, y\n\n elif self.dataname == '5_917':\n data = pd.read_csv('{}/fri_c1_1000_25_917.csv'.format(self.datapath), header=0, sep=',')\n # X = scale(data[data.columns[:-1]])\n X = data[data.columns[:-1]]\n y = LabelEncoder().fit_transform(data[data.columns[-1]])\n return X, y\n # TODO: not sure it's 1049\n elif self.dataname == '6_1049':\n # Characteristics: all attributes are numeric, binary class\n data = pd.read_csv('{}/pc4_1049.csv'.format(self.datapath), header=0, sep=',')\n y = data['c'].map({True: 1, False: 0})\n # X = scale(data[data.columns[:-1]])\n X = data[data.columns[:-1]]\n return X, y \n\n","sub_path":"EGO-ss/PreprocessData.py","file_name":"PreprocessData.py","file_ext":"py","file_size_in_byte":14336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"439908208","text":"# Autor: Jesús Roberto Herrera Vieyra, A01377230\n# Descripcion: Programa que calcula el total de alumos y los porcentajes de cada género\n# Escribe tu programa después de esta línea.\nmujeres = int(input(\"Número de mujeres: \"))\nhombres = int(input(\"Número de hombres:\"))\n\ntotal= hombres+mujeres\nporcentajeH= (hombres*100)/total\nporcentajeM=(mujeres*100)/total\n\nprint(\"Total de alumnos: \",(total))\nprint(\"Porcentaje de mujeres: \",\"{0:.1f}\".format(porcentajeM),\"%\")\nprint(\"Porcentaje de hombres: \",\"{0:.1f}\".format(porcentajeH),\"%\")\n","sub_path":"porcentajes.py","file_name":"porcentajes.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"581622049","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 20 14:59:49 2017\r\n\r\n@author: JohannesMHeinrich\r\n\"\"\"\r\n\r\nfrom time import localtime, strftime\r\nfrom ctypes import *\r\n\r\nimport time\r\n\r\ndll_HF = windll.LoadLibrary(\"C:\\\\Windows\\\\System32\\\\wlmData.dll\")\r\n\r\n \r\n#import numpy as np\r\n#import matplotlib.pyplot as plt\r\n#import matplotlib.cm as cm\r\n \r\nclass HighFinesse_WM():\r\n \"\"\" Class to interface the HighFinesse_WM\r\n \r\n usage:\r\n to fill later\r\n \"\"\"\r\n def __init__(self):\r\n \r\n print('HighFinesse WM initialized')\r\n \r\n # the ControlWLM/Ex functions start, hide or terminate the WL server application\r\n# Action = 'cCtrlWLMHide'\r\n# control_show = dll_HF.ControlWLM(Action, None, None)\r\n# \r\n# print(control_show)\r\n\r\n\r\n\r\n\r\n \r\n def get_frequency(self):\r\n\r\n dll_HF.GetFrequency.restype=c_double\r\n \r\n frequency = c_double()\r\n frequency = dll_HF.GetFrequency(frequency)\r\n\r\n return frequency\r\n\r\n \r\n \r\n \r\n def get_wavelength(self):\r\n\r\n dll_HF.GetWavelength.restype=c_double\r\n \r\n wavelength = c_double()\r\n wavelength = dll_HF.GetWavelength(wavelength)\r\n\r\n return wavelength\r\n\r\n \r\n \r\n def get_temperature(self):\r\n \r\n dll_HF.GetTemperature.restype=c_double\r\n \r\n temperature = c_double()\r\n temperature = dll_HF.GetTemperature(temperature)\r\n\r\n return temperature\r\n\r\n\r\n\r\n\r\n\r\n\r\n#wv = HighFinesse_WM()\r\n#a = []\r\n#for i in range(50):\r\n# b = wv.get_frequency()\r\n# time.sleep(0.1)\r\n# a.append(b)\r\n# \r\n#import numpy as np\r\n#import matplotlib.pyplot as plt\r\n#\r\n#x = np.arange(0, 50, 1);\r\n#\r\n#plt.plot(x, a)\r\n#plt.show()","sub_path":"library/instr_HighFinesseWM_WS07.py","file_name":"instr_HighFinesseWM_WS07.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"599992754","text":"def print5to50():\n for num in range(5, 50):\n div = 2\n while div < num:\n if num % div == 0:\n break\n div=div+1\n if div == num:\n print(str(num) + ' is a prime number')\n\n\nprint5to50()\n","sub_path":"prime5to50.py","file_name":"prime5to50.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"120969240","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^signup', views.singup, name='signup'),\n url(r'^login', views.login, name='login'),\n url(r'^test', views.test_get, name='test_get'),\n url(r'^receive', views.receive, name='receive'),\n url(r'^get_login', views.get_login, name='loginGet'),\n]","sub_path":"athenatech/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"415810489","text":"import csv\r\nimport numpy as np\r\nfrom sklearn.svm import SVR\r\nimport matplotlib.pyplot as plt\r\nimport mysql.connector\r\n\r\n\r\ndef main():\r\n con=mysql.connector.connect(host='localhost',user='root',passwd='qwerty',database='project')\r\n\r\n cursor=con.cursor()\r\n cursor.execute(\"SELECT count(mtr_no) FROM project.data_log where mtr_no=111;\")\r\n n=cursor.fetchone()[0]\r\n\r\n dates = [i for i in range(n)]\r\n prices = []\r\n\r\n cursor.execute(\"select `reading` from `data_log` where mtr_no=111\")\r\n l=cursor.fetchall()\r\n for i in range(365):\r\n prices.append(l[i][0])\r\n\r\n def predict_prices(dates, prices, x):\r\n dates = np.array([dates]).reshape(-1,1)#np.reshape(dates,(len(dates),1))\r\n #array.reshape(1, -1)\r\n #svr_lin= SVR(kernel = 'linear',C=1e3)\r\n #svr_poly=SVR(kernel= 'poly', C=1e3,degree = 2)\r\n svr_rbf= SVR(kernel= 'rbf', C=1e3,gamma=0.1)\r\n #svr_lin.fit(dates,prices)\r\n #svr_poly.fit(dates,prices)\r\n svr_rbf.fit(dates,prices)\r\n\r\n plt.scatter(dates,prices,color='black',label='Data')\r\n plt.plot(dates,svr_rbf.predict(dates),color='red',label='RBF model')\r\n #plt.plot(dates,svr_lin.predict(dates),color='green',label='Linear model')\r\n #plt.plot(dates,svr_poly.predict(dates),color='blue',label='Polynomial model')\r\n plt.xlabel('Date')\r\n plt.ylabel('Price')\r\n plt.title('Support Vector Regression')\r\n plt.legend()\r\n plt.show()\r\n return svr_rbf.predict(np.array([x]).reshape(1,1)),#svr_lin.predict(np.array([x]).reshape(1,1)), svr_poly.predict(np.array([x]).reshape(1,1))\r\n\r\n#get_data('C:\\\\Users\\\\Master-Pc\\\\Desktop\\\\a.csv')\r\nmain()\r\npredicted_price= main.predict_prices(dates,prices,366)\r\nprint(predicted_price)\r\n \r\n\r\n \r\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"581582643","text":"'''\nCreated on May 6, 2019\n\n@author: courtneyfergusonlee\n'''\n\n\ndef get_expected(player_1, player_2):\n # Returns the expected value for each player\n expected_1 = 1 / \\\n (1 + 10**((player_2['rating'] - player_1['rating']) / 400))\n expected_2 = 1 / \\\n (1 + 10**((player_1['rating'] - player_2['rating']) / 400))\n\n return expected_1, expected_2\n\n\ndef get_k_factor(player):\n # Returns the k-factor from a player dictionary\n if player['num_games'] < 30:\n return 40\n elif player['rating'] < 2400:\n return 20\n elif player['rating'] >= 2400:\n return 10\n\n\ndef get_ratings(player_1, player_2):\n # Returns player ratings from two player dictionaries\n outcome_dict = {\n 'win': 1,\n 'loss': 0,\n 'draw': .5\n }\n expected_1, expected_2 = get_expected(player_1, player_2)\n k1 = get_k_factor(player_1)\n k2 = get_k_factor(player_2)\n\n player_1_new = player_1['rating'] + k1 * \\\n (outcome_dict[player_1['outcome']] - expected_1)\n player_2_new = player_2['rating'] + k2 * \\\n (outcome_dict[player_2['outcome']] - expected_2)\n\n return player_1_new, player_2_new\n\n\nif __name__ == '__main__':\n player_1 = {\n 'rating': 956,\n 'num_games': 100,\n 'outcome': 'win'\n }\n\n player_2 = {\n 'rating': 907,\n 'num_games': 100,\n 'outcome': 'loss'\n }\n\n ratings = get_ratings(player_1, player_2)\n print(\"Ratings: {}\".format(ratings))\n","sub_path":"data_utilities/elo_algorithm.py","file_name":"elo_algorithm.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"266928981","text":"\n\"\"\"\nUnitary Event (UE) analysis is a statistical method that\n enables to analyze in a time resolved manner excess spike correlation\n between simultaneously recorded neurons by comparing the empirical\n spike coincidences (precision of a few ms) to the expected number \n based on the firing rates of the neurons.\n\nReferences:\n-----------\nGruen, Diesmann, Grammont, Riehle, Aertsen (1999) J Neurosci Methods, 94(1): 67-79.\nGruen, Diesmann, Aertsen (2002a,b) Neural Comput, 14(1): 43-80; 81-19.\nGruen S, Riehle A, and Diesmann M (2003) Effect of cross-trial nonstationarity \non joint-spike events Biological Cybernetics 88(5):335-351. \nGruen S (2009) Data-driven significance estimation of precise spike correlation. \nJ Neurophysiology 101:1126-1140 (invited review)\n\"\"\"\n\n\n\n\n\nimport numpy as np\nimport quantities as pq\nimport neo\nimport warnings\nimport elephant.conversion as conv\nimport scipy\n\n\ndef hash_from_pattern(m, N, base=2):\n \"\"\"\n Calculate for a spike pattern or a matrix of spike patterns\n (provide each pattern as a column) composed of N neurons a\n unique number.\n\n\n Parameters:\n -----------\n m: list of integers\n matrix of 0-1 patterns as columns,\n shape: (number of neurons, number of patterns)\n N: integer\n number of neurons is required to be equal to the number\n of rows\n base: integer\n base for calculation of the number from binary\n sequences (= pattern).\n Default is 2\n\n Returns:\n --------\n list of integers:\n An array containing the hash values of each pattern,\n shape: (number of patterns)\n\n Raises:\n -------\n ValueError: if matrix m has wrong orientation\n\n Examples:\n ---------\n descriptive example:\n m = [0\n 1\n 1]\n N = 3\n base = 2\n hash = 0*2^2 + 1*2^1 + 1*2^0 = 3\n\n second example:\n >>> import numpy as np\n >>> m = np.array([[0, 1, 0, 0, 1, 1, 0, 1],\n [0, 0, 1, 0, 1, 0, 1, 1],\n [0, 0, 0, 1, 0, 1, 1, 1]])\n\n >>> hash_from_pattern(m,N=3)\n array([0, 4, 2, 1, 6, 5, 3, 7])\n \"\"\"\n # check the consistency between shape of m and number neurons N\n if N != np.shape(m)[0]:\n raise ValueError('patterns in the matrix should be column entries')\n\n # generate the representation for binary system\n v = np.array([base**x for x in range(N)])\n # reverse the order\n v = v[np.argsort(-v)]\n # calculate the binary number by use of scalar product\n return np.dot(v,m)\n\n\ndef inverse_hash_from_pattern(h, N, base=2):\n \"\"\"\n Calculate the 0-1 spike patterns (matrix) from hash values\n\n Parameters:\n -----------\n h: list of integers\n list or array of hash values, length: number of patterns\n N: integer\n number of neurons\n base: integer\n base for calculation of the number from binary\n sequences (= pattern).\n Default is 2\n\n Raises:\n -------\n ValueError: if the hash is not compatible with the number\n of neurons hash value should not be larger than the biggest\n possible hash number with given number of neurons\n (e.g. for N = 2, max(hash) = 2^1 + 2^0 = 3\n , or for N = 4, max(hash) = 2^3 + 2^2 + 2^1 + 2^0 = 15)\n\n Returns:\n --------\n numpy.array:\n A matrix of shape: (N, number of patterns)\n\n Examples\n ---------\n >>> import numpy as np\n >>> h = np.array([3,7])\n >>> N = 4\n >>> inverse_hash_from_pattern(h,N)\n array([[1, 1],\n [1, 1],\n [0, 1],\n [0, 0]])\n \"\"\"\n\n # check if the hash values are not bigger than possible hash value\n # for N neuron with basis = base\n if np.any(h > np.sum([base**x for x in range(N)])):\n raise ValueError(\n \"hash value is not compatible with the number of neurons N\")\n # check if the hash values are integer\n if not np.all(np.int64(h) == h):\n raise ValueError(\"hash values are not integers\")\n\n m = np.zeros((N,len(h)), dtype=int)\n for j, hh in enumerate(h):\n i = N-1\n while i >= 0 and hh != 0:\n m[i, j] = hh % base\n hh /= base\n i -= 1\n return m\n\n\ndef n_emp_mat(mat, N, pattern_hash, base=2):\n \"\"\"\n Calculates empirical number of observed patterns expressed\n by their hash values\n\n Parameters:\n -----------\n m: list of integers\n matrix of 0-1 patterns as columns,\n shape: (number of neurons N, number of patterns)\n N: integer\n number of neurons\n pattern_hash: list of integers\n array of hash values. Length defines number of patterns\n base: integer\n base for calculation of the number from binary\n sequences (= pattern).\n Default is 2\n\n Returns:\n --------\n N_emp: list of integers\n empirical number of each observed pattern.\n Same length as pattern_hash\n indices: list of list of integers\n list of indices of mat per entry of pattern_hash.\n indices[i] = N_emp[i] = pattern_hash[i]\n\n Raises:\n -------\n ValueError: if mat is not zero-one matrix\n\n Examples:\n ---------\n >>> mat = np.array([[1, 0, 0, 1, 1],\n [1, 0, 0, 1, 0]])\n >>> pattern_hash = np.array([1,3])\n >>> n_emp, n_emp_indices = N_emp_mat(mat, N,pattern_hash)\n >>> print n_emp\n [ 0. 2.]\n >>> print n_emp_indices\n [array([]), array([0, 3])]\n \"\"\"\n # check if the mat is zero-one matrix\n if np.any(mat>1) or np.any(mat<0):\n raise ValueError(\"entries of mat should be either one or zero\")\n h = hash_from_pattern(mat, N, base = base)\n N_emp = np.zeros(len(pattern_hash))\n indices = []\n for p_h_idx, p_h in enumerate(pattern_hash):\n indices_tmp = np.nonzero(h == p_h)[0]\n indices.append(indices_tmp)\n N_emp_tmp = len(indices_tmp)\n N_emp[p_h_idx] = N_emp_tmp\n return N_emp, indices\n\n\ndef n_emp_mat_sum_trial(mat, N, pattern_hash, method='analytic_TrialByTrial'):\n \"\"\"\n Calculates empirical number of observed patterns summed across trials\n\n Parameters:\n -----------\n mat: 3d numpy array\n the entries are zero or one\n 0-axis --> trials\n 1-axis --> neurons\n 2-axis --> time bins\n N: integer\n number of neurons\n pattern_hash: list of integers\n array of hash values, length: number of patterns\n method: string\n method with which the unitary events whould be computed\n 'analytic_TrialByTrial' -- > calculate the expectency\n (analytically) on each trial, then sum over all trials.\n 'analytic_TrialAverage' -- > calculate the expectency\n by averaging over trials.\n (cf. Gruen et al. 2003)\n 'surrogate_TrialByTrial' -- > calculate the distribution \n of expected coincidences by spike time randomzation in \n each trial and sum over trials.\n Default is 'analytic_trialByTrial'\n\n\n\n Returns:\n --------\n N_empL list of integers\n empirical number of observed pattern summed across trials,\n length: number of patterns (i.e. len(patter_hash))\n idx_trials: list of list of integers\n list of indices of mat for each trial in which\n the specific pattern has been observed.\n 0-axis --> trial\n 1-axis --> list of indices for the chosen trial per\n entry of pattern_hash\n\n Raises:\n -------\n ValueError: if matrix mat has wrong orientation\n ValueError: if mat is not zero-one matrix\n\n Examples:\n ---------\n >>> mat = np.array([[[1, 1, 1, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 1, 1, 0, 1]],\n\n [[1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [1, 1, 0, 1, 0]]])\n\n >>> pattern_hash = np.array([4,6])\n >>> N = 3\n >>> n_emp_sum_trial, n_emp_sum_trial_idx =\n n_emp_mat_sum_trial(mat, N,pattern_hash)\n >>> n_emp_sum_trial\n array([ 1., 3.])\n >>> n_emp_sum_trial_idx\n [[array([0]), array([3])], [array([], dtype=int64), array([2, 4])]]\n \"\"\"\n # check the consistency between shape of m and number neurons N\n if N != np.shape(mat)[1]:\n raise ValueError('the entries of mat should be a list of a'\n 'list where 0-axis is trials and 1-axis is neurons')\n\n num_patt = len(pattern_hash)\n N_emp = np.zeros(num_patt)\n\n idx_trials = []\n for mat_tr in mat:\n # check if the mat is zero-one matrix\n if np.any(np.array(mat_tr)>1):\n raise ValueError(\"entries of mat should be either one or zero\")\n N_emp_tmp,indices_tmp = n_emp_mat(mat_tr, N, pattern_hash,base=2)\n idx_trials.append(indices_tmp)\n N_emp += N_emp_tmp\n if method == 'analytic_TrialByTrial' or method == 'surrogate_TrialByTrial':\n return N_emp, idx_trials\n elif method == 'analytic_TrialAverage':\n return N_emp/float(len(mat)), idx_trials\n\n\ndef _sts_overlap(sts, t_start=None, t_stop=None):\n \"\"\"\n Find the internal range t_start, t_stop where all spike trains are\n defined; cut all spike trains taking that time range only\n \"\"\"\n max_tstart = max([t.t_start for t in sts])\n min_tstop = min([t.t_stop for t in sts])\n\n if t_start is None:\n t_start = max_tstart\n if not all([max_tstart == t.t_start for t in sts]):\n warnings.warn(\n \"Spiketrains have different t_start values -- \"\n \"using maximum t_start as t_start.\")\n\n if t_stop is None:\n t_stop = min_tstop\n if not all([min_tstop == t.t_stop for t in sts]):\n warnings.warn(\n \"Spiketrains have different t_stop values -- \"\n \"using minimum t_stop as t_stop.\")\n\n sts_cut = [st.time_slice(t_start=t_start, t_stop=t_stop) for st in sts]\n return sts_cut\n\n\ndef n_exp_mat(mat, N, pattern_hash, method = 'analytic', **kwargs):\n \"\"\"\n Calculates the expected joint probability for each spike pattern\n\n Parameters:\n -----------\n mat: 2d numpy array\n the entries are zero or one\n 0-axis --> neurons\n 1-axis --> time bins\n pattern_hash: list of integers\n array of hash values, length: number of patterns\n method: string\n method with which the expectency should be caculated\n 'analytic' -- > analytically\n 'surr' -- > with surrogates (spike time randomization)\n Default is 'analytic'\n kwargs:\n -------\n n_surr: integer\n number of surrogate to be used\n Default is 100\n\n Raises:\n -------\n ValueError: if matrix m has wrong orientation\n\n Returns:\n --------\n if method is analytic:\n numpy.array:\n An array containing the expected joint probability of each pattern,\n shape: (number of patterns,)\n if method is surr:\n numpy.ndarray, 0-axis --> different realizations,\n length = number of surrogates\n 1-axis --> patterns\n\n Examples:\n ---------\n >>> mat = np.array([[1, 1, 1, 1],\n [0, 1, 0, 1],\n [0, 0, 1, 0]])\n >>> pattern_hash = np.array([5,6])\n >>> N = 3\n >>> n_exp_anal = n_exp_mat(mat,N, pattern_hash, method = 'analytic')\n >>> n_exp_anal\n [ 0.5 1.5 ]\n >>>\n >>>\n >>> n_exp_surr = n_exp_mat(\n mat, N,pattern_hash, method = 'surr', n_surr = 5000)\n >>> print n_exp_surr\n [[ 1. 1.]\n [ 2. 0.]\n [ 2. 0.]\n ...,\n [ 2. 0.]\n [ 2. 0.]\n [ 1. 1.]]\n\n \"\"\"\n # check if the mat is zero-one matrix\n if np.any(mat > 1) or np.any(mat < 0):\n raise ValueError(\"entries of mat should be either one or zero\")\n\n if method == 'analytic':\n marg_prob = np.mean(mat,1,dtype=float)\n # marg_prob needs to be a column vector, so we\n # build a two dimensional array with 1 column\n # and len(marg_prob) rows\n marg_prob = np.reshape(marg_prob,(len(marg_prob),1))\n m = inverse_hash_from_pattern(pattern_hash, N)\n nrep = np.shape(m)[1]\n # multipyling the marginal probability of neurons with regard to the pattern\n pmat = np.multiply(m,np.tile(marg_prob,(1,nrep))) +\\\n np.multiply(1-m,np.tile(1-marg_prob,(1,nrep)))\n return np.prod(pmat,axis=0)*float(np.shape(mat)[1])\n if method == 'surr':\n if len(pattern_hash)>1:\n raise ValueError('surrogate method works only for one pattern!') \n if 'n_surr' in kwargs:\n n_surr = kwargs['n_surr']\n else:\n n_surr = 100.\n N_exp_array = np.zeros(n_surr)\n for rz_idx, rz in enumerate(np.arange(n_surr)):\n # shuffling all elements of zero-one matrix\n mat_surr = np.array(mat)\n [np.random.shuffle(i) for i in mat_surr]\n N_exp_array[rz_idx] = n_emp_mat(mat_surr, N, pattern_hash)[0][0]\n return N_exp_array\n\n\ndef n_exp_mat_sum_trial(mat, N, pattern_hash, method = 'analytic_TrialByTrial', **kwargs):\n \"\"\"\n Calculates the expected joint probability\n for each spike pattern sum over trials\n\n Parameters:\n -----------\n mat: 3d numpy array\n the entries are zero or one\n 0-axis --> trials\n 1-axis --> neurons\n 2-axis --> time bins\n N: integer\n number of neurons\n pattern_hash: list of integers\n array of hash values, length: number of patterns\n method: string\n method with which the unitary events whould be computed\n 'analytic_TrialByTrial' -- > calculate the expectency\n (analytically) on each trial, then sum over all trials.\n 'analytic_TrialAverage' -- > calculate the expectency\n by averaging over trials.\n (cf. Gruen et al. 2003)\n 'surrogate_TrialByTrial' -- > calculate the distribution \n of expected coincidences by spike time randomzation in \n each trial and sum over trials.\n Default is 'analytic_trialByTrial'\n\n kwargs:\n -------\n n_surr: integer\n number of surrogate to be used\n Default is 100\n\n Returns:\n --------\n numpy.array:\n An array containing the expected joint probability of\n each pattern summed over trials,shape: (number of patterns,)\n\n Examples:\n --------\n >>> mat = np.array([[[1, 1, 1, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 1, 1, 0, 1]],\n\n [[1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [1, 1, 0, 1, 0]]])\n\n >>> pattern_hash = np.array([5,6])\n >>> N = 3\n >>> n_exp_anal = n_exp_mat_sum_trial(mat, N, pattern_hash)\n >>> print n_exp_anal\n array([ 1.56, 2.56])\n \"\"\"\n # check the consistency between shape of m and number neurons N\n if N != np.shape(mat)[1]:\n raise ValueError('the entries of mat should be a list of a'\n 'list where 0-axis is trials and 1-axis is neurons')\n\n if method == 'analytic_TrialByTrial':\n n_exp = np.zeros(len(pattern_hash))\n for mat_tr in mat:\n n_exp += n_exp_mat(mat_tr, N, pattern_hash, method='analytic')\n elif method == 'analytic_TrialAverage':\n n_exp = n_exp_mat(\n np.mean(mat,0), N, pattern_hash, method='analytic')*np.shape(mat)[0]\n elif method == 'surrogate_TrialByTrial':\n if 'n_surr' in kwargs: \n n_surr = kwargs['n_surr']\n else:\n n_surr = 100.\n n_exp = np.zeros(n_surr)\n for mat_tr in mat:\n n_exp += n_exp_mat(mat_tr, N, pattern_hash, method='surr', n_surr = n_surr)\n else:\n raise ValueError(\n \"The method only works on the zero_one matrix at the moment\")\n return n_exp\n\n\ndef gen_pval_anal(mat, N, pattern_hash, method='analytic_TrialByTrial',**kwargs):\n \"\"\"\n computes the expected coincidences and a function to calculate\n p-value for given empirical coincidences\n\n this function generate a poisson distribution with the expected\n value calculated by mat. it returns a function which gets\n the empirical coincidences, `n_emp`, and calculates a p-value\n as the area under the poisson distribution from `n_emp` to infinity\n\n Parameters:\n -----------\n mat: 3d numpy array\n the entries are zero or one\n 0-axis --> trials\n 1-axis --> neurons\n 2-axis --> time bins\n N: integer\n number of neurons\n pattern_hash: list of integers\n array of hash values, length: number of patterns\n method: string\n method with which the unitary events whould be computed\n 'analytic_TrialByTrial' -- > calculate the expectency\n (analytically) on each trial, then sum over all trials.\n ''analytic_TrialAverage' -- > calculate the expectency\n by averaging over trials.\n Default is 'analytic_trialByTrial'\n (cf. Gruen et al. 2003)\n\n kwargs:\n -------\n n_surr: integer\n number of surrogate to be used\n Default is 100\n\n\n Returns:\n --------\n pval_anal:\n a function which calculates the p-value for\n the given empirical coincidences\n n_exp: list of floats\n expected coincidences\n\n Examples:\n --------\n >>> mat = np.array([[[1, 1, 1, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 1, 1, 0, 1]],\n\n [[1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [1, 1, 0, 1, 0]]])\n\n >>> pattern_hash = np.array([5,6])\n >>> N = 3\n >>> pval_anal,n_exp = gen_pval_anal(mat, N,pattern_hash)\n >>> n_exp\n array([ 1.56, 2.56])\n \"\"\"\n if method == 'analytic_TrialByTrial' or method == 'analytic_TrialAverage':\n n_exp = n_exp_mat_sum_trial(mat, N, pattern_hash, method = method)\n def pval(n_emp):\n p = 1.- scipy.special.gammaincc(n_emp, n_exp)\n return p\n elif method == 'surrogate_TrialByTrial':\n if 'n_surr' in kwargs: \n n_surr = kwargs['n_surr'] \n else:\n n_surr = 100.\n n_exp = n_exp_mat_sum_trial(mat, N, pattern_hash, method = method, n_surr = n_surr)\n def pval(n_emp):\n hist = np.bincount(np.int64(n_exp))\n exp_dist = hist/float(np.sum(hist))\n if len(n_emp)>1:\n raise ValueError('in surrogate method the p_value can be calculated only for one pattern!')\n return np.sum(exp_dist[n_emp[0]:])\n\n return pval, n_exp\n\n\n\ndef jointJ(p_val):\n \"\"\"Surprise measurement\n\n logarithmic transformation of joint-p-value into surprise measure\n for better visualization as the highly significant events are\n indicated by very low joint-p-values\n\n Parameters:\n -----------\n p_val: list of floats\n p-values of statistical tests for different pattern.\n\n Returns:\n --------\n J: list of floats\n list of surprise measure\n\n Examples:\n ---------\n >>> p_val = np.array([0.31271072, 0.01175031])\n >>> jointJ(p_val)\n array([0.3419968 , 1.92481736])\n \"\"\"\n p_arr = np.array(p_val)\n\n try:\n Js = np.log10(1-p_arr)-np.log10(p_arr)\n except RuntimeWarning:\n pass\n return Js\n\n\ndef _rate_mat_avg_trial(mat):\n \"\"\"\n calculates the average firing rate of each neurons across trials\n \"\"\"\n num_tr, N, nbins = np.shape(mat)\n psth = np.zeros(N)\n for tr,mat_tr in enumerate(mat):\n psth += np.sum(mat_tr, axis=1)\n return psth/float(nbins)/float(num_tr)\n\n\ndef _bintime(t, binsize):\n \"\"\"\n change the real time to bintime\n \"\"\"\n t_dl = t.rescale('ms').magnitude\n binsize_dl = binsize.rescale('ms').magnitude\n return np.floor(np.array(t_dl)/binsize_dl).astype(int)\n\n\ndef _winpos(t_start, t_stop, winsize, winstep,position='left-edge'):\n \"\"\"\n Calculates the position of the analysis window\n \"\"\"\n t_start_dl = t_start.rescale('ms').magnitude\n t_stop_dl = t_stop.rescale('ms').magnitude\n winsize_dl = winsize.rescale('ms').magnitude\n winstep_dl = winstep.rescale('ms').magnitude\n\n # left side of the window time\n if position == 'left-edge':\n ts_winpos = np.arange(t_start_dl, t_stop_dl - winsize_dl + winstep_dl, winstep_dl)*pq.ms\n else:\n raise ValueError('the current version only returns left-edge of the window')\n return ts_winpos\n\n\ndef _UE(mat, N, pattern_hash, method='analytic_TrialByTrial',**kwargs):\n \"\"\"\n returns the default results of unitary events analysis\n (Surprise, empirical coincidences and index of where it happened\n in the given mat, n_exp and average rate of neurons)\n \"\"\"\n rate_avg = _rate_mat_avg_trial(mat)\n n_emp, indices = n_emp_mat_sum_trial(mat, N, pattern_hash, method)\n if method == 'surrogate_TrialByTrial':\n if 'n_surr' in kwargs: \n n_surr = kwargs['n_surr']\n else: n_surr = 100\n dist_exp, n_exp = gen_pval_anal(mat, N, pattern_hash, method, n_surr=n_surr)\n elif method == 'analytic_TrialByTrial' or method == 'analytic_TrialAverage':\n dist_exp, n_exp = gen_pval_anal(mat, N, pattern_hash, method)\n pval = dist_exp(n_emp)\n Js = jointJ(pval)\n return Js, rate_avg, n_exp, n_emp,indices\n\n\ndef jointJ_window_analysis(\n data, binsize, winsize, winstep, pattern_hash,\n method='analytic_TrialByTrial', t_start=None,\n t_stop=None, binary=True, **kwargs):\n \"\"\"\n Calculates the joint surprise in a sliding window fashion\n\n Parameters:\n ----------\n data: list of neo.SpikeTrain objects\n list of spike trains in different trials\n 0-axis --> Trials\n 1-axis --> Neurons\n 2-axis --> Spike times\n binsize: Qunatity scalar with dimension time\n size of bins for descritizing spike trains\n winsize: Qunatity scalar with dimension time\n size of the window of analysis\n winstep: Qunatity scalar with dimension time\n size of the window step\n pattern_hash: list of integers\n list of interested patterns in hash values\n (see hash_from_pattern and inverse_hash_from_pattern functions)\n method: string\n method with which the unitary events whould be computed\n 'analytic_TrialByTrial' -- > calculate the expectency\n (analytically) on each trial, then sum over all trials.\n ''analytic_TrialAverage' -- > calculate the expectency\n by averaging over trials.\n (cf. Gruen et al. 2003)\n 'surrogate_TrialByTrial' -- > calculate the distribution \n of expected coincidences by spike time randomzation in \n each trial and sum over trials.\n Default is 'analytic_trialByTrial'\n\n kwargs:\n -------\n n_surr: integer\n number of surrogate to be used\n Default is 100\n\n\n Returns:\n -------\n result: dictionary\n Js: list of float\n JointSurprise of different given patterns within each window\n shape: different pattern hash --> 0-axis\n different window --> 1-axis\n indices: list of list of integers\n list of indices of pattern whithin each window\n shape: different pattern hash --> 0-axis\n different window --> 1-axis\n n_emp: list of integers\n empirical number of each observed pattern.\n shape: different pattern hash --> 0-axis\n different window --> 1-axis\n n_exp: list of floats\n expeced number of each pattern.\n shape: different pattern hash --> 0-axis\n different window --> 1-axis\n rate_avg: list of floats\n average firing rate of each neuron\n shape: different pattern hash --> 0-axis\n different window --> 1-axis\n\n \"\"\"\n if not isinstance(data[0][0],neo.SpikeTrain):\n raise ValueError(\"structure of the data is not correct: 0-axis should be trials, 1-axis units and 2-axis neo spike trains\")\n\n if t_start is None: t_start = data[0][0].t_start.rescale('ms')\n if t_stop is None: t_stop = data[0][0].t_stop.rescale('ms')\n\n # position of all windows (left edges)\n t_winpos = _winpos(t_start, t_stop, winsize, winstep,position = 'left-edge')\n t_winpos_bintime = _bintime(t_winpos, binsize)\n\n winsize_bintime = _bintime(winsize, binsize)\n winstep_bintime = _bintime(winstep, binsize)\n\n if winsize_bintime * binsize != winsize:\n warnings.warn(\n \"ratio between winsize and binsize is not integer -- \"\n \"the actual number for window size is \"+str (winsize_bintime * binsize))\n\n if winstep_bintime * binsize != winstep:\n warnings.warn(\n \"ratio between winsize and binsize is not integer -- \"\n \"the actual number for window size is\" + str(winstep_bintime * binsize))\n\n num_tr, N = np.shape(data)[:2]\n\n n_bins = int((t_stop - t_start)/binsize)\n\n mat_tr_unit_spt = np.zeros((len(data), N, n_bins))\n for tr, sts in enumerate(data):\n bs = conv.BinnedSpikeTrain(sts, t_start=t_start, t_stop=t_stop, binsize=binsize)\n if binary is True:\n mat = bs.to_bool_array()\n else:\n raise ValueError(\n \"The method only works on the zero_one matrix at the moment\")\n mat_tr_unit_spt[tr] = mat\n\n num_win = len(t_winpos)\n Js_win, n_exp_win, n_emp_win = (np.zeros(num_win) for _ in xrange(3))\n rate_avg = np.zeros((num_win,N))\n indices_win = {}\n for i in range(num_tr):\n indices_win['trial'+str(i)]= []\n\n for i, win_pos in enumerate(t_winpos_bintime):\n mat_win = mat_tr_unit_spt[:,:,win_pos:win_pos + winsize_bintime]\n if method == 'surrogate_TrialByTrial':\n if 'n_surr' in kwargs: \n n_surr = kwargs['n_surr']\n else: n_surr = 100\n Js_win[i], rate_avg[i], n_exp_win[i], n_emp_win[i], indices_lst = _UE(mat_win, N,pattern_hash,method,n_surr=n_surr)\n else:\n Js_win[i], rate_avg[i], n_exp_win[i], n_emp_win[i], indices_lst = _UE(mat_win, N,pattern_hash,method)\n for j in range(num_tr):\n if len(indices_lst[j][0]) > 0:\n indices_win['trial'+str(j)] = np.append(indices_win['trial'+str(j)], indices_lst[j][0] + win_pos)\n return {'Js': Js_win, 'indices':indices_win, 'n_emp': n_emp_win,'n_exp': n_exp_win,'rate_avg':rate_avg/binsize}\n","sub_path":"notebooks/elephant_dev/unitary_event_analysis_dev.py","file_name":"unitary_event_analysis_dev.py","file_ext":"py","file_size_in_byte":26969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"388047835","text":"from django.shortcuts import render, redirect, get_object_or_404, RequestContext, render_to_response\nfrom datetime import datetime, timedelta\nfrom messaging.models import Message\nfrom .forms import NewMessageForm\n\n######################################\n# Messages\n######################################\n\ndef messages(request):\n context = RequestContext(request)\n messages = []\n user = request.user\n current_date = datetime.today() - timedelta(days=7)\n if request.method == 'GET':\n messages = Message.objects.filter(to_user=user, created__gte=current_date).order_by('-created')\n #groups=request.user.groups.all()\n return render_to_response('messaging/messages.html', {'messages': messages }, context)\n \ndef new_message(request, template_name='dmin/new_message.html'):\n form = NewMessageForm(request.POST or None)\n if form.is_valid():\n frm = form.save(commit=False)\n frm.from_user = request.user\n frm.save()\n return redirect('/a/dmin/profile')\n return render(request, template_name, {'form':form})\n","sub_path":"tinytotts/messaging/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"218200676","text":"\"\"\"A database encapsulating collections of near-Earth objects and their\nclose approaches.\n\nA `NEODatabase` holds an interconnected data set of NEOs and close approaches.\nIt provides methods to fetch an NEO by primary designation or by name, as well\nas a method to query the set of close approaches that match a collection of\nuser-specified criteria.\n\nUnder normal circumstances, the main module creates one NEODatabase from the\ndata on NEOs and close approaches extracted by `extract.load_neos` and\n`extract.load_approaches`.\n\nYou'll edit this file in Tasks 2 and 3.\n\"\"\"\n\"\"\"\nA function will be made which makes it possible to link together the neos and\nclose approaches which we have been provided through the load_neos and\nload_approaches. The parameters will be the neos and approaches itself.\nThis is our helper function for linking which we will use for the other\nfunctions in database.py as well.\n\"\"\"\n\n\ndef link_neos_and_approaches(neos, approaches):\n neosList = {} # for the neos list\n approachesList = [] # for the approaches list\n\n # every close approach has attributes with designation and so does\n # every neo. We'll check if they match, then it will be linked.\n # Also, it will searched as well in the list we are making. If it\n # is already there, the approach will be appended to the neosList\n # in the approaches. Else, it will be given with a new neo.\n\n for approach in approaches:\n for neo in neos:\n if neo.designation == approach._designation:\n approach.neo = neo\n if neo.designation in neosList:\n neosList[neo.designation].approaches.append(approach)\n else:\n neo.approaches.append(approach)\n neosList[neo.designation] = neo\n break\n approachesList.append(approach)\n\n for neo in neos:\n if neo.designation not in neosList:\n neosList[neo.designation] = neo\n\n return neosList.values(), approachesList\n\n\nclass NEODatabase:\n\n \"\"\"A database of near-Earth objects and their close approaches.\n\n A `NEODatabase` contains a collection of NEOs and a collection of close\n approaches. It additionally maintains a few auxiliary data structures to\n help fetch NEOs by primary designation or by name and to help speed up\n querying for close approaches that match criteria.\n \"\"\"\n\n def __init__(self, neos, approaches):\n\n \"\"\"Create a new `NEODatabase`.\n As a precondition, this constructor assumes that the collections\n of NEOs and close approaches haven't yet been linked - that is,\n the `.approaches` attribute of each `NearEarthObject` resolves\n to an empty collection, and the `.neo` attribute of each\n `CloseApproach` is None.\n\n However, each `CloseApproach` has an attribute (`._designation`) that\n matches the `.designation` attribute of the corresponding NEO. This\n constructor modifies the supplied NEOs and close approaches to link\n them together - after it's done, the `.approaches` attribute of each\n NEO has a collection of that NEO's close approaches, and the `.neo`\n attribute of each close approach references the appropriate NEO.\n\n :param neos: A collection of `NearEarthObject`s.\n :param approaches: A collection of `CloseApproach`es.\n \"\"\"\n\n self.neos_name = {}\n self.neos_designation = {}\n\n # this will save the values securely\n self._neos, self._approaches = link_neos_and_approaches(neos,\n approaches)\n for neo in self._neos:\n if neo.name:\n self.neos_name[neo.name] = neo\n self.neos_designation[neo.designation] = neo\n\n def get_neo_by_designation(self, designation):\n\n \"\"\"Find and return an NEO by its primary designation.\n\n If no match is found, return `None` instead.\n\n Each NEO in the data set has a unique primary designation, as a string.\n\n The matching is exact - check for spelling and capitalization if no\n match is found.\n\n :param designation: The primary designation of the NEO to search for.\n :return: The `NearEarthObject` with the desired primary designation,\n or `None`.\n \"\"\"\n\n return self.neos_designation.get(designation)\n\n def get_neo_by_name(self, name):\n\n \"\"\"Find and return an NEO by its name.\n\n If no match is found, return `None` instead.\n\n Not every NEO in the data set has a name. No NEOs are associated with\n the empty string nor with the `None` singleton.\n\n The matching is exact - check for spelling and capitalization if no\n match is found.\n\n :param name: The name, as a string, of the NEO to search for.\n :return: The `NearEarthObject` with the desired name, or `None`.\n \"\"\"\n\n if name in self.neos_name:\n return self.neos_name[name]\n return None\n\n def query(self, filters=()):\n\n \"\"\"Query close approaches to generate those that match a collection\n of filters.\n\n This generates a stream of `CloseApproach` objects that match all\n of the provided filters.\n\n If no arguments are provided, generate all known close approaches.\n\n The `CloseApproach` objects are generated in internal order, which\n isn't guaranteed to be sorted meaningfully, although is often sorted\n by time.\n\n :param filters: A collection of filters capturing user-specified\n criteria.\n :return: A stream of matching `CloseApproach` objects.\n \"\"\"\n\n for approach in self._approaches:\n # map(func, iter) will be used to filter out the approaches\n # for CloseApproach objects.\n flag = False in map(lambda i: i(approach), filters)\n if flag is False:\n yield approach\n","sub_path":"NEO/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"171560816","text":"### Implementing and simulating multiplexers in PyRTL ###\n\nimport pyrtl\n\n# Now, it is time to build and simulate (for 16 cycles) a 3-bit 5:1 MUX.\n# You can develop your design using either Boolean gates as above or PyRTL's\n# conditional assignment.\n\n# Declare data inputs\n# < add your code here >\n\na = pyrtl.Input(bitwidth=3, name='a')\nb = pyrtl.Input(bitwidth=3, name='b')\nc = pyrtl.Input(bitwidth=3, name='c')\nd = pyrtl.Input(bitwidth=3, name='d')\ne = pyrtl.Input(bitwidth=3, name='e')\n\n# Declare control inputs\n# < add your code here >\n\ns = pyrtl.Input(bitwidth=3, name='s')\n\n# Declare outputs \n# < add your code here >\n\no = pyrtl.Output(bitwidth=3, name='o')\n\n\n# Describe your 5:1 MUX implementation\n# < add your code here >\n\nsel0 = s[2]\nsel1 = s[1]\nsel2 = s[0]\n\n\nwith pyrtl.conditional_assignment:\n with ((~sel0) & (~sel1) & (~sel2)):\n o |= a\n with ((~sel0) & (~sel1) & (sel2)):\n o |= b\n with ((~sel0) & (sel1) & (~sel2)):\n o |= c\n with ((~sel0) & (sel1) & (sel2)):\n o |= d\n with ((sel0) & (~sel1) & (~sel2)):\n o |= e\n\n\n#o <<= temp1 | temp2 | temp3 | temp4 | temp5\n\n# Simulate and test your design for 16 cycles using random inputs\n# < add your code here >\n\n\nsim_trace = pyrtl.SimulationTrace()\nsim = pyrtl.Simulation(tracer=sim_trace)\n\nimport random\nfor cycle in range(16):\n sim.step({\n 'a': random.choice([0,1,2,3,4,5,6,7]),\n 'b': random.choice([0,1,2,3,4,5,6,7]),\n 'c': random.choice([0,1,2,3,4,5,6,7]),\n 'd': random.choice([0,1,2,3,4,5,6,7]),\n 'e': random.choice([0,1,2,3,4,5,6,7]),\n 's': random.choice([0,1,2,3,4])\n })\n\n\nprint('--- 3-bit 5:1 MUX Simulation ---')\nsim_trace.render_trace()\n","sub_path":"lab3/lab3_q3.py","file_name":"lab3_q3.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"468418806","text":"from tensorflow.python.layers import core as layers_core\nfrom nltk.tokenize import word_tokenize\nimport pickle\nimport tensorflow as tf\nimport numpy as np\n\nfrom utils import data_utils\n\n\nclass Chatbot(object):\n\n\tdef __init__(self, params, language_base):\n\n\t\tself.params = params\n\n\t\twith tf.variable_scope(\"chat\"):\n\t\t\tself.train_model = ChatModel(tf.contrib.learn.ModeKeys.TRAIN, params, language_base)\n\t\twith tf.variable_scope('chat', reuse=True):\n\t\t\tself.eval_model = ChatModel(tf.contrib.learn.ModeKeys.EVAL, params, language_base)\n\t\twith tf.variable_scope('chat', reuse=True):\n\t\t\tself.infer_model = ChatModel(tf.contrib.learn.ModeKeys.INFER, params, language_base)\n\n\tdef train(self, data, sess):\n\n\t\treturn self.train_model.train(data, sess)\n\n\tdef infer(self, data, sess):\n\n\t\treturn self.infer_model.infer(data, sess)\n\n\tdef respond(self, text, language_base, sess):\n\n\t\tpad_seq = ['' for _ in range(self.params.src_max_len)]\n\t\twords = word_tokenize(text)\n\t\tsrc_len = len(words)\n\t\twords = [words[i].lower() if i < len(words) else '' for i in range(self.params.src_max_len)]\n\t\tids = language_base.convert_words_to_ids(words)\n\t\tpad_ids = language_base.convert_words_to_ids(pad_seq)\n\t\tencoder_inputs = np.array([ids] + [pad_ids for _ in range(self.params.batch_size-1)])\n\t\tsource_sequence_lengths = np.array([src_len] + [1 for _ in range(self.params.batch_size-1)])\n\t\tbatch_data = (encoder_inputs, None, None, source_sequence_lengths, None)\n\t\ttranslation_ids = self.infer(batch_data, sess)[0][0][0]\n\t\ttranslation_words = language_base.convert_ids_to_words(translation_ids)\n\t\ttranslation_words = data_utils.trim_words(translation_words)\n\t\ttranslation = data_utils.words_to_text(translation_words)\n\n\t\treturn translation.capitalize()\n\n\tdef save(self, directory):\n\n\t\twith open(os.path.join(directory, 'params'), 'wb') as f:\n\t\t\tpickle.dump(self.params, f)\n\n\nclass ChatModel(object):\n\n\tdef __init__(self, mode, params, language_base):\n\n\t\tself.mode = mode\n\n\t\t# Placeholders\n\t\tself.encoder_inputs = tf.placeholder(tf.int32, shape=[params.batch_size, params.src_max_len], name='encoder_inputs')\n\t\tself.source_sequence_lengths = tf.placeholder(tf.int32, shape=[params.batch_size], name='source_sequence_lengths')\n\t\tself.decoder_inputs = tf.placeholder(tf.int32, shape=[params.batch_size, params.tgt_max_len], name='decoder_inputs')\n\t\tself.target_sequence_lengths = tf.placeholder(tf.int32, shape=[params.batch_size], name='target_sequence_lengths')\n\t\tself.decoder_outputs = tf.placeholder(tf.int32, shape=[params.batch_size, params.tgt_max_len], name='decoder_outputs')\n\n\t\t# Look up embedding:\n\t\t# encoder_inputs: [max_time, batch_size]\n\t\t# encoder_emb_inp: [max_time, batch_size, embedding_size]\n\t\tencoder_emb_inp = tf.nn.embedding_lookup(language_base.embeddings, self.encoder_inputs)\n\t\tdecoder_emb_inp = tf.nn.embedding_lookup(language_base.embeddings, self.decoder_inputs)\n\n\t\tencoder_emb_inp.set_shape([params.batch_size, params.src_max_len, language_base.word_embedding_size])\n\t\tdecoder_emb_inp.set_shape([params.batch_size, params.tgt_max_len, language_base.word_embedding_size])\n\n\t\tencoder_cell = tf.nn.rnn_cell.BasicLSTMCell(params.num_units)\n\n\t\tencoder_initial_state = encoder_cell.zero_state(params.batch_size, dtype=tf.float32)\n\n\t\tencoder_outputs, encoder_state = tf.nn.dynamic_rnn(\n\t\t\tencoder_cell, encoder_emb_inp, initial_state=encoder_initial_state,\n\t\t\tsequence_length=self.source_sequence_lengths, \n\t\t\ttime_major=False, swap_memory=True)\n\n\t\t# Build RNN cell\n\t\tdecoder_cell = tf.nn.rnn_cell.BasicLSTMCell(params.num_units)\n\n\t\t# attention_states: [batch_size, max_time, num_units]\n\t\t# attention_states = tf.transpose(encoder_outputs, [1, 0, 2])\n\n\t\tsource_seq_lengths = self.source_sequence_lengths\n\n\t\tif self.mode == tf.contrib.learn.ModeKeys.INFER and params.beam_width > 0:\n\t\t\tencoder_outputs = tf.contrib.seq2seq.tile_batch(\n\t\t\t\tencoder_outputs, multiplier=params.beam_width)\n\t\t\tsource_seq_lengths = tf.contrib.seq2seq.tile_batch(\n\t\t\t\tsource_seq_lengths, multiplier=params.beam_width)\n\n\t\t# Create an attention mechanism\n\t\tattention_mechanism = tf.contrib.seq2seq.LuongAttention(\n\t\t\tparams.num_units, encoder_outputs,\n\t\t\tmemory_sequence_length=source_seq_lengths)\n\n\t\tdecoder_cell = tf.contrib.seq2seq.AttentionWrapper(\n\t\t\tdecoder_cell, attention_mechanism,\n\t\t\tattention_layer_size=params.num_units)\n\n\t\tprojection_layer = layers_core.Dense(units=len(language_base.vocabulary), use_bias=True)\n\n\t\tif self.mode == tf.contrib.learn.ModeKeys.INFER:\n\n\t\t\tif params.beam_width > 0:\n\t\t\t\tencoder_state = tf.contrib.seq2seq.tile_batch(\n\t\t\t\t\tencoder_state, multiplier=params.beam_width)\n\t\t\t\tbatch_size = params.batch_size * params.beam_width\n\n\t\t\tdecoder_initial_state = decoder_cell.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n\n\t\t\tmaximum_iterations = tf.round(tf.reduce_max(self.source_sequence_lengths) * 2)\n\n\t\t\ttmp_embeddings = tf.identity(language_base.embeddings)\n\t\t\ttmp_embeddings.set_shape([len(language_base.vocabulary), language_base.word_embedding_size])\n\n\t\t\tdecoder = tf.contrib.seq2seq.BeamSearchDecoder(\n\t\t\t\tcell=decoder_cell,\n\t\t\t\tembedding=tmp_embeddings,\n\t\t\t\tstart_tokens=tf.fill([params.batch_size], language_base.sos_id),\n\t\t\t\tend_token=language_base.eos_id,\n\t\t\t\tinitial_state=decoder_initial_state,\n\t\t\t\tbeam_width=params.beam_width,\n\t\t\t\toutput_layer=projection_layer,\n\t\t\t\tlength_penalty_weight=params.length_penalty_weight)\n\n\t\t\t# Dynamic decoding\n\t\t\toutputs, _, _ = tf.contrib.seq2seq.dynamic_decode(\n\t\t\t\tdecoder, maximum_iterations=maximum_iterations)\n\n\t\t\tself.translations = outputs.predicted_ids\n\t\t\tself.translations = tf.transpose(self.translations, perm=[0, 2, 1])\n\n\t\telse:\n\n\t\t\tself.predict_count = tf.reduce_sum(self.target_sequence_lengths)\n\n\t\t\tdecoder_initial_state = decoder_cell.zero_state(params.batch_size, tf.float32).clone(cell_state=encoder_state)\n\n\t\t\t# Helper\n\t\t\thelper = tf.contrib.seq2seq.TrainingHelper(\n\t\t\t\tdecoder_emb_inp, [params.tgt_max_len for _ in range(params.batch_size)], time_major=False)\n\n\t\t\t# # Decoder\n\t\t\t# if decoder_type == 'basic':\n\t\t\tdecoder = tf.contrib.seq2seq.BasicDecoder(\n\t\t\t\tdecoder_cell, helper, decoder_initial_state,\n\t\t\t\toutput_layer=projection_layer)\n\t\t\t\t\n\t\t\t# elif decoder_type == 'attention':\n\t\t\t# decoder = tf.contrib.seq2seq.BahdanauAttention(\n\t\t\t# decoder_cell, helper, encoder_state,\n\t\t\t# output_layer=projection_layer)\n\t\t\t\t\n\t\t\t# Dynamic decoding\n\t\t\toutputs, _, _ = tf.contrib.seq2seq.dynamic_decode(\n\t\t\t\tdecoder, output_time_major=False,\n\t\t\t\tswap_memory=True\n\t\t\t)\n\n\t\t\tlogits = outputs.rnn_output\n\n\t\t\tcrossent = tf.nn.sparse_softmax_cross_entropy_with_logits(\n\t\t\t\tlabels=self.decoder_outputs, logits=logits)\n\n\t\t\ttarget_weights = tf.sequence_mask(\n\t\t\t\tself.target_sequence_lengths, params.tgt_max_len,\n\t\t\t\tdtype=logits.dtype)\n\n\t\t\tself.loss = (tf.reduce_sum(crossent * target_weights) / tf.to_float(params.batch_size))\n\n\t\t\tself.prediction = outputs.sample_id\n\n\t\t\tglobal_step = tf.Variable(0, trainable=False)\n\t\t\tself.inc_gstep = tf.assign(global_step, global_step + params.batch_size)\n\t\t\tlearning_rate = params.learning_rate\n\t\t\t# learning_rate = tf.train.exponential_decay(\n\t\t\t# \tparams.learning_rate, global_step, decay_steps=10, decay_rate=0.9, staircase=True)\n\n\t\t\tadam_optimizer = tf.train.AdamOptimizer(learning_rate)\n\t\t\tadam_gradients, v = zip(*adam_optimizer.compute_gradients(self.loss))\n\t\t\tadam_gradients, _ = tf.clip_by_global_norm(adam_gradients, params.max_gradient_norm)\n\t\t\tself.adam_optimize = adam_optimizer.apply_gradients(zip(adam_gradients, v))\n\n\tdef _feed_dict(self, data):\n\n\t\tif self.mode == tf.contrib.learn.ModeKeys.INFER:\n\t\t\treturn {\n\t\t\t\tself.encoder_inputs: data[0],\n\t\t\t\tself.source_sequence_lengths: data[3]\n\t\t\t}\n\t\telse:\n\t\t\treturn {\n\t\t\t\tself.encoder_inputs: data[0],\n\t\t\t\tself.source_sequence_lengths: data[3],\n\t\t\t\tself.decoder_inputs: data[1],\n\t\t\t\tself.target_sequence_lengths: data[4],\n\t\t\t\tself.decoder_outputs: data[2],\n\t\t\t}\n\n\tdef train(self, data, sess):\n\n\t\tassert self.mode == tf.contrib.learn.ModeKeys.TRAIN\n\n\t\treturn sess.run([self.loss, self.adam_optimize, self.inc_gstep, self.predict_count], feed_dict=self._feed_dict(data))\n\n\tdef infer(self, data, sess):\n\n\t\tassert self.mode == tf.contrib.learn.ModeKeys.INFER\n\n\t\treturn sess.run([self.translations], feed_dict=self._feed_dict(data))\n\n\n\n\n\n\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"268834649","text":"# usage:\n# python jenkins.py jobname1, jobname2\nimport sys, httplib\n\nJENKINS_HOST = 'localhost:8080'\nURL = '/jenkins/job/%s/build?token=%s&cause=%s'\nJENKINS_AUTH_TOKEN = 'token'\nCAUSE='Requested%20by%20Python'\n\njenkins_job_ids = sys.argv\njenkins_job_ids.pop(0) # shift operation to reduce this command\n\nfor job_id in jenkins_job_ids:\n http = httplib.HTTPConnection(JENKINS_HOST)\n url = URL % (job_id, JENKINS_AUTH_TOKEN, CAUSE)\n http.request('GET', url)\n response = http.getresponse()\n #print response.status, response.reason, url # debug\n","sub_path":"gist.githubuser_daicham/jenkins.py","file_name":"jenkins.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"429993402","text":"import os\nimport math\n\n\n# Assigning Value To variable\na = 10\nb = 20\nname = \"ABC\"\n\ndef my_function(x, y):\n '''\n This Function returns Addition\n '''\n return x + y\n\t\nans = my_function(a, b)\n\n\"\"\"\nCan Add Multiple Commnets Here\n\"\"\"\nprint(ans)\n","sub_path":"first_program.py","file_name":"first_program.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"377978647","text":"# Algorithm insufficient to solve all test cases\n# the solution requires a Dynamic Programming \n# approach. Pushing off until skills have been \n# acquired. \n\nclass NAndODD:\n\n def divide_by_two(self, x):\n return x / 2\n\n def add_k(self, x, k):\n return x + k\n\n def GoF(self, x, K):\n count = 0\n if x > K:\n while x > K:\n if x % 2 == 0:\n x = self.divide_by_two(x)\n count += 1\n else:\n x = self.add_k(x, K)\n count += 1\n else:\n while x < K:\n if x % 2 == 0:\n x = self.divide_by_two(x)\n count += 1\n else:\n x = self.add_k(x, K)\n count += 1\n return count\n\n def bugs(self, x, K):\n count = 0\n while x > K:\n if x % 2 == 0:\n x = self.divide_by_two(x)\n count += 1\n else:\n x = self.add_k(x, K)\n count += 1\n return count\n\n def solve(self, L, R, K):\n return self.GoF(L, K) + self.GoF(R, K) if L != R else self.GoF(L, K)\n","sub_path":"NAddOdd.py","file_name":"NAddOdd.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"441814166","text":"# Copyright 2015 Google LLC\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 unittest\n\nimport mock\n\nfrom ._testing import _make_credentials\n\n\nclass MultiCallableStub(object):\n \"\"\"Stub for the grpc.UnaryUnaryMultiCallable interface.\"\"\"\n\n def __init__(self, method, channel_stub):\n self.method = method\n self.channel_stub = channel_stub\n\n def __call__(self, request, timeout=None, metadata=None, credentials=None):\n self.channel_stub.requests.append((self.method, request))\n\n return self.channel_stub.responses.pop()\n\n\nclass ChannelStub(object):\n \"\"\"Stub for the grpc.Channel interface.\"\"\"\n\n def __init__(self, responses=[]):\n self.responses = responses\n self.requests = []\n\n def unary_unary(self, method, request_serializer=None, response_deserializer=None):\n return MultiCallableStub(method, self)\n\n\nclass TestCluster(unittest.TestCase):\n\n PROJECT = \"project\"\n INSTANCE_ID = \"instance-id\"\n LOCATION_ID = \"location-id\"\n CLUSTER_ID = \"cluster-id\"\n LOCATION_ID = \"location-id\"\n CLUSTER_NAME = (\n \"projects/\" + PROJECT + \"/instances/\" + INSTANCE_ID + \"/clusters/\" + CLUSTER_ID\n )\n LOCATION_PATH = \"projects/\" + PROJECT + \"/locations/\"\n SERVE_NODES = 5\n OP_ID = 5678\n OP_NAME = \"operations/projects/{}/instances/{}/clusters/{}/operations/{}\".format(\n PROJECT, INSTANCE_ID, CLUSTER_ID, OP_ID\n )\n\n @staticmethod\n def _get_target_class():\n from google.cloud.bigtable.cluster import Cluster\n\n return Cluster\n\n def _make_one(self, *args, **kwargs):\n return self._get_target_class()(*args, **kwargs)\n\n @staticmethod\n def _get_target_client_class():\n from google.cloud.bigtable.client import Client\n\n return Client\n\n def _make_client(self, *args, **kwargs):\n return self._get_target_client_class()(*args, **kwargs)\n\n def test_constructor_defaults(self):\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n\n cluster = self._make_one(self.CLUSTER_ID, instance)\n self.assertEqual(cluster.cluster_id, self.CLUSTER_ID)\n self.assertIs(cluster._instance, instance)\n self.assertIsNone(cluster.location_id)\n self.assertIsNone(cluster.state)\n self.assertIsNone(cluster.serve_nodes)\n self.assertIsNone(cluster.default_storage_type)\n\n def test_constructor_non_default(self):\n from google.cloud.bigtable.enums import StorageType\n from google.cloud.bigtable.enums import Cluster\n\n STATE = Cluster.State.READY\n STORAGE_TYPE_SSD = StorageType.SSD\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n\n cluster = self._make_one(\n self.CLUSTER_ID,\n instance,\n location_id=self.LOCATION_ID,\n _state=STATE,\n serve_nodes=self.SERVE_NODES,\n default_storage_type=STORAGE_TYPE_SSD,\n )\n self.assertEqual(cluster.cluster_id, self.CLUSTER_ID)\n self.assertIs(cluster._instance, instance)\n self.assertEqual(cluster.location_id, self.LOCATION_ID)\n self.assertEqual(cluster.state, STATE)\n self.assertEqual(cluster.serve_nodes, self.SERVE_NODES)\n self.assertEqual(cluster.default_storage_type, STORAGE_TYPE_SSD)\n\n def test_name_property(self):\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n instance = _Instance(self.INSTANCE_ID, client)\n cluster = self._make_one(self.CLUSTER_ID, instance)\n\n self.assertEqual(cluster.name, self.CLUSTER_NAME)\n\n def test_from_pb_success(self):\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n from google.cloud.bigtable import enums\n\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n\n location = self.LOCATION_PATH + self.LOCATION_ID\n state = enums.Cluster.State.RESIZING\n storage_type = enums.StorageType.SSD\n cluster_pb = data_v2_pb2.Cluster(\n name=self.CLUSTER_NAME,\n location=location,\n state=state,\n serve_nodes=self.SERVE_NODES,\n default_storage_type=storage_type,\n )\n\n klass = self._get_target_class()\n cluster = klass.from_pb(cluster_pb, instance)\n self.assertIsInstance(cluster, klass)\n self.assertEqual(cluster._instance, instance)\n self.assertEqual(cluster.cluster_id, self.CLUSTER_ID)\n self.assertEqual(cluster.location_id, self.LOCATION_ID)\n self.assertEqual(cluster.state, state)\n self.assertEqual(cluster.serve_nodes, self.SERVE_NODES)\n self.assertEqual(cluster.default_storage_type, storage_type)\n\n def test_from_pb_bad_cluster_name(self):\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n\n bad_cluster_name = \"BAD_NAME\"\n\n cluster_pb = data_v2_pb2.Cluster(name=bad_cluster_name)\n\n klass = self._get_target_class()\n with self.assertRaises(ValueError):\n klass.from_pb(cluster_pb, None)\n\n def test_from_pb_instance_id_mistmatch(self):\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n\n ALT_INSTANCE_ID = \"ALT_INSTANCE_ID\"\n client = _Client(self.PROJECT)\n instance = _Instance(ALT_INSTANCE_ID, client)\n\n self.assertNotEqual(self.INSTANCE_ID, ALT_INSTANCE_ID)\n cluster_pb = data_v2_pb2.Cluster(name=self.CLUSTER_NAME)\n\n klass = self._get_target_class()\n with self.assertRaises(ValueError):\n klass.from_pb(cluster_pb, instance)\n\n def test_from_pb_project_mistmatch(self):\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n\n ALT_PROJECT = \"ALT_PROJECT\"\n client = _Client(project=ALT_PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n\n self.assertNotEqual(self.PROJECT, ALT_PROJECT)\n cluster_pb = data_v2_pb2.Cluster(name=self.CLUSTER_NAME)\n\n klass = self._get_target_class()\n with self.assertRaises(ValueError):\n klass.from_pb(cluster_pb, instance)\n\n def test___eq__(self):\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n cluster1 = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n cluster2 = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n self.assertEqual(cluster1, cluster2)\n\n def test___eq__type_differ(self):\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n cluster1 = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n cluster2 = object()\n self.assertNotEqual(cluster1, cluster2)\n\n def test___ne__same_value(self):\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n cluster1 = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n cluster2 = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n comparison_val = cluster1 != cluster2\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n client = _Client(self.PROJECT)\n instance = _Instance(self.INSTANCE_ID, client)\n cluster1 = self._make_one(\"cluster_id1\", instance, self.LOCATION_ID)\n cluster2 = self._make_one(\"cluster_id2\", instance, self.LOCATION_ID)\n self.assertNotEqual(cluster1, cluster2)\n\n def test_reload(self):\n from google.cloud.bigtable_admin_v2.gapic import bigtable_instance_admin_client\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n from google.cloud.bigtable.enums import StorageType\n from google.cloud.bigtable.enums import Cluster\n\n api = bigtable_instance_admin_client.BigtableInstanceAdminClient(mock.Mock())\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n STORAGE_TYPE_SSD = StorageType.SSD\n instance = _Instance(self.INSTANCE_ID, client)\n cluster = self._make_one(\n self.CLUSTER_ID,\n instance,\n location_id=self.LOCATION_ID,\n serve_nodes=self.SERVE_NODES,\n default_storage_type=STORAGE_TYPE_SSD,\n )\n\n # Create response_pb\n LOCATION_ID_FROM_SERVER = \"new-location-id\"\n STATE = Cluster.State.READY\n SERVE_NODES_FROM_SERVER = 10\n STORAGE_TYPE_FROM_SERVER = StorageType.HDD\n\n response_pb = data_v2_pb2.Cluster(\n name=cluster.name,\n location=self.LOCATION_PATH + LOCATION_ID_FROM_SERVER,\n state=STATE,\n serve_nodes=SERVE_NODES_FROM_SERVER,\n default_storage_type=STORAGE_TYPE_FROM_SERVER,\n )\n\n # Patch the stub used by the API method.\n client._instance_admin_client = api\n instance_admin_client = client._instance_admin_client\n instance_stub = instance_admin_client.transport\n instance_stub.get_cluster.side_effect = [response_pb]\n\n # Create expected_result.\n expected_result = None # reload() has no return value.\n\n # Check Cluster optional config values before.\n self.assertEqual(cluster.location_id, self.LOCATION_ID)\n self.assertIsNone(cluster.state)\n self.assertEqual(cluster.serve_nodes, self.SERVE_NODES)\n self.assertEqual(cluster.default_storage_type, STORAGE_TYPE_SSD)\n\n # Perform the method and check the result.\n result = cluster.reload()\n self.assertEqual(result, expected_result)\n self.assertEqual(cluster.location_id, LOCATION_ID_FROM_SERVER)\n self.assertEqual(cluster.state, STATE)\n self.assertEqual(cluster.serve_nodes, SERVE_NODES_FROM_SERVER)\n self.assertEqual(cluster.default_storage_type, STORAGE_TYPE_FROM_SERVER)\n\n def test_exists(self):\n from google.cloud.bigtable_admin_v2.gapic import bigtable_instance_admin_client\n from google.cloud.bigtable_admin_v2.proto import instance_pb2 as data_v2_pb2\n from google.cloud.bigtable.instance import Instance\n from google.api_core import exceptions\n\n instance_api = bigtable_instance_admin_client.BigtableInstanceAdminClient(\n mock.Mock()\n )\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n instance = Instance(self.INSTANCE_ID, client)\n\n # Create response_pb\n cluster_name = client.instance_admin_client.cluster_path(\n self.PROJECT, self.INSTANCE_ID, self.CLUSTER_ID\n )\n response_pb = data_v2_pb2.Cluster(name=cluster_name)\n\n # Patch the stub used by the API method.\n client._instance_admin_client = instance_api\n instance_admin_client = client._instance_admin_client\n instance_stub = instance_admin_client.transport\n instance_stub.get_cluster.side_effect = [\n response_pb,\n exceptions.NotFound(\"testing\"),\n exceptions.BadRequest(\"testing\"),\n ]\n\n # Perform the method and check the result.\n non_existing_cluster_id = \"cluster-id-2\"\n alt_cluster_1 = self._make_one(self.CLUSTER_ID, instance)\n alt_cluster_2 = self._make_one(non_existing_cluster_id, instance)\n self.assertTrue(alt_cluster_1.exists())\n self.assertFalse(alt_cluster_2.exists())\n with self.assertRaises(exceptions.BadRequest):\n alt_cluster_1.exists()\n\n def test_create(self):\n import datetime\n from google.api_core import operation\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n from google.cloud.bigtable_admin_v2.proto import (\n bigtable_instance_admin_pb2 as messages_v2_pb2,\n )\n from google.cloud._helpers import _datetime_to_pb_timestamp\n from google.cloud.bigtable.instance import Instance\n from google.cloud.bigtable_admin_v2.types import instance_pb2\n from google.cloud.bigtable_admin_v2.gapic import bigtable_instance_admin_client\n from google.cloud.bigtable_admin_v2.proto import (\n bigtable_instance_admin_pb2 as instance_v2_pb2,\n )\n from google.cloud.bigtable.enums import StorageType\n\n NOW = datetime.datetime.utcnow()\n NOW_PB = _datetime_to_pb_timestamp(NOW)\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n STORAGE_TYPE_SSD = StorageType.SSD\n LOCATION = self.LOCATION_PATH + self.LOCATION_ID\n instance = Instance(self.INSTANCE_ID, client)\n cluster = self._make_one(\n self.CLUSTER_ID,\n instance,\n location_id=self.LOCATION_ID,\n serve_nodes=self.SERVE_NODES,\n default_storage_type=STORAGE_TYPE_SSD,\n )\n expected_request_cluster = instance_pb2.Cluster(\n location=LOCATION,\n serve_nodes=cluster.serve_nodes,\n default_storage_type=cluster.default_storage_type,\n )\n expected_request = instance_v2_pb2.CreateClusterRequest(\n parent=instance.name,\n cluster_id=self.CLUSTER_ID,\n cluster=expected_request_cluster,\n )\n\n metadata = messages_v2_pb2.CreateClusterMetadata(request_time=NOW_PB)\n type_url = \"type.googleapis.com/{}\".format(\n messages_v2_pb2.CreateClusterMetadata.DESCRIPTOR.full_name\n )\n response_pb = operations_pb2.Operation(\n name=self.OP_NAME,\n metadata=Any(type_url=type_url, value=metadata.SerializeToString()),\n )\n\n # Patch the stub used by the API method.\n channel = ChannelStub(responses=[response_pb])\n api = bigtable_instance_admin_client.BigtableInstanceAdminClient(\n channel=channel\n )\n client._instance_admin_client = api\n\n # Perform the method and check the result.\n result = cluster.create()\n actual_request = channel.requests[0][1]\n\n self.assertEqual(actual_request, expected_request)\n self.assertIsInstance(result, operation.Operation)\n self.assertEqual(result.operation.name, self.OP_NAME)\n self.assertIsInstance(result.metadata, messages_v2_pb2.CreateClusterMetadata)\n\n def test_update(self):\n import datetime\n from google.api_core import operation\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n from google.cloud._helpers import _datetime_to_pb_timestamp\n from google.cloud.bigtable_admin_v2.proto import (\n bigtable_instance_admin_pb2 as messages_v2_pb2,\n )\n from google.cloud.bigtable_admin_v2.types import instance_pb2\n from google.cloud.bigtable_admin_v2.gapic import bigtable_instance_admin_client\n from google.cloud.bigtable.enums import StorageType\n\n NOW = datetime.datetime.utcnow()\n NOW_PB = _datetime_to_pb_timestamp(NOW)\n\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n STORAGE_TYPE_SSD = StorageType.SSD\n instance = _Instance(self.INSTANCE_ID, client)\n cluster = self._make_one(\n self.CLUSTER_ID,\n instance,\n location_id=self.LOCATION_ID,\n serve_nodes=self.SERVE_NODES,\n default_storage_type=STORAGE_TYPE_SSD,\n )\n # Create expected_request\n expected_request = instance_pb2.Cluster(\n name=cluster.name, serve_nodes=self.SERVE_NODES\n )\n\n metadata = messages_v2_pb2.UpdateClusterMetadata(request_time=NOW_PB)\n type_url = \"type.googleapis.com/{}\".format(\n messages_v2_pb2.UpdateClusterMetadata.DESCRIPTOR.full_name\n )\n response_pb = operations_pb2.Operation(\n name=self.OP_NAME,\n metadata=Any(type_url=type_url, value=metadata.SerializeToString()),\n )\n\n # Patch the stub used by the API method.\n channel = ChannelStub(responses=[response_pb])\n api = bigtable_instance_admin_client.BigtableInstanceAdminClient(\n channel=channel\n )\n client._instance_admin_client = api\n\n # Perform the method and check the result.\n result = cluster.update()\n actual_request = channel.requests[0][1]\n\n self.assertEqual(actual_request, expected_request)\n self.assertIsInstance(result, operation.Operation)\n self.assertEqual(result.operation.name, self.OP_NAME)\n self.assertIsInstance(result.metadata, messages_v2_pb2.UpdateClusterMetadata)\n\n def test_delete(self):\n from google.protobuf import empty_pb2\n from google.cloud.bigtable_admin_v2.gapic import bigtable_instance_admin_client\n\n api = bigtable_instance_admin_client.BigtableInstanceAdminClient(mock.Mock())\n credentials = _make_credentials()\n client = self._make_client(\n project=self.PROJECT, credentials=credentials, admin=True\n )\n instance = _Instance(self.INSTANCE_ID, client)\n cluster = self._make_one(self.CLUSTER_ID, instance, self.LOCATION_ID)\n\n # Create response_pb\n response_pb = empty_pb2.Empty()\n\n # Patch the stub used by the API method.\n client._instance_admin_client = api\n instance_admin_client = client._instance_admin_client\n instance_stub = instance_admin_client.transport\n instance_stub.delete_cluster.side_effect = [response_pb]\n\n # Create expected_result.\n expected_result = None # delete() has no return value.\n\n # Perform the method and check the result.\n result = cluster.delete()\n\n self.assertEqual(result, expected_result)\n\n\nclass _Instance(object):\n def __init__(self, instance_id, client):\n self.instance_id = instance_id\n self._client = client\n\n def __eq__(self, other):\n return other.instance_id == self.instance_id and other._client == self._client\n\n\nclass _Client(object):\n def __init__(self, project):\n self.project = project\n self.project_name = \"projects/\" + self.project\n self._operations_stub = mock.sentinel.operations_stub\n\n def __eq__(self, other):\n return other.project == self.project and other.project_name == self.project_name\n","sub_path":"bigtable/tests/unit/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":19219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"486298379","text":"def unify(x, y, s):\n \"\"\"Unify expressions x,y with substitution s; return a substitution that\n would make x,y equal, or None if x,y can not unify. x and y can be\n variables (e.g. Expr('x')), constants, lists, or Exprs. [Fig. 9.1]\n >>> ppsubst(unify(x + y, y + C, {}))\n {x: y, y: C}\n \"\"\"\n if s is None:\n return None\n elif x == y:\n return s\n elif is_variable(x):\n return unify_var(x, y, s)\n elif is_variable(y):\n return unify_var(y, x, s)\n elif isinstance(x, Expr) and isinstance(y, Expr):\n return unify(x.args, y.args, unify(x.op, y.op, s))\n elif isinstance(x, str) or isinstance(y, str):\n return None\n elif issequence(x) and issequence(y) and len(x) == len(y):\n if not x: return s\n return unify(x[1:], y[1:], unify(x[0], y[0], s))\n else:\n return None\n\ndef is_variable(x):\n \"A variable is an Expr with no args and a lowercase symbol as the op.\"\n return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)\n\ndef unify_var(var, x, s):\n if var in s:\n return unify(s[var], x, s)\n elif occur_check(var, x, s):\n return None\n else:\n return extend(s, var, x)\n\ndef occur_check(var, x, s):\n \"\"\"Return true if variable var occurs anywhere in x\n (or in subst(s, x), if s has a binding for x).\"\"\"\n if var == x:\n return True\n elif is_variable(x) and x in s:\n return occur_check(var, s[x], s)\n elif isinstance(x, Expr):\n return (occur_check(var, x.op, s) or\n occur_check(var, x.args, s))\n elif isinstance(x, (list, tuple)):\n return some(lambda element: occur_check(var, element, s), x)\n else:\n return False\n\ndef extend(s, var, val):\n \"\"\"Copy the substitution s and extend it by setting var to val;\n return copy.\n >>> ppsubst(extend({x: 1}, y, 2))\n {x: 1, y: 2}\n \"\"\"\n s2 = s.copy()\n s2[var] = val\n return s2\n\ndef subst(s, x):\n \"\"\"Substitute the substitution s into the expression x.\n >>> subst({x: 42, y:0}, F(x) + y)\n (F(42) + 0)\n \"\"\"\n if isinstance(x, list):\n return [subst(s, xi) for xi in x]\n elif isinstance(x, tuple):\n return tuple([subst(s, xi) for xi in x])\n elif not isinstance(x, Expr):\n return x\n elif is_var_symbol(x.op):\n return s.get(x, x)\n else:\n return Expr(x.op, *[subst(s, arg) for arg in x.args])\n\ndef fol_fc_ask(KB, alpha):\n \"\"\"Inefficient forward chaining for first-order logic. [Fig. 9.3]\n KB is a FolKB and alpha must be an atomic sentence.\"\"\"\n while True:\n new = {}\n for r in KB.clauses:\n ps, q = parse_definite_clause(standardize_variables(r))\n raise NotImplementedError\n\ndef standardize_variables(sentence, dic=None):\n \"\"\"Replace all the variables in sentence with new variables.\n >>> e = expr('F(a, b, c) & G(c, A, 23)')\n >>> len(variables(standardize_variables(e)))\n 3\n >>> variables(e).intersection(variables(standardize_variables(e)))\n set([])\n >>> is_variable(standardize_variables(expr('x')))\n True\n \"\"\"\n if dic is None: dic = {}\n if not isinstance(sentence, Expr):\n return sentence\n elif is_var_symbol(sentence.op):\n if sentence in dic:\n return dic[sentence]\n else:\n v = Expr('v_%d' % standardize_variables.counter.next())\n dic[sentence] = v\n return v\n else:\n return Expr(sentence.op,\n *[standardize_variables(a, dic) for a in sentence.args])\n\nstandardize_variables.counter = itertools.count()\n\na = input(\"Enter first exp: \")\nb = input(\"Enter second exp: \")\ns = input(\"Enter substitution: \")\n\nres = unify(a,b,c)\n\nprint(res)\n","sub_path":"unify.py","file_name":"unify.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"525312085","text":"import math\n\nclass Solution:\n def modInverse(self, a, m):\n g = self.gcd(a, m)\n \n p = self.power(a, m - 2, m)\n \n return p\n # @param A : integer\n # @return an integer\n def power(self, x, y, m):\n if(y ==0):\n return 1\n \n p = self.power(x, y//2, m) % m\n p = (p*p) % m\n \n if(y%2 == 0):\n return p\n else:\n return ((x*p) % m)\n \n def gcd(self, a, b):\n if(a == 0):\n return b\n else:\n return self.gcd(b%a, a)\n \n \n def solve(self, A):\n if(A == 2):\n A = 3\n q = 3 * (3**(A - 2))\n p = 3 * ((3**(A - 3)) - ((3**(A - 3))/3))\n #q = q + p \n \n if q%p == 0:\n print(\"q: \" + str(q))\n print(\"p: \" + str(p))\n return self.modInverse(q/p, (10**9)+7)\n else:\n x = q%p\n print(\"q: \" + str(q))\n print(\"p: \" + str(p))\n print(x)\n print(q//x)\n print(p//x)\n return self.modInverse((q/x)*(p/x), (10**9)+7)\n#https://www.interviewbit.com/test/b1d9dc30a7/?signature=BAhpAwgsCA%3D%3D--3f52f3e83a02d4a97ed6da667a55bee349c7b7b4#/problem_6","sub_path":"Unkown/Basketball.py","file_name":"Basketball.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"234175085","text":"# Return the two numbers from a sorted array such that they add up to a specific target\n# assume each input have exactly one solution and can not use same number twice\n\n\n# Method-1: using brute force\n# Time complexity: O(n^2)\n# Space complexity: O(1)\n# def two_sum(arr, sum_val):\n# for i in range(len(arr) - 1):\n# for j in range(i+1, len(arr)):\n# if arr[i] + arr[j] == sum_val:\n# print((arr[i], arr[j]))\n# return True\n#\n# return False\n\n# Method-2: using hash table\n# Time complexity: O(n)\n# Space complexity: O(n)\n# def two_sum(arr, sum_val):\n#\n# hast_table = dict()\n# for i in range(len(arr)):\n# if arr[i] in hast_table:\n# print(hast_table[arr[i]], arr[i])\n# return True\n# else:\n# hast_table[sum_val - arr[i]] = arr[i]\n# print(hast_table)\n#\n# return False\n\n# Method-3: traverse from both side towards middle\n# Time complexity: O(n)\n# Space complexity: O(1)\ndef two_sum(arr, sum_val):\n i = 0\n j = len(arr) - 1\n\n while i <= j:\n if arr[i] + arr[j] == sum_val:\n print(arr[i], arr[j])\n return True\n elif arr[i] + arr[j] < sum_val:\n i += 1\n\n # arr[i] + arr[j] > sum_val\n else:\n j -= 1\n\n return False\n\n\nif __name__ == \"__main__\":\n\n a = [2, 3, 4, 6, 7, 9]\n target = 10\n print(two_sum(a, target))\n","sub_path":"array/two_sum_problem.py","file_name":"two_sum_problem.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"487702885","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport base64\nfrom io import BytesIO\nfrom PIL import Image, ImageChops\nimport random\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\n\ndef get_gap_test(picture0, picture1, picture2):\n position=picture0.getbbox()\n up=position[3]\n bottom=position[1]\n left=position[0]\n right=position[2]\n\n #diff_position=ImageChops.difference(picture1, picture2).getbbox()\n #diff_left=diff_position[0]\n #diff_right=diff_position[2]\n\n moved = {}\n for move in range(0,picture0.size[0]-right):\n moved[move]=0\n\n for checkx in range(0,picture0.size[0]):\n for checky in range(bottom,up):\n for checkpixel in range(0,3):\n thisabs=abs(picture2.getpixel((checkx,checky))[checkpixel]-picture1.getpixel((checkx,checky))[checkpixel])\n for move in range(0,picture0.size[0]-right):\n if checkxmove+right:\n moved[move]+=thisabs\n else:\n moved[move]+=abs(picture0.getpixel((checkx-move,checky))[checkpixel]-picture1.getpixel((checkx,checky))[checkpixel])\n\n minmove=0\n minmoved=None\n for move in moved.keys():\n if minmoved is None or minmoved >= moved[move]:\n minmoved=moved[move]\n minmove=move\n print(minmove)\n return minmove\n\ndef simpleSimulateDragX(driver, source, targetOffsetX):\n action_chains = ActionChains(driver)\n action_chains.click_and_hold(source)\n action_chains.pause(0.2)\n action_chains.move_by_offset(targetOffsetX, 0)\n action_chains.pause(0.6)\n action_chains.release()\n action_chains.perform()\n\nheaders = {'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}\n\nparser = argparse.ArgumentParser()\nparser.description='please enter parameters ...'\nparser.add_argument('-s', '--search', help='what you want to search', dest='search', type=str, default='lindy')\nparser.add_argument('-o', '--output', help='output file', dest='out', type=str, default='hermes.txt')\nargs = parser.parse_args()\n\nurl='https://www.hermes.com/pl/en/search/?s='+args.search+'#||Category'\n\n# Get the Firefox profile object\nprofile = webdriver.firefox.webdriver.FirefoxProfile()\n# Disable images\n#profile.set_preference('permissions.default.image', 2)\n# Disable Flash\nprofile.set_preference(\n 'dom.ipc.plugins.enabled.libflashplayer.so', 'false'\n)\nprofile.native_events_enabled = True\noptions = webdriver.firefox.options.Options()\noptions.headless = True\nfirefox = webdriver.Firefox(firefox_profile=profile, options=options, timeout=60)\nfirefox.get(url)\n\ngeted = False\nerrors='unknown errors'\ncontent=''\n\ntime.sleep(2)\nwhile 'You have been blocked' in firefox.title:\n print(firefox.title)\n firefox.switch_to.frame(0)\n WebDriverWait(firefox, 30).until(lambda the_driver: the_driver.find_element_by_xpath(\"//div[@class='geetest_holder geetest_wind geetest_ready']\").is_displayed())\n captcha = firefox.find_element_by_xpath('//div[@class=\"geetest_holder geetest_wind geetest_ready\"]')\n ActionChains(firefox).move_to_element_with_offset(to_element=captcha, xoffset=0, yoffset=1).perform()\n ActionChains(firefox).move_to_element_with_offset(to_element=captcha, xoffset=0, yoffset=2).perform()\n time.sleep(2)\n #with open('source2.txt', 'w') as filehermes:\n # filehermes.write(firefox.page_source)\n WebDriverWait(firefox, 30).until(lambda the_driver: the_driver.find_element_by_xpath(\"//div[@class='geetest_holder geetest_wind geetest_wait_compute']\").is_displayed())\n compute = firefox.find_element_by_xpath('//div[@class=\"geetest_holder geetest_wind geetest_wait_compute\"]')\n compute.click()\n time.sleep(3)\n WebDriverWait(firefox, 30).until(lambda the_driver: the_driver.find_element_by_xpath(\"//div[@class='geetest_slider_button']\").is_displayed())\n img_info = firefox.execute_script('return document.getElementsByClassName(\"geetest_canvas_fullbg geetest_fade geetest_absolute\")[0].toDataURL(\"image/png\");')\n img_base64 = img_info.split(\",\")[1]\n img_bytes = base64.b64decode(img_base64)\n picture1 = Image.open(BytesIO(img_bytes))\n img_info = firefox.execute_script('return document.getElementsByClassName(\"geetest_canvas_bg geetest_absolute\")[0].toDataURL(\"image/png\");')\n img_base64 = img_info.split(\",\")[1]\n img_bytes = base64.b64decode(img_base64)\n picture2 = Image.open(BytesIO(img_bytes))\n img_info = firefox.execute_script('return document.getElementsByClassName(\"geetest_canvas_slice geetest_absolute\")[0].toDataURL(\"image/png\");')\n img_base64 = img_info.split(\",\")[1]\n img_bytes = base64.b64decode(img_base64)\n picture0 = Image.open(BytesIO(img_bytes))\n gap = get_gap_test(picture0, picture1, picture2)\n slider = firefox.find_element_by_xpath('//div[@class=\"geetest_slider_button\"]')\n simpleSimulateDragX(firefox, slider, gap)\n firefox.switch_to_default_content()\n time.sleep(30)\n if 'You have been blocked' in firefox.title:\n firefox.refresh()\n\nsubtitles = firefox.find_elements_by_xpath('//div[@class=\"sub-title\"]')\nif len(subtitles) == 0:\n geted = True\nelse:\n errors=subtitles[0].text\n print(errors)\nmaintitles = firefox.find_elements_by_xpath('//div[@class=\"main-title\"]')\nif len(maintitles) > 0:\n content=maintitles[0].text\n print(content)\nelse:\n print('no main-title')\n geted = False\nwith open(args.out, 'w') as filehermes:\n filehermes.write(content+'\\n'+url)\n\nfirefox.close()\nfirefox.quit()\n\nif not geted:\n raise Exception(errors)\n","sub_path":"hermes.py","file_name":"hermes.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"433669724","text":"import os\nimport numpy as np\nimport librosa as la\n\n\ndef convert_format():\n\tsongs = os.listdir(\"coversongs/covers32k\")\n\tfor i in range(len(songs)):\n\t\tsong = songs[i]\n\t\tcovers = [d for d in os.listdir(\"coversongs/covers32k/{}\".format(song)) if \"mp3\" in d]\n\t\tfor j in range(len(covers)):\n\t\t\tcover = covers[j]\n\t\t\tos.system(\"cp coversongs/covers32k/{}/{} covers80/{}_{}.mp3\".format(song, cover, i, j))\n\n\ndef convert_numpy():\n songs = [\"covers80/\"+d for d in os.listdir(\"covers80\") if \"mp3\" in d]\n for i in range(len(songs)):\n \tname = songs[i].split(\"/\")[-1].split(\".\")[0]\n \tprint(\"coverting\", i)\n \taudio = la.load(songs[i])[0]\n \twith open(\"covers80npy/{}.npy\".format(name), \"wb\") as f:\n \t\tnp.save(f, la.feature.chroma_cqt(audio))\n\n\ndef load_all():\n\tchromas = list()\n\tsongs = [\"covers80npy/\"+d for d in os.listdir(\"covers80npy\") if \"npy\" in d]\n\tfor s in songs:\n\t\tchromas.append(np.load(s))\n\treturn chromas\n\n","sub_path":"covers80.py","file_name":"covers80.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"629109599","text":"## Script maps IP information exchanges to illustrate information flow\n## and centrality metrics on the network. \n## Subnet option allows for filtering for traffic internal to a given subnet\n## Output is an annotated GraphML file that can be imported into Cytoscape.\n## Annotations include centrality calculations based on the completed graph \n\n## This is the only script that uses the .json file generated by the length_preprocess script\n\n# Required Input: .json file from the length_preprocess script\n# Optional Input: Number of clusters, output graphml name\n# Output: GraphML file\n\nimport json\nfrom argparse import ArgumentParser\nfrom scapy.all import *\nimport numpy as np\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nimport matplotlib.pyplot as plt\n\nimport time\n\ndef parse_length_dict(length_dict, conversation_id = None, index=0, verbose=False):\n\n if index == 0:\n reported_lengths = []\n if verbose:\n print(f\"Returning only the reported lengths.\")\n elif index == 1:\n wire_lengths = []\n if verbose:\n print(f\"Returning only the wire lengths.\")\n elif index == 2:\n reported_lengths = []\n wire_lengths = []\n if verbose:\n print(f\"Returning a list each for reported length and wire length\")\n else:\n print(f\"Provide a valid index for the length lists.\")\n return\n\n if conversation_id == None:\n print(f\"Provide a conversation id to target\")\n return\n\n for packet in length_dict[conversation_id]:\n if index == 0 or index == 2:\n reported_lengths.append(packet[0])\n if index == 1 or index == 2:\n wire_lengths.append(packet[1])\n\n if index == 0:\n return reported_lengths\n elif index == 1:\n return wire_lengths\n elif index == 2:\n return reported_lengths, wire_lengths\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('-f', '--file', help='Path to input json file', required=True)\n parser.add_argument('-c', '--clusters', help='Number of kmeans clusters to use', default=8)\n parser.add_argument('-d', '--directory', help='Directory of input json files')\n parser.add_argument('-o', '--output', help='File name for output graphml file', default= \"output.graphml\")\n args = parser.parse_args()\n\n with open(args.file, 'r') as f:\n print(f\"Loading json file: {args.file}\")\n length_dict = dict(json.load(f))\n \n packet_count = []\n X = []\n start = time.time()\n for key in length_dict:\n print(f\"Loading conversation: {key}\")\n reported_lengths = parse_length_dict(length_dict, conversation_id=key, index=0)\n X += reported_lengths\n finish = time.time()\n print(f\"Loading all conversations took {finish - start:.3f} seconds.\")\n\n X = np.array(X)\n start = time.time() \n # kmeans = KMeans(n_clusters=int(args.clusters))\n kmeans = MiniBatchKMeans(n_clusters=int(args.clusters))\n kmeans.fit(X.reshape(-1,1))\n finish = time.time()\n print(f\"Kmeans clustering took {finish - start:.3f} seconds.\")\n # from IPython import embed; embed()\n\n plt.scatter(X, kmeans.labels_)\n # print(kmeans.cluster_centers_)\n # print(kmeans.labels_)\n plt.show()\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"259025571","text":"import math\nfrom PyCal.Memory.data_factory import DataFactory\nclass IF92:\n def __init__(self):\n self.__data_type = \"DataTab\"\n self.__data_factory = DataFactory()\n\n def getScore(self, fid):\n result = {}\n eg69 = \"EG69\"\n\n fl_method_assigment = self.__data_factory.getTab(self.__data_type, \"Method Assignment\", {\"FID\": [fid], \"Assignment ID\": [], \"Method ID\": []})\n \"\"\"\n 1. Check the METHOD ASSIGNMENT tab\n A) If there is an input in the METHOD ID column then:\n \"\"\"\n fl_method_assigment_mid = fl_method_assigment[fl_method_assigment[\"Method ID\"].notnull()]\n \"\"\"\n 2. count the number of ASSIGNMENT IDs related to each particular METHOD ID(Methods Assignment tab)\n \"\"\"\n result[eg69] = len(fl_method_assigment_mid[\"Assignment ID\"].values)\n \"\"\"\n B) If there is no input then:\n 2. count the number of ASSIGNMENT IDs as \"0\" or don't count them.\n At the end take the results and use the EG to obtain a score for each Method ID (related to a particular Freelancer ID)\n \"\"\"\n return result\n# class IF93:\n# def __init__(self):\n# self.__data_type = \"DataTab\"\n# self.__data_factory = DataFactory()\n#\n# def getScore(self, fid):\n# result = {}\n# eg70 = \"EG70\"\n# fl_job = self.__data_factory.getTab(self.__data_type, \"Job\", {\"FID\": [fid], \"Industry/Sub-Domain\":[]})\n# fl_assignment = self.__data_factory.getTab(self.__data_type, \"Assignment\", {\"FID\": [fid], \"Industry/Sub-Domain\": []})\n# fl_job_method = self.__data_factory.getTab(self.__data_type, \"Method Job\", {\"FID\": [fid], \"JID\": [], \"Method\": []})\n# \"\"\"\n# 1. Check METHOD ID column in the METHOD JOB tab\n# A) If there is an input then\n# 2. Check INDUSTRY (Sub-Domain) column in the JOB tab\n# AA) If there is no Input (its because its a consultancy) then:\n# \"\"\"\n# fl_job_method_wm = fl_job_method[fl_job_method[\"Method ID\"].notnull()]\n# fl_job_method_wm_grouped = fl_job_method_wm.groupby(\"JID\")[\"Method\"]\n# jid_method = {k:v for k,v in fl_job_method_wm_grouped}\n# \"\"\"\n# 3. go to assignment tab and work only with Assignments related to that specific Consultancy Jobs ID\n# \"\"\"\n# fl_job_method_wm_jid = fl_job_method_wm[\"JID\"].values\n# \"\"\"\n# 4. then take the INDUSTRY (Sub-Domain) related to that particular JOB ID (Assignment tab)\n# \"\"\"\n# fl_job_jid = fl_job[fl_job[\"JID\"].isin(fl_job_method_wm_jid)]\n# fl_job_jid_nosd = fl_job_jid[fl_job_jid[\"Sub-Domain\"].isnull()]\n# fl_job_jid_nosd_jid = fl_job_jid_nosd[\"JID\"].values\n# fl_assignment_jid = fl_assignment[fl_assignment[\"JID\"].isin(fl_job_jid_nosd_jid)]\n# \"\"\"\n# 5. then for each Method ID column(Method Job tab) take the associated JOB ID (Method Job tab) and therefore the associated ASSIGNMENT ID(Assignment tab) and therefore the associated INDUSTRY (Sub-Domain) (Assignment tab)\n# \"\"\"\n# fl_assignment_jid[\"JID\"] = fl_assignment_jid[\"JID\"].map(i => jid_method[i])\n# fl_assignemnt_jid_grouped = fl_assignment_jid.groupby(\"JID\")[\"Industry/Sub-Domain\"]\n# aa_out = {k: set(v) for k,v in fl_assignment_jid_grouped}\n# \"\"\"\n# AB) If there is input (its because its not a consultancy) then:\n# \"\"\"\n# fl_job_jid_wsd = fl_job_jid[fl_job_jid[\"Sub-Domain\"].notnull()]\n# \"\"\"\n# 3. take the INDUSTRY (Sub-Domain) (Job tab) related to that particular JOB ID (Job tab)\n# \"\"\"\n# fl_job_jid_wsd[\"JID\"] = fl_job_jid_wsd[\"JID\"].map(i => jid_method[i])\n# \"\"\"\n# 4. then for each Method ID column(Method Job tab) take the associated JOB ID (Method Job tab) and therefore the associated INDUSTRY (Sub-Domain) (Job tab)\n# \"\"\"\n# fl_job_jid_wsd_grouped = fl_job_jid_wsd.groupby(\"JID\")[\"Industry/Sub-Domain\"]\n# ab_out = {k: set(v) for k,v in fl_job_jid_wsd_grouped}\n#\n# result[eg70] = {k: len(aa_out.get(k, set()) | ab_out.get(k, set())) for k in set(aa_out) | set(ab_out)}\n# \"\"\"\n# B) If there is not input the\n# Count the number of different INDUSTRIES as \"0\" or don't count them.\n# ----\n# -At the end for each FREELANCER ID take all the INDUSTRY (Sub-Domain) obtained for each METHOD ID\n# -Count the number of different INDUSTRY (Sub-Domain) per METHOD ID\n# \"\"\"\n# return result\n#\n# class IF94:\n# def __init__(self):\n# self.__data_type = \"DataTab\"\n# self.__data_factory = DataFactory()\n#\n# def getScore(self, fid):\n# result = {}\n# eg71 = \"EG71\"\n# \"\"\"\n# 1. Check the METHODS column in the Trainings & Certificates tab\n# \"\"\"\n# fl_tnc = self.__data_factory.getTab(self.__data_type, \"Trainings & Certificates\", {\"FID\": [fid], \"TNCID\": [], \"Method\": []})\n# \"\"\"\n# 2. then in the Trainings & Certificates ID column, count the number of Training & Certificates related to the specific METHOD\n# \"\"\"\n# fl_tnc_grouped = fl_tnc.groupby(\"Method\")[\"TNCID\"]\n# result[eg71] = {k: len(list(v)) for k,v in fl_tnc_grouped}\n# return result\n","sub_path":"Brain/method/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"214993265","text":"import datetime\n\nclass Patient:\n\n def __init__(self,ID = 0,firstname = 'First Name',\\\n middlename = 'Middle Name',lastname = 'Last Name',\\\n maidenname = 'Maiden Name', gender = 'Gender',\\\n birthday = '01.01.01',age = 0):\n \n self.ID = str(ID)\n self.FirstName = firstname\n self.MiddleName = middlename\n self.LastName = lastname\n self.MaidenName = maidenname\n self.Gender = gender\n self.Birthday = birthday\n self.Age = str(age)\n self.LocalPatientID = ''\n self.createLocalID()\n \n def createLocalID(self):\n \"\"\"encodes the patient information to the LocalPatientID in the EDF header record field\"\"\"\n\n # ascii-character limit for every patient information (in bytes)\n lenID = 5\n lenFirstName = 20\n lenMiddleName = 12\n lenLastName = 12\n lenMaidenName = 12\n lenGender = 6\n lenBirthday = 10\n lenAge = 3\n\n LocalPatientIDlist = [self.ID, self.FirstName, self.MiddleName,\\\n self.LastName, self.MaidenName, self.Gender,\\\n self.Birthday, self.Age]\n lenLocalPatientID = [lenID, lenFirstName, lenMiddleName,\\\n lenLastName, lenMaidenName, lenGender,\\\n lenBirthday, lenAge]\n \n for i in range(len(LocalPatientIDlist)):\n maxlen = lenLocalPatientID[i]\n if len(LocalPatientIDlist[i]) > maxlen:\n # truncates the string if length is greater than limit\n LocalPatientIDlist[i] = LocalPatientIDlist[i][:maxlen] \n else: \n LocalPatientIDlist[i] = LocalPatientIDlist[i].ljust(maxlen)\n \n # converts the list to a string with no separator in between elements\n self.LocalPatientID = ''.join(LocalPatientIDlist)\n\n def get(self):\n \"\"\" returns the LocalPatientID attribute \"\"\"\n\n return self.LocalPatientID\n \nclass BioSignal:\n \"\"\"contains the biomedical signals of the patient as well as their technical information\"\"\"\n\n def __init__(self, Label = 'Label', TransducerType = '', PhyDimension = 'Dimension',\\\n PhyMin = -32767, PhyMax = 32767, DigMin = -32767, DigMax = 32767, Prefiltering = '',\\\n NRsamples = 1, RawBioSignal = []):\n # Label = Standard: 'TypeOfSignal Sensor'\n # DigMin > -32767\n # DigMax < 32767\n \n Reserved = ' '*32\n\n # fields defined in the EDF format\n self.Label = Label \n self.TransducerType = TransducerType\n self.PhyDimension = PhyDimension\n self.PhyMin = str(PhyMin) \n self.PhyMax = str(PhyMax)\n self.DigMin = str(DigMin) \n self.DigMax = str(DigMax) \n self.Prefiltering = Prefiltering\n self.NRsamples = str(NRsamples)\n self.Reserved = Reserved\n \n self.TechInfo = [] # list containing 256 bytes of characters describing the technical characteristics of each signal\n self.RawBioSignal = RawBioSignal # the biomedical signal itself\n\n self.createTechInfo()\n \n def createTechInfo(self):\n \"\"\"encodes the biomedical signal technical information to the EDF header record\"\"\"\n\n # ascii-character limit for every biosignal information (in bytes)\n lenLabel = 16\n lenTransducerType = 80\n lenPhyDimension = 8\n lenPhyMin = 8\n lenPhyMax = 8\n lenDigMin = 8\n lenDigMax = 8\n lenPrefiltering = 80\n lenNRsamples = 8\n lenReserved = 32\n\n self.TechInfo = [self.Label, self.TransducerType, self.PhyDimension, self.PhyMin, self.PhyMax, self.DigMin, self.DigMax, self.Prefiltering,\\\n self.NRsamples, self.Reserved]\n lenTechInfo = [lenLabel, lenTransducerType, lenPhyDimension, lenPhyMin, lenPhyMax, lenDigMin, lenDigMax, lenPrefiltering, lenNRsamples, lenReserved]\n\n for i in range(len(self.TechInfo)):\n maxlen = lenTechInfo[i]\n if len(self.TechInfo[i]) > maxlen:\n # truncates the string if length is greater than limit\n self.TechInfo[i] = self.TechInfo[i][:maxlen] \n else:\n \n self.TechInfo[i] = self.TechInfo[i].ljust(maxlen)\n \nclass EDF:\n \"\"\"manipulates the Patient and BioSignal objects to create an EDF file\"\"\"\n\n def __init__(self, Patient, BioSignals, StartDate = '01.01.01', StartTime = '01.59.59', Location = '',\\\n nDataRecord = -1, DurationDataRecord = 1, ):\n # StartDate = dd.mm.yy\n # StartTime = hh.mm.ss\n \n Reserved = ' '*44\n\n # fields defined in the EDF format\n self.Version = '0' # 0 is the only version number allowed\n self.LocalPatientID = Patient.get() \n self.LocalRecordingID = 'Startdate ' + Location # Location should contain a date (DD-MMM-YYYY) and the location of the patient\n self.StartDate = StartDate\n self.StartTime = StartTime\n self.nSignals = str(len(BioSignals))\n self.nBytesHeader = str(256 + 256*int(self.nSignals))\n self.EDFPlus = Reserved\n self.nDataRecord = str(nDataRecord) # if unknown, default value is -1 (prior or during recording)\n self.DurationDataRecord = str(DurationDataRecord)\n\n self.BioSignals = BioSignals\n self.HeaderRecord = '' # contains the header record information of the EDF data\n self.DataRecord = '' # contains the 2-byte ASCII encided data record values of the BioSignals\n self.EDFFile = '' # contains the EDF file of a patient and will be saved as .edf\n \n self.Starttime = datetime.datetime.today() + datetime.timedelta(seconds = -15)\n self.timestamp = self.Starttime.strftime(\"%H%M%S\")\n \n self.createHeaderRecord()\n self.createDataRecord()\n\n \n def createHeaderRecord(self):\n \"\"\"creates the header record fields of the EDF file\"\"\"\n\n # ascii-character limit for every header record information (in bytes)\n lenVersion = 8\n lenLocalPatientID = 80\n lenLocalRecordingID = 80\n lenStartDate = 8\n lenStartTime = 8\n lennBytesHeader = 8\n lenEDFPlus = 44\n lennDataRecord = 8\n lenDurationDataRecord = 8\n lennSignals = 4\n \n HeaderInfolist = [self.Version, self.LocalPatientID, self.LocalRecordingID, self.StartDate, self.StartTime, self.nBytesHeader, self.EDFPlus,\\\n self.nDataRecord, self.DurationDataRecord, self.nSignals]\n lenHeaderInfo = [lenVersion, lenLocalPatientID, lenLocalRecordingID, lenStartDate, lenStartTime, lennBytesHeader, lenEDFPlus, lennDataRecord,\\\n lenDurationDataRecord, lennSignals]\n\n for i in range(len(HeaderInfolist)):\n maxlen = lenHeaderInfo[i]\n if len(HeaderInfolist[i]) > maxlen:\n # truncates the string if length is greater than limit\n HeaderInfolist[i] = HeaderInfolist[i][:maxlen] \n \n else:\n HeaderInfolist[i] = HeaderInfolist[i].ljust(maxlen)\n \n # converts the list to a string with no separator in between elements\n self.HeaderRecord = ''.join(HeaderInfolist) \n\n # concatenates each BioSignal TechInfo to the Header Record string\n for i in range(len(self.BioSignals[0].TechInfo)):\n for x in range(len(self.BioSignals)):\n self.HeaderRecord = self.HeaderRecord + self.BioSignals[x].TechInfo[i]\n\n\n def createDataRecord(self):\n \"\"\"creates the data record fields of the EDF file\"\"\"\n\n counter = 0\n DataRecordlist = []\n end = []\n offset = []\n start = []\n temp = []\n\n def DecToBin(num):\n # converts a decimal number to its 16-bit binary representation\n \n BinStr = ''\n if num == 0: return '0'*16\n while num > 0:\n BinStr = str(num % 2) + BinStr\n num = num >> 1 # right-shift the num by 1 bit\n BinStr = BinStr.zfill(16) # make BinStr a 16-bit string\n return BinStr\n\n for i in range(len(self.BioSignals)):\n offset.append(int(self.BioSignals[i].NRsamples))\n start.append(0)\n end.append(0)\n\n while (counter < int(self.nDataRecord)):\n \n for x in range(len(self.BioSignals)):\n\n end[x] = start[x] + offset[x]\n temp = self.BioSignals[x].RawBioSignal[start[x]:end[x]]\n\n for i in range(len(temp)):\n intRawValue = temp[i]\n\n if intRawValue >= 0:\n # if positive-valued, convert to binary\n binRawValue = DecToBin(intRawValue)\n else:\n # if negative, get the positive representation by adding (2**16-1)\n # these are the numbers from 32768-65535\n negRawValue = intRawValue + (2**16-1)\n # then convert to binary\n binRawValue = DecToBin(negRawValue)\n\n # divide the 16-bit binary number to two 8-bit binary numbers (MSByte and LSByte)\n MSByte = binRawValue[:8]\n LSByte = binRawValue[8:]\n\n # convert each byte to decimal then get its ASCII representation \n chrMSByte = chr(int(MSByte,2))\n chrLSByte = chr(int(LSByte,2))\n\n # each value in the data record is a 2-byte 2's complement integer represented by its ASCII character\n # it is arranged as: Value = LSB,MSB\n DataRecordlist.extend([chrLSByte, chrMSByte])\n\n # update the pointer for the next set of data records\n start[x] = end[x]\n\n counter += 1\n\n # when all BioSignal objects are accessed and encoded, converts the list to a string\n self.DataRecord = ''.join(DataRecordlist)\n \n def get(self,myPatient):\n\n self.EDFFile = self.HeaderRecord + self.DataRecord\n edffile = open(myPatient.LastName + '_' + self.timestamp + '.edf', 'wb+')\n edffile.write(self.EDFFile)\n edffile.close()\n","sub_path":"lifelink/rxbox/branches/RxBox v0.2/edf.py","file_name":"edf.py","file_ext":"py","file_size_in_byte":10770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"321298595","text":"#!/usr/bin/python\nimport sys\nimport numpy as np\n\n\n# ARGUMENTS: \n# Takes an input of the carbon indices of a GQD assembly (space delimited, with one newline character between the different GQDs) as the first argument and prints out a plumed input file that calculates the in plane vectors (for the 1.5 nm GQD) and the distance between the GQDs. (NOTE: This uses in plane vectors defined based on the central ring, not the same as the other plumedPrint.py script)\n# input file should be in VMD indices, this automatically adds one to the VMD indices to get the correct plumed ones\n# EBau 8/11/14\n\ndef printComments(output):\n output.write('# plumed input file to print carbon vectors and distance between GQDs' + 2*'\\n')\n\n\ndef printlist(gqds,output):\n y=0\n for x in gqds:\n numlist = x.split()\n output.write('cgra%s: COM ATOMS={' % repr(y+1) )\n z=0\n for no in numlist:\n num=int(no)\n if z < len(numlist)-1:\n output.write(repr(num+1) + ' ')\n else:\n output.write(repr(num+1))\n z=z+1\n output.write('}')\n output.write('\\n' + '\\n')\n y=y+1\n\ndef distancePrint(gqds,output):\n for x in range(1,len(gqds)):\n output.write('cdist%s%s: DISTANCE ATOMS=cgra%s,cgra%s COMPONENTS' % (x, repr(x+1), x, repr(x+1)) + '\\n')\n output.write('\\n')\n\ndef printCarbons(gqds,output):\n y=1\n for x in gqds:\n z=0\n numlist = x.split()\n if y==len(gqds): \n output.write('c%sa: DISTANCE ATOMS=%s,%s COMPONENTS' % (repr(y),repr(int(numlist[0])+1),repr(int(numlist[2])+1)) + '\\n')\n output.write('#c%sb: DISTANCE ATOMS=%s,%s COMPONENTS' % (repr(y),repr(int(numlist[0])+1),repr(int(numlist[5])+1)) + '\\n')\n else:\n output.write('c%sa: DISTANCE ATOMS=%s,%s COMPONENTS' % (repr(y),repr(int(numlist[0])+1),repr(int(numlist[2])+1)) + '\\n')\n output.write('c%sb: DISTANCE ATOMS=%s,%s COMPONENTS' % (repr(y),repr(int(numlist[0])+1),repr(int(numlist[5])+1)) + '\\n')\n y=y+1\n output.write('\\n')\n\ndef printPlumed(gqds,output):\n output.write('PRINT ARG=')\n for x in range(1,len(gqds)):\n y=x+1\n if x < len(gqds)-1:\n output.write('c%sa.x,c%sa.y,c%sa.z,' % (x,x,x))\n output.write('c%sb.x,c%sb.y,c%sb.z,' % (x,x,x))\n output.write('cdist%s%s.x,cdist%s%s.y,cdist%s%s.z' % (x,y,x,y,x,y))\n output.write(',')\n else:\n output.write('c%sa.x,c%sa.y,c%sa.z,' % (x,x,x))\n output.write('c%sb.x,c%sb.y,c%sb.z,' % (x,x,x))\n output.write('cdist%s%s.x,cdist%s%s.y,cdist%s%s.z,' % (x,y,x,y,x,y))\n output.write('c%sa.x,c%sa.y,c%sa.z' % (x+1,x+1,x+1))\n output.write(' FILE=vectorsHelix')\n\ndef main():\n numbers = open(sys.argv[1], 'r')\n input = numbers.read()\n output = open(sys.argv[2],'w')\n gqds = input.split('\\n')\n del gqds[-1]\n printComments(output)\n printlist(gqds,output)\n distancePrint(gqds,output)\n printCarbons(gqds,output)\n printPlumed(gqds,output)\n\nif __name__ == '__main__':\n main()\n","sub_path":"plumedHelixPrint.py","file_name":"plumedHelixPrint.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"450596268","text":"\"\"\"SAML SOAP Binding Query/Response Interface with service hosted in\nPaste paster web server\n\nNERC DataGrid Project\n\"\"\"\n__author__ = \"P J Kershaw\"\n__date__ = \"01/07/10\"\n__copyright__ = \"(C) 2010 Science and Technology Facilities Council\"\n__license__ = \"http://www.apache.org/licenses/LICENSE-2.0\"\n__contact__ = \"Philip.Kershaw@stfc.ac.uk\"\n__revision__ = '$Id$'\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport unittest\nfrom os import path\nfrom ndg.saml import importElementTree\nElementTree = importElementTree()\n\nfrom ndg.soap.utils.etree import prettyPrint\n\nfrom ndg.saml.saml2.core import Attribute, StatusCode\nfrom ndg.saml.xml.etree import ResponseElementTree\nfrom ndg.saml.saml2.binding.soap.client.attributequery import \\\n AttributeQuerySslSOAPBinding\nfrom ndg.saml.utils.factory import AttributeQueryFactory\nfrom ndg.saml.test.binding.soap import WithPasterBaseTestCase, paste_installed\n \n \nclass SamlSslSoapBindingTestCase(WithPasterBaseTestCase):\n \"\"\"Test SAML SOAP Binding with SSL\"\"\"\n SERVICE_URI = 'https://localhost:5443/attributeauthority'\n SUBJECT = \"https://openid.localhost/philip.kershaw\"\n SUBJECT_FORMAT = \"urn:ndg:saml:openid\"\n CONFIG_FILENAME = 'attribute-interface.ini'\n \n CLIENT_CERT_FILEPATH = path.join(WithPasterBaseTestCase.THIS_DIR, \n 'localhost.crt')\n CLIENT_PRIKEY_FILEPATH = path.join(WithPasterBaseTestCase.THIS_DIR, \n 'localhost.key')\n CLIENT_CACERT_DIR = path.join(WithPasterBaseTestCase.THIS_DIR, 'ca')\n VALID_DNS = [\n '/O=NDG/OU=Security/CN=localhost', \n ]\n \n @unittest.skipIf(not paste_installed, 'Need Paste.Deploy to run '\n 'SamlSslSoapBindingTestCase')\n \n def __init__(self, *arg, **kw):\n kw['withSSL'] = True\n super(SamlSslSoapBindingTestCase, self).__init__(*arg, **kw)\n \n def test02SendQuery(self):\n query_binding = AttributeQuerySslSOAPBinding()\n \n attribute_query = AttributeQueryFactory.create()\n attribute_query.subject.nameID.format = self.__class__.SUBJECT_FORMAT\n attribute_query.subject.nameID.value = self.__class__.SUBJECT\n attribute_query.issuerName = '/O=Site A/CN=Authorisation Service'\n\n\n attribute = Attribute()\n attribute.name = 'urn:ndg:saml:emailaddress'\n attribute.friendlyName = 'emailAddress'\n attribute.nameFormat = 'http://www.w3.org/2001/XMLSchema'\n \n attribute_query.attributes.append(attribute)\n \n query_binding.clockSkewTolerance = 2.\n query_binding.sslCACertDir = self.__class__.CLIENT_CACERT_DIR\n query_binding.sslCertFilePath = self.__class__.CLIENT_CERT_FILEPATH\n query_binding.sslPriKeyFilePath = self.__class__.CLIENT_PRIKEY_FILEPATH\n query_binding.sslValidDNs = self.__class__.VALID_DNS\n \n response = query_binding.send(attribute_query, \n uri=self.__class__.SERVICE_URI)\n \n # Convert back to ElementTree instance read for string output\n samlResponseElem = ResponseElementTree.toXML(response)\n \n print(\"SAML Response ...\")\n print(ElementTree.tostring(samlResponseElem))\n print(\"Pretty print SAML Response ...\")\n print(prettyPrint(samlResponseElem))\n \n self.assert_(response.status.statusCode.value==StatusCode.SUCCESS_URI)\n \n \nif __name__ == \"__main__\":\n if paste_installed:\n unittest.main()\n else:\n import warnings\n warnings.warn('Skip unittests for %r, Paste package is not installed' %\n __name__)\n","sub_path":"ndg/saml/test/binding/soap/test_attributeservice_paster.py","file_name":"test_attributeservice_paster.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"560984084","text":"from .client import Client\nfrom .response import Message\nfrom .util import distribute\nfrom . import logger\n\n\nclass Reader(Client):\n '''A client meant exclusively for reading'''\n def __init__(self, topic, channel, lookupd_http_addresses=None,\n nsqd_tcp_addresses=None, max_in_flight=200):\n self._channel = channel\n self._max_in_flight = max_in_flight\n Client.__init__(self, lookupd_http_addresses, nsqd_tcp_addresses, topic)\n\n def add(self, connection):\n '''Add this connection and manipulate its RDY state'''\n conn = Client.add(self, connection)\n if conn:\n conn.sub(self._topic, self._channel)\n conn.rdy(1)\n\n def distribute_ready(self):\n '''Distribute the ready state across all of the connections'''\n connections = [c for c in self.connections() if c.alive()]\n if len(connections) > self._max_in_flight:\n raise NotImplementedError(\n 'Max in flight must be greater than number of connections')\n else:\n # Distribute the ready count evenly among the connections\n for count, conn in distribute(self._max_in_flight, connections):\n logger.info('Sending RDY %i to %s', count, conn)\n conn.rdy(count)\n\n def needs_distribute_ready(self):\n '''Determine whether or not we need to redistribute the ready state'''\n # Determine whether or not we need to redistribute the ready state. For\n # now, we'll just to the simple thing and say that if any of the\n # conections has a ready state of 0\n alive = [c for c in self.connections()]\n # It can happen that a connection receives more messages than we might\n # believe its RDY state to be. Consider the case where we send one RDY\n # status, messages are sent back but before we consume them, we send a\n # second RDY status. In this case, the RDY count might be decremented\n # below 0.\n if min([c.ready for c in alive]) <= 0:\n return True\n\n def close_connection(self, connection):\n '''A hook into when connections are closed'''\n Client.close_connection(self, connection)\n self.distribute_ready()\n\n def read(self):\n '''Read some number of messages'''\n found = Client.read(self)\n\n # Redistribute our ready state if necessary\n if self.needs_distribute_ready():\n self.distribute_ready()\n\n # Finally, return all the results we've read\n return found\n\n def __iter__(self):\n while True:\n for message in self.read():\n # A reader's only interested in actual messages\n if isinstance(message, Message):\n # We'll probably add a hook in here to track the RDY states\n # of our connections\n yield message\n","sub_path":"nsq/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"615860307","text":"#!/usr/bin/python\n\nwords = { \t1: 'one',\n\t\t\t2: 'two',\n\t\t\t3: 'three',\n\t\t\t4: 'four',\n\t\t\t5: 'five',\n\t\t\t6: 'six',\n\t\t\t7: 'seven',\n\t\t\t8: 'eight',\n\t\t\t9: 'nine',\n\t\t\t10: 'ten',\n\t\t\t11: 'eleven',\n\t\t\t12: 'twelve',\n\t\t\t13: 'thirteen',\n\t\t\t14: 'fourteen',\n\t\t\t15: 'fifteen',\n\t\t\t16: 'sixteen',\n\t\t\t17: 'seventeen',\n\t\t\t18: 'eighteen',\n\t\t\t19: 'nineteen',\n\t\t\t20: 'twenty',\n\t\t\t30: 'thirty',\n\t\t\t40: 'forty',\n\t\t\t50: 'fifty',\n\t\t\t60: 'sixty',\n\t\t\t70: 'seventy',\n\t\t\t80: 'eighty',\n\t\t\t90: 'ninety',\n\t\t\t100: 'hundred',\n\t\t\t1000: 'one thousand' }\n\ntotalchars = 0\n\n\nfor x in range(1001):\n\tcurnum = x\n\tcurrentword = \"\"\n\tif curnum / 100 > 0 and curnum != 1000:\n\t\tcurrentword = words[curnum / 100] + \" \" + words[ 100 ]\n\t\tcurnum %= 100\n\t\tif curnum > 0:\n\t\t\tcurrentword += \" and \"\n\tif curnum / 10 > 0 and curnum != 1000 and curnum > 19:\n\t\tcurrentword += words[(curnum/10)*10]\n\t\tcurnum %= 10\n\tif curnum > 0:\n\t\tcurrentword += words[curnum]\n\tprint(currentword)\n\ttotalchars += len(currentword) - currentword.count(' ')\n\t\nprint(totalchars)","sub_path":"problem17.py","file_name":"problem17.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"519944369","text":"# coding: utf-8\n\nfrom .utils import _convert_int_to_float\n\ndef _element_vector_name(i):\n return 'vec_{i}'.format(i=i)\n\ndef _global_vector_name(i):\n return 'rhs_{i}'.format(i=i)\n\ndef construct_element_vector_names(n_rows):\n vec_args = []\n for i in range(0, n_rows):\n vec = _element_vector_name(i)\n vec_args.append(vec)\n\n return vec_args\n\ndef print_element_vector_args(n_rows, vec_args):\n vec_args_str = ', '.join(vec for vec in vec_args)\n return vec_args_str\n\ndef print_element_vector_init(n_rows, vec_args, size, tab):\n slices = ','.join(':' for i in range(0, size))\n\n lines = []\n for i in range(0, n_rows):\n vec = vec_args[i]\n\n line = '{vec}[{slices}] = 0.0'.format(vec=vec,slices=slices)\n line = tab + line\n\n lines.append(line)\n\n vec_init_str = '\\n'.join(line for line in lines)\n return vec_init_str\n\ndef print_accumulation_var_init(n_rows, tab):\n lines = []\n for i in range(0, n_rows):\n line = 'v_{i} = 0.0'.format(i=i)\n line = tab + line\n\n lines.append(line)\n\n accum_init_str = '\\n'.join(line for line in lines)\n return accum_init_str\n\ndef print_accumulation_var(n_rows, expr, tab):\n lines = []\n for i in range(0, n_rows):\n line = 'v_{i} += ({__WEAK_FORM__}) * wvol'\n e = _convert_int_to_float(expr[i].evalf())\n # we call evalf to avoid having fortran doing the evaluation of rational\n # division\n line = line.format(i=i, __WEAK_FORM__=e)\n line = tab + line\n\n lines.append(line)\n\n accum_str = '\\n'.join(line for line in lines)\n return accum_str\n\ndef print_bilinear_accumulation_assign(n_rows, dim, tab):\n if dim == 1:\n e_pattern = 'vec_{i}[il_1] = v_{i}'\n\n elif dim == 2:\n e_pattern = 'vec_{i}[il_1, il_2] = v_{i}'\n\n elif dim ==3:\n e_pattern = 'vec_{i}[il_1, il_2, il_3] = v_{i}'\n\n else:\n raise NotImplementedError('only 1d, 2d and 3d are available')\n\n lines = []\n for i in range(0, n_rows):\n line = e_pattern.format(i=i)\n line = tab + line\n\n lines.append(line)\n\n accum_assign_str = '\\n'.join(line for line in lines)\n return accum_assign_str\n\ndef print_linear_accumulation_assign(n_rows, dim, tab):\n if dim == 1:\n e_pattern = 'vec_{i}[il_1] = v_{i}'\n\n elif dim == 2:\n e_pattern = 'vec_{i}[il_1, il_2] = v_{i}'\n\n elif dim ==3:\n e_pattern = 'vec_{i}[il_1, il_2, il_3] = v_{i}'\n\n else:\n raise NotImplementedError('only 1d, 2d and 3d are available')\n\n lines = []\n for i in range(0, n_rows):\n line = e_pattern.format(i=i)\n line = tab + line\n\n lines.append(line)\n\n accum_assign_str = '\\n'.join(line for line in lines)\n return accum_assign_str\n\n# TODO use space degrees\ndef print_element_vector_decs(n_rows, dim, vec_args, tab):\n if dim == 1:\n pattern = 'zeros( test_p1+1 )'\n\n elif dim == 2:\n pattern = 'zeros( (test_p1+1, test_p2+1) )'\n\n elif dim == 3:\n pattern = 'zeros( (test_p1+1, test_p2+1, test_p3+1) )'\n\n else:\n raise NotImplementedError('only 1d, 2d and 3d are available')\n\n lines = []\n for i in range(0, n_rows):\n vec = vec_args[i]\n line = '{vec} = {pattern}'.format(vec=vec, pattern=pattern)\n line = tab + line\n lines.append(line)\n\n decs = '\\n'.join(i for i in lines)\n return decs\n\ndef construct_global_vector_names(n_rows):\n vec_args = []\n for i in range(0, n_rows):\n vec = _global_vector_name(i)\n vec_args.append(vec)\n\n return vec_args\n\ndef print_global_vector_args(n_rows, vec_args):\n vec_args_str = ', '.join(vec for vec in vec_args)\n return vec_args_str\n\n# TODO use spaces\ndef print_global_vector_decs(n_rows, vec_args):\n pattern = 'StencilVector( test_space.vector_space )'\n\n lines = []\n for i in range(0, n_rows):\n vec = vec_args[i]\n line = '{vec} = {pattern}'.format(vec=vec, pattern=pattern)\n lines.append(line)\n\n decs = '\\n'.join(i for i in lines)\n return decs\n\n# TODO use spaces\ndef print_global_vector_update(n_rows, dim,\n element_vec_args,\n global_vec_args, tab):\n\n lslices = ','.join(':' for i in range(0, dim))\n\n lines = []\n for i in range(0, n_rows):\n lvec = element_vec_args[i]\n gvec = global_vec_args[i]\n\n # ... every vector should have access to its corresponding space and\n # degrees\n if dim == 1:\n gslices = 'is1-test_p1:is1+1'\n\n elif dim == 2:\n gslices = 'is1-test_p1:is1+1, is2-test_p2:is2+1'\n\n elif dim == 3:\n gslices = 'is1-test_p1:is1+1, is2-test_p2:is2+1, is3-test_p3:is3+1'\n # ...\n\n line = '{gvec}[{gslices}] += {lvec}[{lslices}]'.format(lvec=lvec,\n gvec=gvec,\n lslices=lslices,\n gslices=gslices)\n line = tab + line\n lines.append(line)\n\n decs = '\\n'.join(i for i in lines)\n return decs\n\ndef construct_argument_vector_name(n_rows):\n if (n_rows == 1):\n return _global_vector_name(0)\n else:\n return 'd_vector'\n\ndef print_argument_vector_kwargs(argument_mat):\n return ', {}=None'.format(argument_mat)\n\ndef print_import_stencil_vector():\n return 'from spl.linalg.stencil import StencilVector'\n\ndef print_set_dict_vector(n_rows, argument_vec, vec_args):\n if n_rows == 1:\n return ''\n\n lines = [argument_vec + ' = {}']\n for i in range(0, n_rows):\n M = _global_vector_name(i)\n line = '{d}[{i}] = {M}'.format(d=argument_vec, i=i, M=M)\n lines.append(line)\n\n return '\\n'.join(i for i in lines)\n\ndef print_get_dict_vector(n_rows, argument_vec, vec_args):\n if n_rows == 1:\n return ''\n\n lines = []\n for i in range(0, n_rows):\n M = _global_vector_name(i)\n line = '{M} = {d}[{i}]'.format(d=argument_vec, i=i, M=M)\n lines.append(line)\n\n return '\\n'.join(i for i in lines)\n\n_template_define_global_vector = \"\"\"\nif {__ARGUMENT_VEC__} is None:\n{__IMPORT_STENCIL__}\n{__DECS__}\n{__SET_DICT__}\n{__ELSE__}\n{__GET_DICT__}\n\"\"\"\n# TODO add comment to the generated code\ndef print_define_global_vector(n_rows, global_vec_args, argument_vec, tab):\n # ...\n def _indent_block(txt):\n indent = ' '*4\n\n lines = []\n for line in txt.split('\\n'):\n line = indent + line\n lines.append(line)\n\n return '\\n'.join(line for line in lines)\n # ...\n\n # ...\n global_vec_decs_str = print_global_vector_decs(n_rows, global_vec_args)\n global_vec_decs_str = _indent_block( global_vec_decs_str )\n # ...\n\n # ...\n import_str = print_import_stencil_vector()\n import_str = _indent_block( import_str )\n # ...\n\n # ...\n set_dict_str = print_set_dict_vector(n_rows, argument_vec, global_vec_args)\n set_dict_str = _indent_block( set_dict_str )\n # ...\n\n # ...\n get_dict_str = print_get_dict_vector(n_rows, argument_vec, global_vec_args)\n get_dict_str = _indent_block( get_dict_str )\n # ...\n\n # ...\n if n_rows == 1:\n else_str = ''\n else:\n else_str = 'else:'\n # ...\n\n pattern = _template_define_global_vector\n code = pattern.format(__ARGUMENT_VEC__=argument_vec,\n __IMPORT_STENCIL__=import_str,\n __DECS__=global_vec_decs_str,\n __SET_DICT__=set_dict_str,\n __GET_DICT__=get_dict_str,\n __ELSE__=else_str)\n\n lines = []\n for line in code.split('\\n'):\n line = tab + line\n lines.append(line)\n\n code = '\\n'.join(line for line in lines)\n\n return code\n","sub_path":"symfe/codegen/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":7840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"535979220","text":"#!/usr/bin/env python\n\"\"\" Simple examples of calling C functions through ctypes module. \"\"\"\nimport ctypes\nfrom ctypes import Structure, c_char_p, c_int, c_float, c_double, byref, POINTER\nimport sys\nimport os\n\nclass MyStruct(Structure):\n _fields_ =[(\"name\",c_char_p),\n (\"age\",c_int),\n (\"mark\",c_double)\n ]\n\n# Load the shared library into C types.\nif __name__ == \"__main__\":\n if sys.platform.startswith(\"win\"):\n c_lib = ctypes.CDLL(\"functions.dll\")\n else:\n cur_path = os.getcwd()\n lib_path = os.path.join (cur_path, \"libfunctions.so\")\n c_lib = ctypes.CDLL(lib_path)\n\n print(\"=================================\")\n\n # Sample data\n x, y = 5, 3.3\n\n # You need tell ctypes that the function returns a float (if the function return is different than integer)\n c_lib.cmult.restype = c_float\n\n # Example of numeric functions\n r1 = c_lib.cmult(x, c_float(y))\n r2 = c_lib.csum(2,5)\n print(\"Python program : variable r2 contains result from csum\", r2)\n\n print(\"\\n=================================\")\n\n # Example of array type function\n a = (c_int * 3) (-1, 2 , 5)\n f_arr = c_lib.cfun_array\n f_arr.restype = POINTER(c_int * 3)\n print(\"Python program : previous array: \", [i for i in a])\n print (\"Python program : new array: \", [i for i in f_arr(a).contents])\n\n print(\"\\n=================================\")\n\n # Example of struct type function\n st = MyStruct(c_char_p(b\"Manolo\"), 37, 6.8)\n result = c_lib.comprobar_num\n\n #Sending and receiving pointers\n result.restype = POINTER(MyStruct)\n output = result(byref(st))\n \n # Getting content from pointer\n final_output = output.contents\n print(\"Python program : \", final_output.name.decode(), \", \", final_output.age, \", \", final_output.mark)\n\n print(\"\\n=================================\")\n","sub_path":"ctypes_test.py","file_name":"ctypes_test.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"147488292","text":"# Mary McHale, 14th April 2018\r\n# Project based on Iris Data, Working out the Max\r\n\r\nf = open('data/iris.csv' , 'r')\r\n# This opens the file called iris.csv\r\nprint(\"Max values are below\")\r\nprint(\" pl pw sl sw\")\r\n# pl = short for Petal length\r\n# pw = short for Petal width\r\n# sl = short for Sepal length\r\n# sw = short for Sepal width\r\n\r\nc = 0\r\n# sets the record counter to zero at beginning\r\nmaxsofarpl = 0\r\nmaxsofarpw = 0\r\nmaxsofarsl = 0\r\nmaxsofarsw = 0\r\n\r\n# maximum values so far in the dataset\r\nrecord = \"\"\r\nwhile c < 100000:\r\n record = f.readline()\r\n if record == \"\":\r\n\r\n #print(\"count = \",c)\r\n #this was a test to ensure that the total of c was in fact 150, otherwise the results of the mean could be wrong\r\n temp1 = format(maxsofarpl, ' .1f')\r\n temp2 = format(maxsofarpw, ' .1f')\r\n temp3 = format(maxsofarsl, ' .1f')\r\n temp4 = format(maxsofarsw, ' .1f')\r\n print (temp1, temp2, temp3, temp4)\r\n \r\n f.close()\r\n quit()\r\n\r\n # Working out the number of characters across each row to put the data into columns\r\n petallength = (record[0:3])\r\n petalwidth = (record[4:7])\r\n sepallength = (record[8:11])\r\n sepalwidth = (record[12:15])\r\n name = (record[16:30])\r\n \r\n petallength = float(petallength) \r\n petalwidth = float(petalwidth)\r\n sepallength = float(sepallength)\r\n sepalwidth = float(sepalwidth)\r\n #float is a python function to change a string variable into a decimal number for adding purposes\r\n \r\n if petallength > maxsofarpl:\r\n maxsofarpl = petallength\r\n if petalwidth > maxsofarpw:\r\n maxsofarpw = petalwidth\r\n if sepallength > maxsofarsl:\r\n maxsofarsl = sepallength \r\n if sepalwidth > maxsofarsw:\r\n maxsofarsw = sepalwidth \r\n #print(petallength, petalwidth, sepallength, sepalwidth)\r\n record = \"\"\r\n c = c + 1","sub_path":"Max.py","file_name":"Max.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"280086927","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport ujson\nimport random\nfrom pathlib import Path\nfrom enum import IntEnum\nfrom loguru import logger\n\n\nclass Dictionary(object):\n __phrases = []\n __names = []\n __surnames = []\n __places = []\n __ue_places = []\n __ue_vip = []\n __dictionaries = []\n\n def __init__(self):\n\n try:\n with codecs.open(Path('dictionaries/phrases.json'), encoding='utf8') as data_file:\n self.__phrases = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__phrases,\n \"path\": Path('dictionaries/phrases.json')\n })\n logger.debug('phrases.json loaded')\n\n # Load first\n with codecs.open(Path('dictionaries/names.json'), encoding='utf8') as data_file:\n self.__names = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__names,\n \"path\": Path('dictionaries/names.json')\n })\n logger.debug('names.json loaded')\n\n # Load surnames\n with codecs.open(Path('dictionaries/surnames.json'), encoding='utf8') as data_file:\n self.__surnames = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__surnames,\n \"path\": Path('dictionaries/surnames.json')\n })\n logger.debug('surnames.json loaded')\n\n # Load place\n with codecs.open(Path('dictionaries/places.json'), encoding='utf8') as data_file:\n self.__places = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__places,\n \"path\": Path('dictionaries/places.json')\n })\n logger.debug('places.json loaded')\n\n # Load users_entries_places\n with codecs.open(Path('dictionaries/ue_places.json'), encoding='utf8') as data_file:\n self.__ue_places = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__ue_places,\n \"path\": Path('dictionaries/ue_places.json')\n })\n logger.debug('ue_places.json loaded')\n\n # Load users_entries_vip\n with codecs.open(Path('dictionaries/ue_vip.json'), encoding='utf8') as data_file:\n self.__ue_vip = ujson.load(data_file)\n self.__dictionaries.append({\n \"data\": self.__ue_vip,\n \"path\": Path('dictionaries/ue_vip.json')\n })\n logger.debug('ue_vip.json loaded')\n\n except OSError or ValueError as err:\n raise DictionaryErrors.OpeningError(err)\n\n if len(self.__phrases) == 0 or len(self.__names) == 0 or len(self.__surnames) == 0 or len(self.__places) == 0:\n raise DictionaryErrors.EmptyDictionaryError\n\n logger.info('Dictionary class initialized')\n\n def random_phrase(self):\n phrase = random.choice(self.__phrases)\n return self.replace(phrase)\n\n def random_name(self):\n if len(self.__ue_vip) > 0 and random.random() < 0.5:\n name = random.choice(self.__ue_vip)\n else:\n name = random.choice(self.__names) + (' ' + random.choice(self.__surnames) if random.random() < 0.5 else '')\n return name\n\n def random_place(self):\n if len(self.__ue_places) > 0 and random.random() < 0.5:\n name = random.choice(self.__ue_places)\n else:\n name = random.choice(self.__places)\n return name\n\n def replace(self, string):\n while string.count('{name}') > 0:\n string = string.replace('{name}', self.random_name(), 1)\n while string.count('{place}') > 0:\n string = string.replace('{place}', self.random_place(), 1)\n return string\n\n def add_entity(self, entity_type, entity_text):\n if entity_type == DictionaryID.PHRASES:\n self.__phrases.append(entity_text)\n elif entity_type == DictionaryID.UE_PLACES:\n self.__ue_places.append(entity_text)\n elif entity_type == DictionaryID.UE_VIP:\n self.__ue_vip.append(entity_text)\n else:\n return DictionaryErrors.DictionaryIDError('Wrong ID, read-only dictionary')\n self.save_dictionary(entity_type)\n\n def save_dictionary(self, dictionary_id):\n if DictionaryID.read_only(dictionary_id):\n raise DictionaryErrors.DictionaryIDError('Invalid ID {}'.format(dictionary_id))\n\n try:\n with codecs.open(self.__dictionaries[dictionary_id]['path'], 'w', encoding='utf-8') as outfile:\n ujson.dump(self.__dictionaries[dictionary_id]['data'], outfile, indent=2, ensure_ascii=False)\n except OSError or ValueError as err:\n raise DictionaryErrors.OpeningError(err)\n\n\nclass DictionaryID(IntEnum):\n __length = 6\n PHRASES, NAMES, SURNAMES, PLACES, UE_PLACES, UE_VIP = range(__length)\n\n @classmethod\n def length(cls):\n return cls.__length.value\n\n @classmethod\n def contains(cls, _id):\n return any(_id == item.value for item in cls)\n\n @classmethod\n def read_only(cls, _id):\n return False if _id in (cls.PHRASES, cls.UE_PLACES, cls.UE_VIP) else True\n\n @classmethod\n def max(cls):\n return cls.__length.value - 1\n\n\nclass DictionaryErrors(Exception):\n class DictionaryError(Exception):\n def __init__(self, message=None):\n if message:\n super().__init__(message)\n else:\n super().__init__()\n\n class OpeningError(DictionaryError):\n pass\n\n class EmptyDictionaryError(DictionaryError):\n pass\n\n class DictionaryIDError(DictionaryError):\n pass\n","sub_path":"dictionaries/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"515126792","text":"####################################\n# 1. package import\nfrom flask import Flask, render_template, g, request, session, flash, redirect, url_for\nimport pandas as pd\nimport pymysql\nimport re\n####################################\n\n\n####################################\n# 2. config\nDEBUG = True\nUSERNAME = \"admin\"\nPASSWORD = \"888\"\nSECRET_KEY = \"development key~~\"\n####################################\n\n\n####################################\n# 3. initialize\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nkDbName = \"db_for_test\"\nkInitTableName = \"coupang_product_table\"\nkTableNameForSelectedDatas = \"selected_datas_table_revised\"\nkPathToCsv = \\\n \"\"\"\n ../../data/backup_dry_tissue_page8.csv\n \"\"\".strip()\n\n\ndef create_table(table_name):\n create_sql = \\\n \"\"\"\n CREATE TABLE {} (\n id INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT,\n code varchar(20),\n name varchar(200),\n brand_name varchar(20),\n hash_tag varchar(20),\n star varchar(20),\n star_count varchar(20),\n weight varchar(50),\n ml varchar(300),\n product_count varchar(50),\n price varchar(50),\n date varchar(30),\n flag varchar(20),\n ingredient_name varchar(200),\n view varchar(20),\n product_img_path varchar(200),\n product_detail_img_paths varchar(5000),\n product_url varchar(200)\n );\n \"\"\".format(table_name)\n with g.db.cursor() as cursor:\n cursor.execute(create_sql)\n g.db.commit()\n\n\ndef get_insert_sql(table_name):\n result = \\\n \"\"\"\n INSERT INTO {} (id, code, name, brand_name, hash_tag, star, star_count, weight, ml, product_count, price, date, flag, ingredient_name, view, product_img_path, product_detail_img_paths, product_url)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\n \"\"\".format(table_name)\n return result\n\n\ndef connect_db():\n return pymysql.connect(host='localhost',\n db=kDbName,\n user='root',\n password='babylab123',\n port=3306,\n charset='utf8')\n\n\ndef init_db():\n with connect_db() as db:\n with db.cursor() as cursor:\n try:\n create_table(kInitTableName)\n except Exception as e:\n print(str(e))\n finally:\n cursor.execute(\"SELECT * FROM {}\".format(kInitTableName))\n datas_from_db_table = cursor.fetchall()\n\n if not datas_from_db_table:\n df = pd.read_csv(kPathToCsv, index_col=0)\n\n for col in df.columns:\n df[col] = df[col].apply(lambda x: \"\" if str(x) == 'nan' else str(x))\n df[col] = df[col].apply(lambda x: x.replace(\" , \", \",\") if \" , \" in x else x)\n\n df2numpy = df.to_numpy()\n df2numpy2list = []\n for data in df2numpy:\n df2numpy2list.append(data.tolist())\n\n insert_sql = get_insert_sql(kInitTableName)\n cursor.executemany(insert_sql, df2numpy2list)\n db.commit()\n cursor.close()\n####################################\n\n\n####################################\n# 4. before_request & teardown_request\n@app.before_request\ndef before_request():\n # HTTP 요청이 들어올때마다 실행\n g.db = connect_db()\n init_db()\n\n\n@app.teardown_request\ndef teardown_request(exception):\n # HTTP 요청 결과가 브라우저에 응답한 다음 실행\n g.db.close()\n####################################\n\n\n####################################\n# 5. views\n@app.route(\"/\")\ndef init_login():\n # 제일 처음에 뜨는 페이지로 로그인을 먼저 요구한다.\n return render_template(\"login.html\")\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n # 로그인 버튼 클릭시 실행되는 함수.\n error = None\n if request.method == 'POST':\n if request.form['username'] != app.config['USERNAME']:\n error = \"Invalid username!\"\n elif request.form['password'] != app.config['PASSWORD']:\n error = \"Invalid password!\"\n else:\n session['logged_in'] = True\n flash(\"login success\")\n return redirect(url_for(\"show_selectable_elements\"))\n return render_template(\"login.html\", error=error)\n\n\n@app.route(\"/logout\", methods=['POST'])\ndef logout():\n # 로그아웃 버튼 클릭시 실행됨.\n session.pop(\"logged_in\", None)\n flash(\"logged out!\")\n return redirect(url_for(\"login\"))\n\n\n@app.route(\"/main\", methods=['GET', 'POST'])\ndef show_selectable_elements():\n # 선택할 수 있는 데이터를 띄워줌.\n datas = None\n with g.db.cursor() as cursor:\n cursor.execute(\"SELECT id, name, date FROM {};\".format(kInitTableName))\n datas = cursor.fetchall()\n cursor.close()\n return render_template('show_selectable_elements.html', datas=datas)\n\n\n@app.route(\"/main/revise\", methods=['GET'])\ndef show_revising_element_from_main():\n # 수정 중인 데이터를 띄워줌. (데이터는 main 에서 나온 경우)\n full_path = request.full_path\n before_parsing_id = re.compile(\"id=[0-9]+\").search(full_path).group()\n after_parsing_id = before_parsing_id.split(\"=\")[-1]\n\n select_sql = \\\n \"\"\"\n SELECT * FROM {}\n WHERE id = {};\n \"\"\".format(kInitTableName, after_parsing_id).strip()\n\n selected_data = None\n with g.db.cursor(pymysql.cursors.DictCursor) as cursor:\n cursor.execute(select_sql)\n selected_data = cursor.fetchone()\n\n return render_template(\"show_revising_data.html\", datas=selected_data)\n\n\n@app.route(\"/already_revised/revise\", methods=['GET'])\ndef show_revising_element_from_already_revised():\n # 수정 중인 데이터를 띄워줌. (데이터는 already_revised 에서 나온 경우)\n full_path = request.full_path\n before_parsing_id = re.compile(\"id=[0-9]+\").search(full_path).group()\n after_parsing_id = before_parsing_id.split(\"=\")[-1]\n\n select_sql = \\\n \"\"\"\n SELECT * FROM {}\n WHERE id = {};\n \"\"\".format(kTableNameForSelectedDatas, after_parsing_id).strip()\n\n selected_data = None\n with g.db.cursor(pymysql.cursors.DictCursor) as cursor:\n cursor.execute(select_sql)\n selected_data = cursor.fetchone()\n\n return render_template(\"show_revising_data.html\", datas=selected_data)\n\n\n@app.route(\"/main/revising\", methods=['POST'])\n@app.route(\"/already_revised/revising\", methods=['POST'])\ndef revising():\n # 수정 완료 버튼 클릭시 실행되는 함수\n revised_product_detail_paths = request.form.getlist(\"revised_product_detail_paths\")\n revised_product_detail_path = ','.join(revised_product_detail_paths)\n\n revised_data_without_product_detail_paths = request.form.getlist(\"revised_element\")\n revised_data = revised_data_without_product_detail_paths[:]\n for idx, element in enumerate(revised_data_without_product_detail_paths):\n if \"/product_detail/\" in element:\n revised_data[idx] = revised_product_detail_path\n break\n\n id = revised_data[0]\n insert_sql = get_insert_sql(kTableNameForSelectedDatas)\n\n try:\n create_table(kTableNameForSelectedDatas)\n finally:\n with g.db.cursor() as cursor:\n delete_sql = \\\n \"\"\"\n DELETE FROM {} WHERE id = {};\n \"\"\".format(kTableNameForSelectedDatas, id).strip()\n cursor.execute(delete_sql)\n cursor.execute(insert_sql, revised_data)\n\n g.db.commit()\n cursor.close()\n return redirect(url_for(\"already_revised\"))\n\n\n@app.route(\"/already_revised\", methods=['GET', 'POST'])\ndef already_revised():\n # 선택, 수정된 데이터만을 모아서 모두 띄워준다.\n try:\n create_table(kTableNameForSelectedDatas)\n finally:\n showing_datas = None\n with g.db.cursor(pymysql.cursors.DictCursor) as cursor:\n select_sql = \\\n \"\"\"\n SELECT id, name, price, date, ingredient_name FROM {}\n \"\"\".format(kTableNameForSelectedDatas).strip()\n cursor.execute(select_sql)\n showing_datas = cursor.fetchall()\n return render_template(\"show_revised_data.html\", datas=showing_datas)\n\n\n@app.route(\"/main/just_view\", methods=['GET'])\ndef just_view_for_init():\n # 데이터의 이름을 클릭했을때,\n full_path = request.full_path\n print(full_path)\n id = re.compile(\"id=[0-9]+\").search(full_path).group().split(\"=\")[-1]\n\n selected_sql = \\\n \"\"\"\n SELECT * FROM {}\n WHERE id = {}\n \"\"\".format(kInitTableName, id)\n\n selected_data = None\n with g.db.cursor(pymysql.cursors.DictCursor) as cursor:\n cursor.execute(selected_sql)\n selected_data = cursor.fetchone()\n return render_template('just_view_for_selected_data.html', datas=selected_data)\n\n\n@app.route(\"/already_revised/just_view\", methods=['GET'])\ndef just_view_for_selected():\n full_path = request.full_path\n id = re.compile(\"id=[0-9]+\").search(full_path).group().split(\"=\")[-1]\n select_sql = \\\n \"\"\"\n SELECT * FROM {}\n WHERE id = {}\n \"\"\".format(kTableNameForSelectedDatas, id)\n\n selected_data = None\n with g.db.cursor(pymysql.cursors.DictCursor) as cursor:\n cursor.execute(select_sql)\n selected_data = cursor.fetchone()\n return render_template('just_view_for_selected_data.html', datas=selected_data)\n\n\n@app.route(\"/delete_data\", methods=['GET', 'POST'])\ndef delete_data():\n delete_data_id = request.form.get(\"deleted_data_id\")\n\n delete_sql = \\\n \"\"\"\n DELETE FROM {}\n WHERE id = {}\n \"\"\".format(kTableNameForSelectedDatas, delete_data_id)\n\n with g.db.cursor() as cursor:\n cursor.execute(delete_sql)\n g.db.commit()\n\n return redirect(url_for(\"already_revised\"))\n####################################\n\n\n####################################\n# 6. template_filter\n@app.template_filter(\"is_name\")\ndef is_name(any_element):\n try:\n int(any_element)\n return False\n except:\n try:\n int(any_element[:4])\n return False\n except:\n return True\n\n\n@app.template_filter(\"to_string\")\ndef to_string(any_element):\n return str(any_element)\n\n\n@app.template_filter(\"split_by_comma\")\ndef split_by_comma(img_paths):\n return img_paths.split(\",\")\n\n\n@app.template_filter(\"is_empty\")\ndef is_empty(a_list):\n return False if a_list else True\n####################################\n\n\nif __name__ == '__main__':\n app.run()\n\n","sub_path":"toy_project_product_manage_with_flask/tutorial/5_coupang_imgs/5_main.py","file_name":"5_main.py","file_ext":"py","file_size_in_byte":10766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"550163849","text":"import threading\nfrom queue import Queue\n\nclass threadingOperation:\n dest=False #holds a pointer to function to be multithreaded.\n thCount=1 #specifies number of threads to be created\n myQueue=False\n results=[] #holds results of threading\n outputType=\"\" #stores type of results, could be list or dict\n def __init__(self,*args):\n if len(args)<2:\n raise ValueError\n destFunc=args[0]\n thCount=args[1]\n self.dest=destFunc\n self.thCount=thCount\n if len(args)>2:\n if args[2]==\"list\":\n self.outputType=\"list\"\n if args[2]==\"dict\":\n self.outputType=\"dict\"\n def worker(self): #one worker per thread, each one will work until all tasks done, then dies\n if self.outputType==\"\":\n while True:\n self.dest( self.myQueue.get() ) #passes task to multied function\n self.myQueue.task_done() #signals to queue that particular task is finished\n elif self.outputType==\"list\":\n while True:\n self.results.append( self.dest( self.myQueue.get() ) ) #passes task to multied function\n self.myQueue.task_done() #signals to queue that particular task is finished\n elif self.outputType==\"dict\":\n while True:\n key=self.myQueue.get()\n self.results[key]=self.dest( key ) #passes task to multied function\n self.myQueue.task_done() #signals to queue that particular task is finished\n def thread(self,taskList):\n #taskList is a list of stuff\n #each element of the list is passed to an instance of the function\n #named in dest\n if self.outputType==\"list\":\n self.results=[]\n elif self.outputType==\"dict\":\n self.results=dict()\n self.myQueue=Queue() #make queue\n for i in range(self.thCount):\n t=threading.Thread(target=self.worker)\n t.daemon=True\n t.start()\n for x in taskList:\n self.myQueue.put(x)\n self.myQueue.join()\n if self.outputType!=\"\":\n return self.results\n","sub_path":"current/easyMultiThread.py","file_name":"easyMultiThread.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"73698019","text":"#!/usr/bin/python3\nimport sys\n\nsave = __import__('7-save_to_json_file').save_to_json_file\nload = __import__('8-load_from_json_file').load_from_json_file\n\n\n\"\"\" Adds all arguments to a Python list, and then save them to a file \"\"\"\ntry:\n list = load(\"add_item.json\")\nexcept Exception:\n list = []\n\nfor i in sys.argv[1:]:\n list.append(i)\n\nsave(list, \"add_item.json\")\n","sub_path":"0x0B-python-input_output/9-add_item.py","file_name":"9-add_item.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"211258158","text":"import json\nimport logging\nimport os\nimport subprocess\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# these are coming from the kubectl layer\nos.environ['PATH'] = '/opt/kubectl:/opt/awscli:' + os.environ['PATH']\n\noutdir = os.environ.get('TEST_OUTDIR', '/tmp')\nkubeconfig = os.path.join(outdir, 'kubeconfig')\n\n\ndef apply_handler(event, context):\n logger.info(json.dumps(dict(event, ResponseURL='...')))\n\n request_type = event['RequestType']\n props = event['ResourceProperties']\n\n # resource properties (all required)\n cluster_name = props['ClusterName']\n manifest_text = props['Manifest']\n role_arn = props['RoleArn']\n prune_label = props.get('PruneLabel', None)\n overwrite = props.get('Overwrite', 'false').lower() == 'true'\n skip_validation = props.get('SkipValidation', 'false').lower() == 'true'\n\n # \"log in\" to the cluster\n cmd = [ 'aws', 'eks', 'update-kubeconfig',\n '--role-arn', role_arn,\n '--name', cluster_name,\n '--kubeconfig', kubeconfig\n ]\n logger.info(f'Running command: {cmd}')\n subprocess.check_call(cmd)\n\n if os.path.isfile(kubeconfig):\n os.chmod(kubeconfig, 0o600)\n\n # write resource manifests in sequence: { r1 }{ r2 }{ r3 } (this is how\n # a stream of JSON objects can be included in a k8s manifest).\n manifest_list = json.loads(manifest_text)\n manifest_file = os.path.join(outdir, 'manifest.yaml')\n with open(manifest_file, \"w\") as f:\n f.writelines(map(lambda obj: json.dumps(obj), manifest_list))\n\n logger.info(\"manifest written to: %s\" % manifest_file)\n\n kubectl_opts = []\n if skip_validation:\n kubectl_opts.extend(['--validate=false'])\n\n if request_type == 'Create':\n # if \"overwrite\" is enabled, then we use \"apply\" for CREATE operations\n # which technically means we can determine the desired state of an\n # existing resource.\n if overwrite:\n kubectl('apply', manifest_file, *kubectl_opts)\n else:\n # --save-config will allow us to use \"apply\" later\n kubectl_opts.extend(['--save-config'])\n kubectl('create', manifest_file, *kubectl_opts)\n elif request_type == 'Update':\n if prune_label is not None:\n kubectl_opts.extend(['--prune', '-l', prune_label])\n\n kubectl('apply', manifest_file, *kubectl_opts)\n elif request_type == \"Delete\":\n try:\n kubectl('delete', manifest_file)\n except Exception as e:\n logger.info(\"delete error: %s\" % e)\n\n\ndef kubectl(verb, file, *opts):\n maxAttempts = 3\n retry = maxAttempts\n while retry > 0:\n try:\n cmd = ['kubectl', verb, '--kubeconfig', kubeconfig, '-f', file] + list(opts)\n logger.info(f'Running command: {cmd}')\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError as exc:\n output = exc.output\n if b'i/o timeout' in output and retry > 0:\n retry = retry - 1\n logger.info(\"kubectl timed out, retries left: %s\" % retry)\n else:\n raise Exception(output)\n else:\n logger.info(output)\n return\n raise Exception(f'Operation failed after {maxAttempts} attempts: {output}')\n","sub_path":"packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/emrcontainers/integ.start-job-run.js.snapshot/asset.9017774b84ae2457b1b2ad6fcbb4860d8ce2537062c77010b24d9b156ced5a1b/apply/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"407691023","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 ('lingua', '0010_auto_20160109_1105'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Device',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('dev_id', models.CharField(unique=True, max_length=50, verbose_name='Device ID')),\n ('reg_id', models.CharField(unique=True, max_length=255, verbose_name='Registration ID')),\n ('email', models.CharField(max_length=255, null=True, verbose_name='Email', blank=True)),\n ('user_type', models.CharField(max_length=255, null=True, verbose_name='User Type', blank=True)),\n ('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='Creation date')),\n ('modified_date', models.DateTimeField(auto_now=True, verbose_name='Modified date')),\n ('is_active', models.BooleanField(default=False, verbose_name='Is active?')),\n ],\n ),\n migrations.AlterField(\n model_name='client',\n name='gender',\n field=models.CharField(default='male', max_length=10, choices=[('male', 'male'), ('female', 'female')]),\n ),\n ]\n","sub_path":"lingua_vista/lingua/migrations/0011_auto_20160109_1745.py","file_name":"0011_auto_20160109_1745.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"649470897","text":"\"\"\"\n 给定一个二叉树,找出其最大深度。\n 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。\n 说明: 叶子节点是指没有子节点的节点。\n\n 示例:\n 给定二叉树 [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\n 返回它的最大深度 3 。\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n return self.iteration(root)\n\n @classmethod\n def recursive(cls, root: TreeNode) -> int:\n if root is None:\n return 0\n left_height = cls.recursive(root.left)\n right_height = cls.recursive(root.right)\n return max(left_height, right_height) + 1\n\n @classmethod\n def iteration(cls, root: TreeNode) -> int:\n depth = 0\n if root:\n stack = [(root, 1)]\n\n while stack:\n node, tmp_depth = stack.pop()\n if node:\n depth = max(depth, tmp_depth)\n stack.append((node.left, tmp_depth+1))\n stack.append((node.right, tmp_depth+1))\n return depth\n","sub_path":"algorithm/LeetCode_104_二叉树的最大深度.py","file_name":"LeetCode_104_二叉树的最大深度.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"194853453","text":"import socket\r\n\r\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\n# Server address and port number, and message to be sent\r\nserver_address = (\"localhost\", 50000)\r\n\r\nmessage = \"I love socket programming in Python!\"\r\nbytes_send = client_socket.sendto(message.encode(\"utf-8\"), server_address)\r\n\r\n# Close the socket\r\nclient_socket.close()\r\n","sub_path":"_site/scripts/udp_simple_client.py","file_name":"udp_simple_client.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"203200844","text":"import numpy as np\r\nimport cv2 as cv\r\n\r\nimg1 = './img1.png'\r\nimg2 = './img2.png'\r\nimg3 = './img3.png'\r\nimg4 = './img4.png'\r\nimg5 = './img5.png'\r\nimg6 = './img6.png'\r\nimg7 = './img7.png'\r\nimg8 = './img8.png'\r\n\r\nmain_read = img7\r\nmain_test = cv.imread('digits.png')\r\n\r\n# img = cv.imread(main_read)\r\nimg = cv.imread('digits.png')\r\n# width = 2500\r\n# height = 400 # keep original height\r\n# dim = (width, height)\r\n#\r\n# # resize image\r\n# img = cv.resize(img, dim, interpolation=cv.INTER_AREA)\r\n\r\n# gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)\r\n# rows = np.vsplit(img, 50)\r\n# cells = []\r\n# for row in rows:\r\n# row_cells = np.hsplit(row, 50)\r\n# for cell in row_cells:\r\n# cell = cell.flatten()\r\n# cells.append(cell)\r\n# cells = np.array(cells, dtype=np.float32)\r\n\r\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n\r\n# Now we split the image to 5000 cells, each 20x20 size\r\ncells = [np.hsplit(row, 100) for row in np.vsplit(gray, 50)]\r\n# Make it into a Numpy array: its size will be (50,100,20,20)\r\nx = np.array(cells)\r\n# Now we prepare the training data and test data\r\ntrain = x[:, :50].reshape(-1, 400).astype(np.float32) # Size = (2500,400)\r\ntest = x[:, 50:100].reshape(-1, 400).astype(np.float32) # Size = (2500,400)\r\n# Create labels for train and test data\r\nk = np.arange(10)\r\ntrain_labels = np.repeat(k, 250)[:, np.newaxis]\r\ntest_labels = train_labels.copy()\r\n# Initiate kNN, train it on the training data, then test it with the test data with k=1\r\nknn = cv.ml.KNearest_create()\r\nknn.train(train, cv.ml.ROW_SAMPLE, train_labels)\r\nret, result, neighbours, dist = knn.findNearest(test, k=5)\r\n# Now we check the accuracy of classification\r\n# For that, compare the result with test_labels and check which are wrong\r\nmatches = result == test_labels\r\ncorrect = np.count_nonzero(matches)\r\naccuracy = correct * 100.0 / result.size\r\nprint('accuracy', accuracy)\r\n# Save the data\r\nnp.savez('knn_data.npz', train=train, train_labels=train_labels)\r\n# Now load the data\r\nwith np.load('knn_data.npz') as data:\r\n print(data.files)\r\n train = data['train']\r\n train_labels = data['train_labels']\r\n\r\nknn = cv.ml.KNearest_create()\r\nknn.train(train, cv.ml.ROW_SAMPLE, train_labels)\r\n\r\ntest_img = cv.imread(main_read)\r\n\r\ntest_img = cv.cvtColor(test_img, cv.COLOR_BGR2GRAY)\r\ntest_img = cv.resize(test_img, (20, 20))\r\nx = np.array(test_img)\r\ntest_img = x.reshape(-1, 400).astype(np.float32)\r\nret, result, neighbours, distance = knn.findNearest(test_img, k=1)\r\n# Print the predicted number\r\nprint('result', result, 'neighbours', neighbours, 'distance', distance)\r\n","sub_path":"OpticalCharacterRecognition/OCRKnn.py","file_name":"OCRKnn.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"346345049","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.2'\n\ntry:\n from mercurial import ui, hg, error\n repo = hg.repository(ui.ui(), \".\")\n ver = repo[version]\nexcept ImportError:\n pass\nexcept error.RepoLookupError:\n tip = repo[\"tip\"]\n version = version + \".%s.%s\" % (tip.rev(), tip.hex()[:12])\nexcept error.RepoError:\n pass\n\nsetup(\n name='unstats_rdf',\n version=version,\n description=\"RDF API for UN Statistical Division Data\",\n long_description=\"\"\"\\\nRDF API for UN Statistical Division Data\"\"\",\n # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Environment :: Web Environment\",\n \"Framework :: Paste\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Information Technology\",\n \"License :: OSI Approved :: GNU Affero General Public License v3\",\n \"Operating System :: POSIX\",\n \"Programming Language :: Python :: 2.6\",\n \"Topic :: Internet\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords=\"unstats rdf\",\n author='Open Knowledge Foundation',\n author_email='okfn-help@lists.okfn.org',\n url=\"http://pypi.python.org/pypi/unstats_rdf_data\",\n license='BSD',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n setup_requires=[\n \"datapkg\",\n ],\n install_requires=[\n \"Paste\",\n \"setuptools\",\n \"ordf\",\n ],\n datapkg_index = \"\"\"\n [cofog99_en]\n title=COFOG 1999 via the EU in XML format (English labels)\n download_url=http://bitbucket.org/ww/unstats_rdf/raw/tip/unstats/data/cofog/COFOG99_EN.xml\n\n [cofog99_fr]\n title=COFOG 1999 via the EU in XML format (French labels)\n download_url=http://bitbucket.org/ww/unstats_rdf/raw/tip/unstats/data/cofog/COFOG99_FR.xml\n\n [cofog99_de]\n title=COFOG 1999 via the EU in XML format (German labels)\n download_url=http://bitbucket.org/ww/unstats_rdf/raw/tip/unstats/data/cofog/COFOG99_DE.xml\n \"\"\",\n entry_points = \"\"\"\n \"\"\",\n)\n","sub_path":"pypi_install_script/unstats_rdf-0.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"101612398","text":"#!/usr/bin/env python\n\nfrom socket import *\nfrom addressbook_pb2 import *\nimport time\n\nsock = socket( AF_INET, SOCK_DGRAM )\n\nmsg = AddressBook()\nperson = msg.person.add()\nperson.name = 'J Doe'\nperson.id = 12345\nperson.email = 'j@doe.net'\nphone = person.phone.add()\nphone.number = '123-456-7890'\nphone.type = 0\nphone = person.phone.add()\nphone.number = '111-111-1111'\nphone.type = 1\n\nrunning = True\n\nwhile running:\n try:\n sock.sendto( msg.SerializeToString(), (\"233.0.0.1\",33445) )\n time.sleep( 10 )\n except KeyboardInterrupt:\n running = False\n continue\n \n \n","sub_path":"runtime/addressbook_test.py","file_name":"addressbook_test.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"386122351","text":"import numpy as np\r\nimport pylab as pl\r\nimport math\r\n\r\ndots = 1000000\r\n# Make an array of x values\r\n\r\nlow = 1.0\r\nhigh = 9.0\r\n\r\nstep = (high-low)/dots\r\n\r\nx = np.arange(low+step, high, step)\r\n\r\nc = 1.0\r\n# Make an array of y values for each x value\r\ny1 = [math.sqrt(16.0 - math.pow(i-5.0, 2)) + 5.0 for i in x]\r\ny2 = [-1.0*math.sqrt(16.0 - math.pow(i-5.0, 2)) + 5.0 for i in x]\r\n#y = y1+y2\r\n\r\n#x = [i for i in x for _ in range(2)]\r\n#print(len(x), \" \", len(y))\r\n# use pylab to plot x and y\r\npl.plot(x, y1, 'r+')\r\npl.plot(x, y2, 'r+')\r\n# give plot a title\r\npl.title('Plot of y vs. x')\r\n# make axis labels\r\npl.xlabel('x axis')\r\npl.ylabel('y axis')\r\n# set axis limits\r\n#pl.xlim(0.0, 0.0001)\r\n#pl.ylim(0.0, 1.0)\r\n# show the plot on the screen\r\npl.show()\r\n\r\n","sub_path":"Plotting.py","file_name":"Plotting.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"516363975","text":"import sys\r\n\r\n\r\ndef get_largest_prime_below(n):\r\n \"\"\"\r\n returneaza ultimul nr prim mai mic decat cel dat\r\n :param n: un nr intreg\r\n :return: numarul cautat\r\n \"\"\"\r\n for i in range(n - 1, 2, -1):\r\n if is_Prime(i):\r\n return i\r\n\r\ndef is_Prime(n):\r\n \"\"\"\r\n verifica daca un nr este prim\r\n :param n: un nr intreg\r\n :return: True, daca nr este prim. False, daca nr nu este prim\r\n \"\"\"\r\n if n < 2:\r\n return False\r\n for i in range(2, n // 2 + 1):\r\n if n % i == 0:\r\n return False\r\n return True\r\n\r\ndef test_is_Prime():\r\n assert is_Prime(4) == False\r\n assert is_Prime(7) == True\r\n assert is_Prime(13) == True\r\n assert is_Prime(6886) == False\r\n\r\ndef test_get_largest_prime_below():\r\n assert get_largest_prime_below(60) == 59\r\n assert get_largest_prime_below(8) == 7\r\n assert get_largest_prime_below(10) == 7\r\n assert get_largest_prime_below(34) == 31\r\n assert get_largest_prime_below(94) == 89\r\n\r\ndef is_palindrome(n):\r\n \"\"\"\r\n verifica daca un nr este palindrom\r\n :param n: un nr intreg\r\n :return: True, daca nr este palindrom, False in caz contrar\r\n \"\"\"\r\n inverse = 0\r\n copy = n\r\n while copy > 0:\r\n inverse = inverse * 10 + copy % 10\r\n copy = copy // 10\r\n if inverse == n:\r\n return True\r\n else:\r\n return False\r\n\r\ndef main():\r\n test_get_largest_prime_below()\r\n test_is_Prime()\r\n print(\"Testele au trecut cu succes\")\r\n while True:\r\n print(\"1. Ultimul nr prim\")\r\n print(\"2. Palindrom\")\r\n print(\"3. Iesire\")\r\n optiune = input(\"Alege optiunea: \")\r\n if optiune == '1':\r\n n = int(input('Dati numarul n: '))\r\n valoare = get_largest_prime_below(n)\r\n print(f'numarul prim cautat este {valoare}')\r\n elif optiune == '2':\r\n n = int(input('Dati numarul n: '))\r\n if is_palindrome(n):\r\n print('Numarul este palindrom')\r\n elif not is_palindrome(n):\r\n print('Numarul nu este palindrom')\r\n elif optiune == '3':\r\n sys.exit()\r\n else:\r\n print(\"optiune invalida\")\r\n\r\nmain()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"264795668","text":"def mergeSort(n, S):\r\n h = n // 2\r\n m = n - h\r\n\r\n if n > 1:\r\n U = S[:h]\r\n V = S[h:]\r\n #분할 전 필요한 추가 메모리의 총합을 계산\r\n global memory, max_memory\r\n memory += len(U) + len(V)\r\n #합병정렬 중에 순간 추가 메모리의 최대값를 계산\r\n max_memory = max(memory, max_memory)\r\n mergeSort(h, U) #divide\r\n mergeSort(m, V) #divide\r\n merge(h,m,U,V,S) #combine\r\n #합병 후 사용한 추가 메모리는 총합에서 제외\r\n memory -= (len(U) + len(V))\r\n \r\ndef merge(h,m,U,V,S):\r\n i = 0; j = 0; k = 0\r\n\r\n while(i < h and j < m):\r\n if U[i] < V[j]:\r\n S[k] = U[i]\r\n i += 1\r\n else:\r\n S[k] = V[j]\r\n j += 1\r\n k += 1\r\n if i >= h:\r\n S[k:] = V[j:]\r\n else:\r\n S[k:] = U[i:]\r\n\r\nS=[3,5,2,9,10,14,4,8]\r\nmemory = 0 ; max_memory = 0\r\nmergeSort(8, S)\r\nprint(S)\r\nprint(\"Additional Memory : \", max_memory)\r\n","sub_path":"Python/2020-2_알고리즘분석/2_DivideConquer/2_2_MergeSort.py","file_name":"2_2_MergeSort.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"501266660","text":"import os\nimport argparse\nimport tensorflow as tf\nfrom Transformer_softmax_lstm import Transformer, Config\nfrom data_process import train_dev_split\nfrom data_process import load_data\nparser = argparse.ArgumentParser()\nparser.add_argument('model_path', type=str)\n\n\n\ndef main(test_model):\n\n config = Config()\n config.batch_size = 1024\n config.hidden_size = 64\n config.vocab_size = 26\n config.embed_size = 320\n config.max_epochs = 100\n config.label_kinds = 2\n config.if_train = True\n config.if_test = True\n config.is_biLSTM = True\n config.max_seqlen = 20\n\n config.original_file = '../data/most_frequent_words_label.txt'\n config.train_file = '../data/most_frequent_words_label_train.txt'\n config.dev_file = '../data/most_frequent_words_label_dev'\n config.vocab_file = '../data/vocab.txt'\n config.model_path = 'models/Transformer_softmax_lstm/'\n\n config.split_ratio = 0.8\n\n print('Prepare data for train and dev ... ')\n train_dev_split(config.original_file, config.train_file, config.dev_file,\n config.vocab_file, config.split_ratio)\n print('Prepare data sucessfully!')\n\n model = Transformer(config)\n gpu_options = tf.GPUOptions(allow_growth=True)\n gpu_options =tf.GPUOptions(per_process_gpu_memory_fraction=0.5, allow_growth=True) ##每个gpu占用0.8 的显存\n tf_config=tf.ConfigProto(gpu_options=gpu_options,allow_soft_placement=True)\n with tf.Session(config=tf_config) as sess:\n if config.if_test:\n init=tf.global_variables_initializer()\n sess.run(init)\n (X_test, y_test) = load_data(config.dev_file)\n\n if len(X_test) < config.batch_size:\n for i in range(0, config.batch_size - len(X_test)):\n X_test.append([0])\n y_test.append([0])\n\n seq_len_test = list(map(lambda x: len(x), X_test))\n\n print('Target to special model to test')\n print('Start do predicting...')\n model.test(sess, test_model, X_test, y_test, seq_len_test,\n config.vocab_file, config.model_path + 'result/')\n\n\n\n print('Success for preparing data')\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main(args.model_path)\n","sub_path":"subword/test_Transformer_softmax_lstm.py","file_name":"test_Transformer_softmax_lstm.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"606977981","text":"#!/usr/bin/env python\nu\"\"\"\nplot_global_grid_5maps.py\nWritten by Tyler Sutterley (05/2023)\nCreates 5 GMT-like plots in a Plate Carree (Equirectangular) projection\n\nPYTHON DEPENDENCIES:\n numpy: Scientific Computing Tools For Python\n http://www.numpy.org\n http://www.scipy.org/NumPy_for_Matlab_Users\n scipy: Scientific Tools for Python\n http://www.scipy.org/\n netCDF4: Python interface to the netCDF C library\n https://unidata.github.io/netcdf4-python/netCDF4/index.html\n h5py: Python interface for Hierarchal Data Format 5 (HDF5)\n http://h5py.org\n matplotlib: Python 2D plotting library\n http://matplotlib.org/\n https://github.com/matplotlib/matplotlib\n cartopy: Python package designed for geospatial data processing\n https://scitools.org.uk/cartopy\n pyshp: Python read/write support for ESRI Shapefile format\n https://github.com/GeospatialPython/pyshp\n\nUPDATE HISTORY:\n Updated 05/2023: use pathlib to define and operate on paths\n added option to set the input variable names or column order\n Updated 03/2023: switch from parameter files to argparse arguments\n updated inputs to spatial from_ascii function\n Updated 07/2022: place some imports behind try/except statements\n Updated 05/2022: use argparse descriptions within documentation\n use mask, shift grid and interpolation functions from tools\n Updated 12/2021: added color palette table (cpt) file reader from tools\n Updated 05/2021: define int/float precision to prevent deprecation warning\n Updated 10/2020: using spatial utilities for reading\n using argparse to set command-line parameters\n Updated 10/2019: changing Y/N flags to True/False\n Updated 09/2019: added parameter for specifying if netCDF4 or HDF5\n Updated 04/2019: set cap style of cartopy geoaxes outline patch\n Updated 03/2019: replacing matplotlib basemap with cartopy\n Updated 02/2019: saving metadata to output figure\n Updated 12/2018: added parameter CBEXTEND for colorbar extension triangles\n Updated 09/2018: use a custom mask_oceans function instead of default maskoceans\n added REMOVE parameter to subtract a spatial field from each input map\n Updated 05/2018: using __future__ print function for python3 compatibility\n Updated 11/2017: can plot a contour of the global average with MEAN\n Written 08/2017\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport copy\nimport logging\nimport pathlib\nimport argparse\nimport warnings\nimport traceback\nimport numpy as np\nimport scipy.ndimage\nimport scipy.interpolate\nimport gravity_toolkit as gravtk\n\n# attempt imports\ntry:\n import cartopy.crs as ccrs\nexcept ModuleNotFoundError:\n warnings.filterwarnings(\"module\")\n warnings.warn(\"cartopy not available\", ImportWarning)\ntry:\n import matplotlib\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n from matplotlib import gridspec\n import matplotlib.colors as colors\n import matplotlib.ticker as ticker\n import matplotlib.offsetbox as offsetbox\n matplotlib.rcParams['axes.linewidth'] = 2.0\n matplotlib.rcParams['font.family'] = 'sans-serif'\n matplotlib.rcParams['font.sans-serif'] = ['Helvetica']\n matplotlib.rcParams['mathtext.default'] = 'regular'\nexcept ModuleNotFoundError:\n warnings.filterwarnings(\"module\")\n warnings.warn(\"matplotlib not available\", ImportWarning)\ntry:\n import shapefile\nexcept ModuleNotFoundError:\n warnings.filterwarnings(\"module\")\n warnings.warn(\"shapefile not available\", ImportWarning)\n# ignore warnings\nwarnings.filterwarnings(\"ignore\")\n\n# cartopy transform for Equirectangular Projection\ntry:\n projection = ccrs.PlateCarree()\nexcept (NameError,ValueError) as exc:\n pass\n\n# PURPOSE: keep track of threads\ndef info(args):\n logging.info(pathlib.Path(sys.argv[0]).name)\n logging.info(args)\n logging.info(f'module name: {__name__}')\n if hasattr(os, 'getppid'):\n logging.info(f'parent process: {os.getppid():d}')\n logging.info(f'process id: {os.getpid():d}')\n\n# PURPOSE plot coastlines and islands (GSHHS with G250 Greenland)\ndef plot_coastline(ax, base_dir, LINEWIDTH=0.5):\n # read the coastline shape file\n coastline_dir = base_dir.joinpath('masks','G250')\n coastline_shape_files = []\n coastline_shape_files.append('GSHHS_i_L1_no_greenland.shp')\n coastline_shape_files.append('greenland_coastline_islands.shp')\n for fi,S in zip(coastline_shape_files,[1000,200]):\n coast_shapefile = coastline_dir.joinpath(*fi)\n logging.debug(str(coast_shapefile))\n shape_input = shapefile.Reader(str(coast_shapefile))\n shape_entities = shape_input.shapes()\n # for each entity within the shapefile\n for c,ent in enumerate(shape_entities[:S]):\n # extract coordinates and plot\n lon,lat = np.transpose(ent.points)\n ax.plot(lon, lat, c='k', lw=LINEWIDTH, transform=projection)\n\n# PURPOSE: plot Antarctic grounded ice delineation\ndef plot_grounded_ice(ax, base_dir, LINEWIDTH=0.5):\n coast_file = ['masks','IceBoundaries_Antarctica_v02',\n 'ant_ice_sheet_islands_v2.shp']\n coast_shapefile = base_dir.joinpath(*coast_file)\n logging.debug(str(coast_shapefile))\n shape_input = shapefile.Reader(str(coast_shapefile))\n shape_entities = shape_input.shapes()\n shape_attributes = shape_input.records()\n i = [i for i,e in enumerate(shape_entities) if (np.ndim(e.points) > 1)]\n # cartopy transform for NSIDC polar stereographic south\n projection = ccrs.Stereographic(central_longitude=0.0,\n central_latitude=-90.0,true_scale_latitude=-71.0)\n for indice in i:\n # extract Polar-Stereographic coordinates for record\n pts = np.array(shape_entities[indice].points)\n ax.plot(pts[:,0], pts[:,1], c='k', lw=LINEWIDTH, transform=projection)\n\n# plot grid program\ndef plot_grid(base_dir, FILENAMES,\n DATAFORM=None,\n VARIABLES=[],\n MASK=None,\n INTERPOLATION=None,\n DDEG=None,\n INTERVAL=None,\n SCALE_FACTOR=1.0,\n REMOVE_FILE=None,\n COLOR_MAP=None,\n CPT_FILE=None,\n PLOT_RANGE=None,\n BOUNDARY=None,\n ALPHA=1.0,\n CONTOURS=False,\n CONTOUR_RANGE=None,\n MEAN_CONTOUR=False,\n TITLES=None,\n LABELS=None,\n CBEXTEND=None,\n CBTITLE=None,\n CBUNITS=None,\n CBFORMAT=None,\n DRAW_GRID_LINES=False,\n GRID=None,\n FIGURE_FILE=None,\n FIGURE_FORMAT=None,\n FIGURE_DPI=None,\n MODE=0o775):\n\n # extend list if a single format was entered for all files\n if len(DATAFORM) < len(FILENAMES):\n DATAFORM = DATAFORM*len(FILENAMES)\n\n # read CPT or use color map\n if CPT_FILE is not None:\n # cpt file\n cmap = gravtk.tools.from_cpt(CPT_FILE)\n else:\n # colormap\n cmap = copy.copy(cm.get_cmap(COLOR_MAP))\n # grey color map for bad values\n cmap.set_bad('w',0.5)\n\n # set transparency ALPHA\n if BOUNDARY is None:\n # contours\n levels = np.arange(PLOT_RANGE[0], PLOT_RANGE[1]+PLOT_RANGE[2],\n PLOT_RANGE[2])\n norm = colors.Normalize(vmin=PLOT_RANGE[0], vmax=PLOT_RANGE[1])\n else:\n # boundary between contours\n levels = np.array(BOUNDARY, dtype=np.float64)\n norm = colors.BoundaryNorm(BOUNDARY, ncolors=256)\n\n # convert degree spacing and interval parameters\n # Grid spacing\n dlon,dlat = (DDEG[0],DDEG[0]) if (len(DDEG) == 1) else (DDEG[0],DDEG[1])\n # Grid dimensions\n if (INTERVAL == 1):# (0:360, 90:-90)\n nlon = np.int64((360.0/dlon)+1.0)\n nlat = np.int64((180.0/dlat)+1.0)\n elif (INTERVAL == 2):# degree spacing/2\n nlon = np.int64((360.0/dlon))\n nlat = np.int64((180.0/dlat))\n\n # interpolation method for image background using transform_scalar\n if (INTERPOLATION == 'nearest'):\n order = 0\n elif (INTERPOLATION == 'bilinear'):\n order = 1\n elif (INTERPOLATION == 'cubic'):\n order = 3\n\n # create masked array if missing values\n if MASK is not None:\n # Read Land-Sea Mask of specified input file\n # 0=Ocean, 1=Land, 2=Lake, 3=Small Island, 4=Ice Shelf\n # Open the land-sea NetCDF file for reading\n landsea = gravtk.spatial().from_netCDF4(MASK,\n date=False, varname='LSMASK')\n # create land function\n nth,nphi = landsea.shape\n mask = np.zeros((nth,nphi),dtype=bool)\n # combine land and island levels for land function\n indx,indy = np.nonzero((landsea.data >= 1) & (landsea.data <= 3))\n mask[indx,indy] = True\n\n # remove a spatial field from each input map\n if REMOVE_FILE is not None:\n REMOVE = gravtk.spatial().from_netCDF4(REMOVE_FILE,\n date=False).data[:,:]\n else:\n REMOVE = 0.0\n\n # image extents\n ax = {}\n # setup Plate Carree projection\n fig = plt.figure(figsize=(10.375,12.5))\n gs = gridspec.GridSpec(3, 2, height_ratios=[2,1,1])\n ax[0] = plt.subplot(gs[0,:], projection=projection)\n ax[1] = plt.subplot(gs[1,0], projection=projection)\n ax[2] = plt.subplot(gs[1,1], projection=projection)\n ax[3] = plt.subplot(gs[2,0], projection=projection)\n ax[4] = plt.subplot(gs[2,1], projection=projection)\n # WGS84 Ellipsoid parameters\n a_axis = 6378137.0# [m] semimajor axis of the ellipsoid\n flat = 1.0/298.257223563# flattening of the ellipsoid\n # (4pi/3)R^3 = (4pi/3)(a^2)b = (4pi/3)(a^3)(1 -f)\n rad_e = a_axis*(1.0 - flat)**(1.0/3.0)\n\n for i,ax1 in ax.items():\n\n # input ascii/netCDF4/HDF5 file\n if (DATAFORM[i] == 'ascii'):\n # ascii (.txt)\n dinput = gravtk.spatial().from_ascii(FILENAMES[i], date=False,\n columns=VARIABLES, spacing=[dlon,dlat], nlat=nlat, nlon=nlon)\n elif (DATAFORM[i] == 'netCDF4'):\n # netCDF4 (.nc)\n field_mapping = gravtk.spatial().default_field_mapping(VARIABLES)\n dinput = gravtk.spatial().from_netCDF4(FILENAMES[i], date=False,\n field_mapping=field_mapping)\n elif (DATAFORM[i] == 'HDF5'):\n # HDF5 (.H5)\n field_mapping = gravtk.spatial().default_field_mapping(VARIABLES)\n dinput = gravtk.spatial().from_HDF5(FILENAMES[i], date=False,\n field_mapping=field_mapping)\n\n # remove offset and scale to units\n if (REMOVE != 0.0) or (SCALE_FACTOR != 1.0):\n dinput = dinput.offset(-REMOVE).scale(SCALE_FACTOR)\n\n # update masked values\n if MASK is not None:\n dinput.replace_invalid(fill_value=dinput.fill_value, mask=mask)\n\n # if dlat is negative\n if (np.sign(dlat) == -1):\n dinput = dinput.flip(axis=0)\n\n # calculate image coordinates\n xmin,xmax,ymin,ymax = ax1.get_extent()\n mx = np.int64((xmax-xmin)/0.5)+1\n my = np.int64((ymax-ymin)/0.5)+1\n X = np.linspace(xmin,xmax,mx)\n Y = np.linspace(ymin,ymax,my)\n gridx,gridy = np.meshgrid(X,Y)\n # create mesh lon/lat\n points = projection.transform_points(projection,\n gridx.flatten(), gridy.flatten())\n lonsin = points[:,0].reshape(my,mx)\n latsin = points[:,1].reshape(my,mx)\n\n # interpolate to image coordinates\n if (INTERVAL == 1) and (np.max(dinput.lon) > 180):# (0:360, 90:-90)\n shift_data,lon180 = gravtk.tools.shift_grid(180.0,\n dinput.data,dinput.lon)\n shift_mask,lon180 = gravtk.tools.shift_grid(180.0,\n dinput.mask,dinput.lon)\n img = gravtk.tools.interp_grid(shift_data,lon180,\n dinput.lat,lonsin,latsin,order)\n msk = gravtk.tools.interp_grid(shift_mask,lon180,\n dinput.lat,lonsin,latsin,order)\n elif (INTERVAL == 2) and (np.max(dinput.lon) > 180):# DDEG/2\n shift_data,lon180 = gravtk.tools.shift_grid(180.0+dlon,\n dinput.data,dinput.lon)\n shift_mask,lon180 = gravtk.tools.shift_grid(180.0+dlon,\n dinput.mask,dinput.lon)\n img = gravtk.tools.interp_grid(shift_data,\n lon180,dinput.lat,lonsin,latsin,order)\n msk = gravtk.tools.interp_grid(shift_mask,\n lon180,dinput.lat,lonsin,latsin,order)\n else:# -180:180 or modification of there of\n img = gravtk.tools.interp_grid(dinput.data,\n dinput.lon,dinput.lat,lonsin,latsin,order)\n msk = gravtk.tools.interp_grid(dinput.mask,\n dinput.lon,dinput.lat,lonsin,latsin,order)\n # create masked array of image\n img = np.ma.array(img, mask=msk.astype(bool))\n\n # plot only grounded points\n if MASK is not None:\n img = gravtk.tools.mask_oceans(lonsin,latsin,\n data=img,order=order,iceshelves=False)\n # plot image with transparency using normalization\n im = ax1.imshow(img, interpolation='nearest',\n extent=(xmin,xmax,ymin,ymax),\n cmap=cmap, norm=norm, alpha=ALPHA,\n origin='lower', transform=projection)\n\n # create mesh lon/lat\n lon, lat = np.meshgrid(dinput.lon,dinput.lat)\n # recalculate data at zoomed coordinates\n data = np.ma.array(scipy.ndimage.zoom(img.data,5,order=1))\n mask = scipy.ndimage.zoom(np.invert(img.mask),5,order=1,output=bool)\n data.mask = np.invert(mask)\n # plot line contours\n if CONTOURS:\n clevs = np.arange(CONTOUR_RANGE[0],\n CONTOUR_RANGE[1] + CONTOUR_RANGE[2],\n CONTOUR_RANGE[2])\n # remove 0 (will plot in red)\n reduce_clevs = clevs[np.nonzero(clevs)]\n # plot contours\n ax1.contour(data,reduce_clevs,colors='0.2',linestyles='solid',\n extent=(xmin,xmax,ymin,ymax),origin='lower',\n transform=projection)\n ax1.contour(data,[0],colors='red',linestyles='solid',linewidths=1.5,\n extent=(xmin,xmax,ymin,ymax),origin='lower',\n transform=projection)\n\n # plot line contour for global average\n if MEAN_CONTOUR and CONTOURS:\n # calculate areas of each grid cell\n dphi,dth = (dlon*np.pi/180.0,dlat*np.pi/180.0)\n indy,indx = np.nonzero(np.logical_not(dinput.mask))\n area = (rad_e**2)*dth*dphi*np.cos(lat[indy,indx]*np.pi/180.0)\n # calculate average\n ave = np.sum(area*dinput.data[indy,indx])/np.sum(area)\n # plot line contour of global average\n ax1.contour(data,[ave],colors='blue',linestyles='solid',linewidths=1.5,\n extent=(xmin,xmax,ymin,ymax),origin='lower',\n transform=projection)\n\n # draw coastlines\n plot_coastline(ax1, base_dir)\n # plot grounded ice exterior for Antarctica\n plot_grounded_ice(ax1, base_dir)\n\n # draw lat/lon grid lines\n if DRAW_GRID_LINES:\n # meridian and parallel grid spacing\n llx,lly = (GRID[0],GRID[0]) if (len(GRID) == 1) else (GRID[0],GRID[1])\n grid_meridians = np.arange(-180, 180 + llx, llx)\n grid_parallels = np.arange(-90, 90 + lly, lly)\n gl = ax1.gridlines(crs=projection, draw_labels=False,\n linewidth=0.1, color='0.25', linestyle='-')\n gl.xlocator = ticker.FixedLocator(grid_meridians)\n gl.ylocator = ticker.FixedLocator(grid_parallels)\n\n # add title for each subplot\n if TITLES is not None:\n TITLE = ' '.join(TITLES[i].split('_'))\n ax1.set_title(TITLE.replace('-',u'\\u2013'), fontsize=18)\n ax1.title.set_y(1.01)\n # Add figure label for each subplot\n if LABELS is not None:\n at = offsetbox.AnchoredText(LABELS[i],\n loc=2, pad=0, borderpad=0.25, frameon=True,\n prop=dict(size=18,weight='bold',color='k'))\n at.patch.set_boxstyle(\"Square,pad=0.1\")\n at.patch.set_edgecolor(\"white\")\n ax1.axes.add_artist(at)\n\n # axis = equal\n ax1.set_aspect('equal', adjustable='box')\n # no ticks on the x and y axes\n ax1.get_xaxis().set_ticks([])\n ax1.get_yaxis().set_ticks([])\n # stronger linewidth on frame\n ax1.spines['geo'].set_linewidth(2.0)\n ax1.spines['geo'].set_zorder(10)\n ax1.spines['geo'].set_capstyle('projecting')\n\n # Add colorbar\n # Add an axes at position rect [left, bottom, width, height]\n cbar_ax = fig.add_axes([0.095, 0.065, 0.81, 0.025])\n # extend = add extension triangles to upper and lower bounds\n # options: neither, both, min, max\n cbar = fig.colorbar(im, cax=cbar_ax, extend=CBEXTEND,\n extendfrac=0.0375, drawedges=False, orientation='horizontal')\n # rasterized colorbar to remove lines\n cbar.solids.set_rasterized(True)\n # Add label to the colorbar\n cbar.ax.set_title(CBTITLE, fontsize=18, rotation=0, y=-1.65, va='top')\n cbar.ax.set_xlabel(CBUNITS, fontsize=18, rotation=0, va='center')\n cbar.ax.xaxis.set_label_coords(1.075, 0.5)\n # Set the tick levels for the colorbar\n cbar.set_ticks(levels)\n cbar.set_ticklabels([CBFORMAT.format(ct) for ct in levels])\n # ticks lines all the way across\n cbar.ax.tick_params(which='both', width=1, length=22, labelsize=18,\n direction='in')\n\n # adjust subplots within figure\n fig.subplots_adjust(left=0.01, right=0.99, bottom=0.10, top=0.97,\n hspace=0.1, wspace=0.05)\n # create output directory if non-existent\n FIGURE_FILE.parent.mkdir(mode=MODE, parents=True, exist_ok=True)\n # save to file\n logging.info(str(FIGURE_FILE))\n plt.savefig(FIGURE_FILE,\n metadata={'Title':pathlib.Path(sys.argv[0]).name},\n dpi=FIGURE_DPI, format=FIGURE_FORMAT)\n plt.clf()\n # change the permissions mode\n FIGURE_FILE.chmod(mode=MODE)\n\n# PURPOSE: create argument parser\ndef arguments():\n parser = argparse.ArgumentParser(\n description=u\"\"\"Creates 5 GMT-like plots on a global Plate Carr\\u00E9e\n (Equirectangular) projection\n \"\"\",\n fromfile_prefix_chars=\"@\"\n )\n parser.convert_arg_line_to_args = gravtk.utilities.convert_arg_line_to_args\n # command line parameters\n parser.add_argument('infile', nargs=5,\n type=pathlib.Path,\n help='Input grid files')\n # working data directory\n parser.add_argument('--directory','-D',\n type=pathlib.Path, default=pathlib.Path.cwd(),\n help='Working data directory')\n # Input data format (ascii, netCDF4, HDF5)\n parser.add_argument('--format','-F',\n type=str, nargs='+',\n default='netCDF4', choices=['ascii','netCDF4','HDF5'],\n help='Input data format')\n # variable names (for ascii names of columns)\n parser.add_argument('--variables','-v',\n type=str, nargs='+', default=['lon','lat','z'],\n help='Variable names of data in input file')\n # land-sea mask\n lsmask = gravtk.utilities.get_data_path(['data','landsea_hd.nc'])\n parser.add_argument('--mask',\n type=pathlib.Path, default=lsmask,\n help='Land-sea mask')\n # output grid parameters\n parser.add_argument('--spacing',\n type=float, nargs='+', default=[0.5,0.5], metavar=('dlon','dlat'),\n help='Spatial resolution of input data')\n parser.add_argument('--interval',\n type=int, default=2, choices=[1,2],\n help=('Input grid interval (1: global, 2: centered global)'))\n # Interpolation method\n parser.add_argument('--interpolation','-I',\n type=str, default='bilinear', choices=['nearest','bilinear','cubic'],\n help='Interpolation method')\n # scale factor\n parser.add_argument('--scale-factor','-s',\n type=float, default=1.0,\n help='Multiplicative scale factor for converting to plot units')\n # plot range\n parser.add_argument('--plot-range','-R',\n type=float, nargs=3, metavar=('MIN','MAX','STEP'),\n help='Plot range and step size for normalization')\n parser.add_argument('--boundary','-B',\n type=float, nargs='+',\n help='Plot boundary for normalization')\n # color palette table or named color map\n try:\n cmap_set = set(cm.datad.keys()) | set(cm.cmaps_listed.keys())\n except (ValueError, NameError) as exc:\n cmap_set = []\n parser.add_argument('--colormap','-m',\n metavar='COLORMAP', type=str, default='viridis',\n choices=sorted(cmap_set),\n help='Named Matplotlib colormap')\n parser.add_argument('--cpt-file','-c',\n type=pathlib.Path,\n help='Input Color Palette Table (.cpt) file')\n # color map alpha\n parser.add_argument('--alpha','-a',\n type=float, default=1.0,\n help='Named Matplotlib colormap')\n # plot contour parameters\n parser.add_argument('--plot-contours',\n default=False, action='store_true',\n help='Plot contours')\n parser.add_argument('--contour-range',\n type=float, nargs=3, metavar=('MIN','MAX','STEP'),\n help='Contour range and step size')\n parser.add_argument('--mean-contour',\n default=False, action='store_true',\n help='Plot contours for mean of dataset')\n # title and label\n parser.add_argument('--plot-title', nargs=5,\n type=str, help='Plot title')\n parser.add_argument('--plot-label', nargs=5,\n type=str, help='Plot label')\n # colorbar parameters\n parser.add_argument('--cbextend',\n type=str, default='both',\n choices=['neither', 'both', 'min', 'max'],\n help='Add extension triangles to colorbar')\n parser.add_argument('--cbtitle',\n type=str, default='',\n help='Title label for colorbar')\n parser.add_argument('--cbunits',\n type=str, default='',\n help='Units label for colorbar')\n parser.add_argument('--cbformat',\n type=str, default='{0:3.0f}',\n help='Tick format for colorbar')\n # additional parameters\n parser.add_argument('--draw-grid-lines',\n default=False, action='store_true',\n help='Add map grid lines')\n parser.add_argument('--grid-lines',\n type=float, nargs='+', default=(15,15),\n help='Input grid spacing for meridians and parallels')\n # output file, format and dpi\n parser.add_argument('--figure-file','-O',\n type=pathlib.Path,\n help='Output figure file')\n parser.add_argument('--figure-format','-f',\n type=str, default='png', choices=('pdf','png','jpg','svg'),\n help='Output figure format')\n parser.add_argument('--figure-dpi','-d',\n type=int, default=180,\n help='Output figure resolution in dots per inch (dpi)')\n # print information about each input and output file\n parser.add_argument('--verbose','-V',\n action='count', default=0,\n help='Verbose output of run')\n # permissions mode of the local directories and files (number in octal)\n parser.add_argument('--mode','-M',\n type=lambda x: int(x,base=8), default=0o775,\n help='Permissions mode of output files')\n # return the parser\n return parser\n\n# This is the main part of the program that calls the individual functions\ndef main():\n # Read the system arguments listed after the program\n parser = arguments()\n args,_ = parser.parse_known_args()\n\n # create logger\n loglevels = [logging.CRITICAL, logging.INFO, logging.DEBUG]\n logging.basicConfig(level=loglevels[args.verbose])\n\n # try to run the analysis with listed parameters\n try:\n info(args)\n # run plot program with parameters\n plot_grid(args.directory, args.infile,\n DATAFORM=args.format,\n VARIABLES=args.variables,\n DDEG=args.spacing,\n INTERVAL=args.interval,\n INTERPOLATION=args.interpolation,\n SCALE_FACTOR=args.scale_factor,\n CPT_FILE=args.cpt_file,\n COLOR_MAP=args.colormap,\n PLOT_RANGE=args.plot_range,\n BOUNDARY=args.boundary,\n ALPHA=args.alpha,\n CONTOURS=args.plot_contours,\n CONTOUR_RANGE=args.contour_range,\n MEAN_CONTOUR=args.mean_contour,\n TITLES=args.plot_title,\n LABELS=args.plot_label,\n CBEXTEND=args.cbextend,\n CBTITLE=args.cbtitle,\n CBUNITS=args.cbunits,\n CBFORMAT=args.cbformat,\n DRAW_GRID_LINES=args.draw_grid_lines,\n GRID=args.grid_lines,\n FIGURE_FILE=args.figure_file,\n FIGURE_FORMAT=args.figure_format,\n FIGURE_DPI=args.figure_dpi,\n MODE=args.mode)\n except Exception as exc:\n # if there has been an error exception\n # print the type, value, and stack trace of the\n # current exception being handled\n logging.critical(f'process id {os.getpid():d} failed')\n logging.error(traceback.format_exc())\n\n# run main program\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/plot_global_grid_5maps.py","file_name":"plot_global_grid_5maps.py","file_ext":"py","file_size_in_byte":24924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"74927101","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n# @fileName : import_log.py\n# @Author : sf_xu\n# @Time : 2019/12/11 10:00\n#\n# @Description :\n\n\nimport os\nimport time\n\n\nclass VisitLogIoc(object):\n def __init__(self, log_content_list=None):\n self._log_content_list = log_content_list\n\n def save(self):\n u\"\"\"\n :return\n \"\"\"\n # project_name = self._request_obj.project_name\n # log_type = self._request_obj.log_type\n # title = self._request_obj.title\n # content = self._request_obj.content\n\n for item in self._log_content_list:\n log_path = os.getcwd() + '/Logs/' + f\"/{item['project_name']}/\" + f\"/{item['log_type']}/\"\n if not os.path.exists(log_path): # 判断文件路径是否存在\n os.makedirs(log_path)\n date = time.strftime('%Y%m%d', time.localtime(time.time()))\n log_name = log_path + date + '.log'\n data = f\"{item['date_time']} - [title]:{item['title']} - [content]:{item['content']}\"\n with open(log_name, mode=\"a+\", encoding=\"utf8\") as f:\n f.writelines(data + \"\\n\")\n f.flush()\n\n return True\n\n\n","sub_path":"projects/log_record/ioc/import_log.py","file_name":"import_log.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"89722221","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 24 17:50:19 2019\n\n@author: akmil\n\"\"\"\n\n'''\nExercise 2: Write another program that prompts for a list of numbers\nas above and at the end prints out both the maximum and minimum of\nthe numbers instead of the average.\n'''\n\nnumbers = []\ntotal = 0\nwhile True:\n try:\n line = input(\"Enter a number: \")\n if line == 'done':\n break\n else:\n line = float(line)\n numbers.append(line)\n except:\n print(\"Invalid data.\")\n continue\n\nfor i in numbers:\n total += i\n\nprint(numbers)\nprint(f\"total = {total}\")\ncount = len(numbers)\nprint(f\"count = {count}\")\nminimum = min(numbers)\nprint(f\"min = {minimum}\")\nmaximum = max(numbers)\nprint(f\"max = {maximum}\")","sub_path":"Assignment3/5_2_excercise.py","file_name":"5_2_excercise.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"606559371","text":"import os\nimport csv\nimport argparse\nimport pydub.silence\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nimport sys\n\n# arg parser\nparser = argparse.ArgumentParser()\nparser.add_argument('-sf', '--sound_file', type=str, required=True, help=\"path to soundfile\")\nparser.add_argument('-sd', \"--save_dir\", type=str, required=False, help=\"path to save dir\")\nparser.add_argument('-ss', '--sample_size', type=int, required=False, help=\"the size of each sample\")\nparser.add_argument('-cv', '--csv_save', type=bool, required=False, help=\"True if metadata\")\nparser.add_argument('-head', '--head', type=str, required=False, help=\"header to wav files\")\nparser.add_argument('-class', '--class_id', type=int, required=False, help=\"classID -- will default to 1\")\nparser.add_argument('-name', '--dataset_name', type=str, required=False, help=\"name of the dataset\")\nargs = parser.parse_args()\n\n\ndef slice(sound_file, save_dir, sample_size=10, csv_save=True, head=\"sample\", class_id=1, dataset_name=None):\n sound = AudioSegment.from_file(sound_file, format=\"wav\")\n if not (dataset_name == None):\n folder = os.path.join(save_dir, dataset_name)\n else:\n folder = save_dir\n\n csv_save_dir = os.path.join(folder, \"metadata\")\n audio_save_dir = os.path.join(folder, \"audio\")\n\n # convert to seconds\n jump = sample_size * 1000\n start = 0\n end = jump\n num_samples = (len(sound) // jump)\n csv_file = []\n\n print(\"Creating folders...\")\n\n if not os.path.isdir(folder):\n os.mkdir(folder)\n os.mkdir(audio_save_dir)\n if csv_save:\n os.mkdir(csv_save_dir)\n else:\n if not os.path.isdir(audio_save_dir):\n os.mkdir(audio_save_dir)\n if csv_save:\n os.mkdir(csv_save_dir)\n\n print(\"Splitting into samples...\")\n\n for sample in range(num_samples - 1):\n segment = sound[start:end]\n if len(segment) != 10000:\n continue\n file_name = f\"{head}_{sample}.wav\"\n segment.export(os.path.join(audio_save_dir, file_name), format='wav')\n length = str(len(segment))\n row = [file_name, length, class_id]\n csv_file.append(row)\n start += jump\n end += jump\n if csv_save:\n print(\"Saving CSV...\")\n with open(os.path.join(csv_save_dir, 'meta.csv'), 'w') as file:\n writer = csv.writer(file)\n writer.writerows(csv_file)\n print(\"Finished.\")\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n \"\"\"\n These are the different parameters for saving and choosing how to splice file. WAV files will be saved\n with a RIFF header and can be read in ML applications. \n \"\"\"\n\n # name of the data set\n dataset_name = \"sad\"\n # path to original sound file\n sound_file = \"/Users/milessigel/Desktop/Datasets/piano_sentiment_dataset/sad_music.wav\"\n # where are the top level datasets saved\n save_dir = \"/Users/milessigel/Desktop/Datasets\"\n # class_id\n class_id = 1\n # header for the sample files\n head = \"sample\"\n # do you want CSV?\n csv_save = True\n # number of seconds of sample\n sample_size = 10\n\n if len(sys.argv) > 1:\n slice(args.sound_file, args.save_dir,\n sample_size=args.sample_size if args.sample_size is not None else sample_size,\n csv_save=args.csv_save if args.csv_save is not None else csv_save,\n head=args.head if args.head is not None else head,\n class_id=args.class_id if args.class_id is not None else class_id,\n dataset_name=args.dataset_name if args.dataset_name is not None else dataset_name)\n exit()\n\n\n slice(sound_file, save_dir, sample_size=sample_size, csv_save=csv_save, head=head, class_id=class_id, dataset_name=dataset_name)\n","sub_path":"wav_split.py","file_name":"wav_split.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"619196901","text":"from ocdskingfisher.base import Source\nfrom ocdskingfisher.util import save_content\nimport json\nimport hashlib\n\n\nclass AustraliaSource(Source):\n \"\"\"\n \"\"\"\n\n publisher_name = 'Australia'\n url = 'https://api.tenders.gov.au'\n source_id = 'australia'\n\n def gather_all_download_urls(self):\n\n if self.sample:\n return[{\n 'url': \"https://api.tenders.gov.au/ocds/findByDates/contractPublished/2018-01-01T00:00:00Z/2018-12-31T23:59:59Z\",\n 'filename': 'year-2018.json',\n 'data_type': 'release_package',\n }]\n\n else:\n out = []\n for year in range(2004, 2020):\n url = \"https://api.tenders.gov.au/ocds/findByDates/contractPublished/{}-01-01T00:00:00Z/{}-12-31T23:59:59Z\".format(year, year) # noqa\n out.append({\n 'url': url,\n 'filename': 'year-{}.json'.format(year),\n 'data_type': 'release_package',\n 'priority': year,\n })\n\n return out\n\n def save_url(self, filename, data, file_path):\n\n save_content_response = save_content(data['url'], file_path)\n if save_content_response.errors:\n return self.SaveUrlResult(errors=save_content_response.errors, warnings=save_content_response.warnings)\n\n additional = []\n\n if not self.sample:\n\n with open(file_path) as f:\n json_data = json.load(f)\n\n if 'links' in json_data and 'next' in json_data['links'] and json_data['links']['next']:\n additional.append({\n 'url': json_data['links']['next'],\n 'filename': 'page-%s.json' % hashlib.md5(json_data['links']['next'].encode('utf-8')).hexdigest(),\n 'data_type': 'release_package',\n # We set priority the same so that all the requests for one year are done at the same time.\n # Because of how this pages using cursors, it's probably best to get them as fast as possible.\n 'priority': data['priority'],\n })\n\n return self.SaveUrlResult(additional_files=additional, warnings=save_content_response.warnings)\n","sub_path":"ocdskingfisher/sources/australia.py","file_name":"australia.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"347187390","text":"import time as t\nimport datetime as dt\nimport requests as req\nimport pandas as pd\nimport numpy as np\nimport json\nimport re\nfrom .utils import convert_to_timestamp, proxy_setter, parse_item\nfrom json import JSONDecodeError\nimport requests_cache\n\n\nclass Client:\n\n URL = 'https://query1.finance.yahoo.com'\n URL_TO_SCRAPE = 'https://finance.yahoo.com/quote'\n\n START_DATE = \"1971-01-01\"\n\n def __init__(self, symbol: str):\n self._symbol = symbol\n self._company_info: dict = {}\n self._historical_prices: pd.DataFrame\n self._recommendations: json = None\n self._fundamentals = False\n self._cash_flow: json = None\n self._income_statement: json = None\n self._balance_sheet: json = None\n self._splits: pd.DataFrame() = None\n self._dividends: pd.DataFrame() = None\n self._trends = {}\n self._financials = None\n self._holders = {}\n self._events = None\n self._sentiment = None\n\n def historical_prices(self, period=\"1y\", interval=\"1d\", start=None,\n end=None, proxy=None, **kwargs):\n\n params = {}\n if period in [None, False, 0, 'max'] or not start:\n if not start:\n start = convert_to_timestamp(self.START_DATE)\n if not end:\n end = convert_to_timestamp(dt.datetime.now())\n params[\"period1\"], params[\"period2\"] = start, end\n else:\n params[\"range\"] = period.lower()\n\n params[\"interval\"] = interval.lower()\n params[\"events\"] = \"div,splits\"\n\n if proxy: proxy = proxy_setter(proxy)\n\n url = f\"{self.URL}/v8/finance/chart/{self._symbol}\"\n data = req.get(url=url, params=params, proxies=proxy)\n\n if \"Will be right back\" in data.text:\n raise RuntimeError(\"Yahoo down\")\n\n data = data.json()\n\n quotes = {}\n\n if 'chart' in data:\n pre_quotes = data['chart']['result'][0]\n indicators = pre_quotes['indicators'][\"quote\"][0]\n quotes['timestamp'] = pre_quotes['timestamp']\n quotes['volume'] = indicators[\"volume\"]\n quotes['open'] = indicators['open']\n quotes['close'] = indicators['open']\n quotes['high'] = indicators['open']\n quotes['low'] = indicators['open']\n\n else:\n raise KeyError(\"No quotes found\")\n\n quotes['index'] = self.timestamp_converter(quotes['timestamp'])\n\n quotes_df = pd.DataFrame.from_dict(quotes).set_index('index').drop('timestamp',axis=1)\n quotes_df.dropna(inplace=True)\n self._historical_prices = quotes_df[['open', 'high', 'low', 'close', 'volume']]\n\n if \"events\" in pre_quotes:\n if \"dividends\" in pre_quotes[\"events\"]:\n dividends_df = pd.DataFrame(list(pre_quotes['events']['dividends'].values()))\n dividends_df['date'] = pd.to_datetime(dividends_df['date'], unit='s')\n dividends_df.set_index('date', inplace=True)\n self._dividends = dividends_df\n\n if 'splits' in pre_quotes[\"events\"]:\n splits_df = pd.DataFrame(list(pre_quotes['events']['splits'].values()))[['date','splitRatio']]\n splits_df['date'] = pd.to_datetime(splits_df['date'], unit='s')\n splits_df.set_index('date',inplace=True)\n self._splits = splits_df\n\n def fundamentals(self, proxy=None, **kwargs):\n\n data = self._scrape_data_to_json(proxy, endpoint='/financials')\n\n # CashFlow\n cash_flow = data.get('cashflowStatementHistory')['cashflowStatements']\n cash_flow_quarterly = data.get('cashflowStatementHistoryQuarterly')['cashflowStatements']\n cash_flow_df = self._create_data_frame(cash_flow, date_col='endDate')\n cash_flow_quarterly_df = self._create_data_frame(cash_flow_quarterly, date_col='endDate')\n self._cash_flow = cash_flow_df\n\n # Balance Sheet\n balance_sheet = data.get('balanceSheetHistory')['balanceSheetStatements']\n balance_sheet_quarterly = data.get('balanceSheetHistoryQuarterly')['balanceSheetStatements']\n balance_sheet_df = self._create_data_frame(balance_sheet, date_col='endDate')\n balance_sheet_quarterly_df = self._create_data_frame(balance_sheet_quarterly, date_col='endDate')\n self._balance_sheet = balance_sheet_df\n\n # Income Statement\n income_statement = data.get('incomeStatementHistory')['incomeStatementHistory']\n income_statement_quarterly = data.get('incomeStatementHistoryQuarterly')['incomeStatementHistory']\n income_statement_df = self._create_data_frame(income_statement, date_col='endDate')\n income_statement_quarterly_df = self._create_data_frame(income_statement_quarterly,date_col='endDate')\n self._income_statement = income_statement_df\n\n # Holders\n data = self._scrape_data_to_json(proxy, endpoint='/holders')\n\n major_holders = data.get('majorDirectHolders')\n if 'holders' in major_holders:\n major_holders = self._create_data_frame(data=major_holders['holders'], date_col='latestTransDate').T\n\n self._holders['major_holders'] = major_holders\n\n insider_holders = data.get('insiderHolders')\n if 'holders' in insider_holders:\n insider_holders = self._create_data_frame(data=insider_holders['holders'],date_col='latestTransDate').T\n\n self._holders['insider_holders'] = insider_holders\n\n if 'summaryDetail' in data:\n self._company_info['summary'] = self._create_data_frame(data.get('summaryDetail'))['raw']\n\n if 'quote_type' in data:\n self._company_info['quote_type'] = self._create_data_frame(data.get('quoteType').items()).T\n\n if 'fundOwnership' in data:\n self._company_info['fund_owner'] = self._create_data_frame(data.get('fundOwnership')['ownershipList'],\n date_col='reportDate').T\n\n insider_transactions = data.get('insiderTransactions')\n if 'transactions' in insider_transactions:\n try:\n insider_transactions = pd.DataFrame(data.get('insiderTransactions')['transactions'])\n insider_transactions = insider_transactions[['filerName', 'transactionText', 'ownership',\n 'startDate', 'value', 'filerRelation', 'shares']]\n for col in ['startDate','value','shares']:\n insider_transactions[col] = insider_transactions[col].apply(\n lambda x: parse_item(x))\n insider_transactions['startDate'] = pd.to_datetime(insider_transactions['startDate'], unit='s')\n insider_transactions.set_index('startDate', inplace=True)\n self._company_info['insider_transactions'] = insider_transactions\n except KeyError:\n self._company_info['insider_transactions'] = pd.DataFrame(data.get('insiderTransactions'))\n\n if 'price' in data:\n try:\n prices = pd.DataFrame(data['price']).T\n except KeyError:\n prices = pd.DataFrame(data['price'])\n self._company_info['prices'] = prices.get('raw')\n\n # KEY STATS\n data = self._scrape_data_to_json(proxy, endpoint='/key-statistics')\n\n if 'defaultKeyStatistics' in data:\n self._key_stats = self._create_data_frame(data.get('defaultKeyStatistics')).get('raw')\n if 'calendarEvents' in data:\n self._events = self._create_data_frame(data.get('calendarEvents')).T\n if 'financialData' in data:\n self._financials = self._create_data_frame(data.get('financialData')).get('raw')\n\n # Analysis\n data = self._scrape_data_to_json(proxy, endpoint='/analysis')\n self._trends['trend_recommendation'] = pd.DataFrame(data.get('recommendationTrend')['trend'])\n self._trends['index_recommendation'] = self._create_data_frame(data.get('indexTrend')['estimates']).T.dropna()\n self._trends['earnings_recommendation'] = self._create_data_frame(data.get('earningsTrend')['trend']).T.dropna()\n self._recommendations = self._create_data_frame(data=data.get('upgradeDowngradeHistory')['history'],date_col='epochGradeDate').T\n\n # sustainability\n data = self._scrape_data_to_json(proxy, endpoint='/sustainability')\n sustainability = {}\n if 'esgScores' in data:\n sus = data.get('esgScores')\n for item in sus:\n if isinstance(sus[item], dict):\n sustainability[item] = sus[item]\n self._company_info['sustainability'] = pd.DataFrame(sustainability).T\n\n self._fundamentals = True\n\n @staticmethod\n def _create_data_frame(data, date_col=None):\n df = pd.DataFrame(data)\n if 'maxAge' in df.columns:\n df.drop('maxAge', axis=1, inplace=True)\n for col in df.columns:\n df[col] = df[col].apply(lambda x: parse_item(x))\n\n if date_col and date_col in df.columns:\n df[date_col] = pd.to_datetime(df[date_col],unit='s')\n df = df.set_index(date_col)\n\n return df.T\n\n def _scrape_data_to_json(self, proxy, endpoint=\"\"):\n if proxy: proxy = proxy_setter(proxy)\n\n url = f\"{self.URL_TO_SCRAPE}/{self._symbol}\" + endpoint\n requests_cache.install_cache(\"yahoo_cache\")\n r = req.get(url=url, proxies=proxy)\n html = r.text\n\n if \"QuoteSummaryStore\" not in html:\n return {}\n\n try:\n html_split = html.split(\"root.App.main =\")[1].split('(this)')[0].split(';\\n}')[0].strip()\n json_data = json.loads(html_split)\n data = json_data['context']['dispatcher']['stores']['QuoteSummaryStore']\n return data\n\n except JSONDecodeError:\n return {}\n\n @staticmethod\n def timestamp_converter(timestamp):\n return [dt.datetime.fromtimestamp(_) for _ in timestamp]\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"liteyahoo/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"547935781","text":"# %%\n# import plotly\n# import plotly.graph_objs as go\n\n# import pandas as pd\n# import numpy as np\n# import json\n# import plotly.express as px\n\n# import requests\n# from bs4 import BeautifulSoup\n# import random\n\n# %%\n\ndef get_medium_articles():\n\n # urls={'medium':'https://medium.com/@jaden09/list/mlops-b4ecfadf718c/archive/{0}/{1:02d}/{2:02d}'}\n\n # def convert_day(day):\n # month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n # m = 0\n # d = 0\n # while day > 0:\n # d = day\n # day -= month_days[m]\n # m += 1\n # return (m, d)\n \n # def get_claps(claps_str):\n # if (claps_str is None) or (claps_str == '') or (claps_str.split is None):\n # return 0\n # split = claps_str.split('K')\n # claps = float(split[0])\n # claps = int(claps*1000) if len(split) == 2 else int(claps)\n # return claps\n\n # url='https://medium.com/@jaden09/list/mlops-b4ecfadf718c'\n # response=requests.get(url)\n # data = []\n\n # Check if the request was successful\n # if response.status_code == 200:\n # Parse the HTML content using Beautiful Soup\n # soup = BeautifulSoup(response.content, 'html.parser')\n # articles = soup.find_all(\n # \"div\",\n # class_=\"postArticle postArticle--short js-postArticle js-trackPostPresentation js-trackPostScrolls\")\n # Find a specific element by tag and class\n # for article in articles:\n # title = article.find(\"h3\", class_=\"graf--title\")\n # if title is None:\n # continue\n # title = title.contents[0]\n # subtitle = article.find(\"h4\", class_=\"graf--subtitle\")\n # subtitle = subtitle.contents[0] if subtitle is not None else ''\n # reading_time = article.find(\"span\", class_=\"readingTime\")\n # reading_time = 0 if reading_time is None else int(reading_time['title'].split(' ')[0])\n # claps = get_claps(article.find_all(\"button\")[1].contents[0])\n # article_url = article.find_all(\"a\")[3]['href'].split('?')[0]\n\n # data.append(title,subtitle,reading_time,claps,article_url)\n\n\n data = {'titles':['Tom', 'Brad', 'Kyle'],\n 'links':['a1', 'a2', 'a3'],\n }\n outputs=zip(tuple(data['titles']),tuple(data['links']))\n return outputs","sub_path":"Python/flask/build_website/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"295130287","text":"from gevent import monkey\n\nmonkey.patch_all()\n\nimport copy\nimport logging\nimport argparse\n\nfrom six.moves import configparser\n\nfrom gevent.server import StreamServer\nfrom pyramid.settings import asbool\n\nimport channelstream.wsgi_app as pyramid_app\nfrom channelstream.gc import gc_conns_forever, gc_users_forever\nfrom channelstream.policy_server import client_handle\nfrom channelstream.ws_app import ChatApplicationSocket\n\nfrom ws4py.server.geventserver import WebSocketWSGIApplication, \\\n WebSocketWSGIHandler, WSGIServer\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\n\nclass RoutingApplication(object):\n def __init__(self, config):\n self.ws_app = WebSocketWSGIApplication(\n handler_cls=ChatApplicationSocket)\n self.wsgi_app = pyramid_app.make_app(config)\n\n def __call__(self, environ, start_response):\n if environ['PATH_INFO'] == '/ws':\n environ['ws4py.app'] = self\n return self.ws_app(environ, start_response)\n\n return self.wsgi_app(environ, start_response)\n\nSHARED_DEFAULTS = {\n 'secret': 'secret',\n 'admin_user': 'admin',\n 'admin_secret': 'admin_secret',\n 'gc_conns_after': 30,\n 'gc_channels_after': 3600 * 72,\n 'wake_connections_after': 5,\n 'allow_posting_from': '127.0.0.1',\n 'port': 8000,\n 'host': '0.0.0.0',\n 'debug': False,\n 'demo': False,\n 'allow_cors': ''\n}\n\n\ndef cli_start():\n config = copy.deepcopy(SHARED_DEFAULTS)\n\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument('-?', '--help', action='help')\n parser.add_argument('-i', '--ini', dest='ini',\n help='config file location',\n default=None)\n parser.add_argument('-s', '--secret', dest='secret',\n help='secret used to secure your requests')\n parser.add_argument('-u', '--admin_username', dest='admin_user',\n help='Administrator username')\n parser.add_argument('-a', '--admin_secret', dest='admin_secret',\n help='secret used to secure your admin_panel')\n parser.add_argument('-host', '--host', dest='host',\n help='host ip on which the server listens to')\n parser.add_argument('-p', '--port', type=int, dest='port',\n help='port on which the server listens to')\n parser.add_argument('-d', '--debug', dest='debug', help='debug')\n parser.add_argument('-e', '--demo', dest='demo', help='demo enabled')\n parser.add_argument('-x', '--allowed_post_ip', dest='allow_posting_from',\n help='comma separated list of ip\\'s '\n 'that can post to server')\n parser.add_argument('-c', '--allow_cors', dest='allow_cors',\n help='comma separated list of domains\\'s '\n 'that can connect to server')\n args = parser.parse_args()\n\n parameters = (\n 'debug', 'port', 'host', 'secret', 'admin_user', 'admin_secret',\n 'demo', 'allow_posting_from', 'allow_cors')\n\n if args.ini:\n parser = configparser.ConfigParser()\n parser.read(args.ini)\n settings = dict(parser.items('channelstream'))\n for key in parameters:\n try:\n config[key] = settings[key]\n except KeyError:\n pass\n else:\n for key in parameters:\n conf_value = getattr(args, key)\n if conf_value:\n config[key] = conf_value\n\n # convert types\n config['debug'] = asbool(config['debug'])\n config['port'] = int(config['port'])\n config['demo'] = asbool(config['demo'])\n\n for key in ['allow_posting_from', 'allow_cors']:\n if not config[key]:\n continue\n try:\n listed = [ip.strip() for ip in config[key].split(',')]\n config[key] = listed\n except ValueError:\n pass\n\n log_level = logging.DEBUG if config['debug'] else logging.INFO\n logging.basicConfig(level=log_level)\n\n url = 'http://{}:{}'.format(config['host'], config['port'])\n\n log.info('Starting flash policy server on port 10843')\n gc_conns_forever()\n gc_users_forever()\n server = StreamServer(('0.0.0.0', 10843), client_handle)\n server.start()\n log.info('Serving on {}'.format(url))\n log.info('Admin interface available on {}/admin'.format(url))\n if config['demo']:\n log.info('Demo enabled, visit {}/demo'.format(url))\n log.warning('\\n\\n!! NEVER run the demo in production !!\\n\\n')\n\n server = WSGIServer((config['host'], config['port']),\n RoutingApplication(config))\n server.serve_forever()\n","sub_path":"channelstream/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"414164068","text":"# -*- coding: utf-8 -*-\n'''\n\tThis module converts tokenize the code sections defined by ... in the anwsers/posts.\n\tCode Token Definition: literals with only [] / {} / ' / \" / , are not tokens\n\t\t\t\t\t\t\tXXX( is token denoting function/method call\n\t\t\t\t\t\t\t.\tis token for special meaning\n\t\t\t\t\t\t\tError messega path -> one token\n\t\t\t\t\t\t\t1.4.6 -> one token\n\tUsage:\n\t\tpython code_tokenizer.py file1.txt ...\n\t\t(This will output file1_codeanno.txt)\n\tToken format:\n\t\tXXX\n'''\nfrom tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP, tok_name, COMMENT, LPAR, RPAR, ERRORTOKEN\nfrom io import BytesIO, StringIO\nimport nltk\nimport codecs\nimport re\nimport sys, os\nimport pdb\n\nsys.path.insert(0, '../utilities')\nfrom utilities import *\nimport hashlib\n\ncode_tag = ['', '']\n\n\n# Main Tokenizer\nclass CodesTokenizer:\n # _sb is the internal string builder storing the annotated(tagged all tokens) \"codes\"\n # _tokens stores the tokens recognized given the \"codes\"\n # _codes is the given codes\n _sb = None\n _tokens = None\n _codes = None\n _reserve_codes = {}\n _processed_codes = None\n\n # Constructor, takes in the codes given, call __setTokens__ to set _tokens\n def __init__(self, codes):\n self._tokens = []\n self._codes = codes\n self._sb = StringBuilder()\n self.__setTokens__()\n\n # detec reserved tokens and store its signature in self._reserve_codes, replace those tokens with their corresponding signature(long int)\n def __ReplaceReserved__(self):\n paths = []\n consec_nums = []\n new_codes = StringBuilder()\n dashs = []\n lts_gts = []\n overall = []\n cookies = []\n # get all paths\n for path in re.finditer(re.compile(r\"(\\w\\:)?((\\\\[^,;\\'\\\" ]+)+|(/[^,;\\'\\\" ]+)+)(\\.\\w+)?\"), self._codes):\n paths.append([path.start(), path.end()])\n\n # get all 1.3.4 liked pattern\n for consec_num in re.finditer(re.compile(r\"\\d+(\\.\\d+)+\"), self._codes):\n consec_nums.append([consec_num.start(), consec_num.end()])\n\n # get all python3-tk liked pattern\n for dash in re.finditer(re.compile(r\"[\\d\\w]+(-[\\d\\w]+)+\"), self._codes):\n dashs.append([dash.start(), dash.end()])\n\n # get all < and >\n for lt_gt in re.finditer(re.compile(r\"&(lt|gt);\"), self._codes):\n lts_gts.append([lt_gt.start(), lt_gt.end()])\n \n # get tokenizer cookie\n for cookie in re.finditer(re.compile(r'[A-Za-z]*coding[:=]', re.ASCII), self._codes):\n cookies.append([cookie.start(), cookie.end() - 1])\n\n # custom union function to union the ranges of different reserved codes\n overall = union([paths, consec_nums, dashs, lts_gts, cookies])\n #\n # import pdb; pdb.set_trace()\n code_anchor = 0\n for start, end in overall:\n new_codes.Append(self._codes[code_anchor: start])\n hash_code = hash_str(self._codes[start: end])\n self._reserve_codes[hash_code] = self._codes[start: end]\n new_codes.Append(' ' + str(hash_code) + ' ')\n code_anchor = end\n if (code_anchor < len(self._codes)):\n new_codes.Append(self._codes[code_anchor:])\n self._processed_codes = new_codes.__str__()\n\n # __setTokens__: Based on _codes given, put all identified tokens to _tokens\n def __setTokens__(self):\n # g = tokenize(BytesIO(self._codes.encode('utf-8')).readline) # tokenize the string\n prev_num = -1\n prev_val = None\n prev_end = -1\n self.__ReplaceReserved__()\n # Split _codes line by line and identify each line\n ss = self._processed_codes.splitlines()\n # pdb.set_trace()\n for line in ss:\n try:\n # call python tokenize.tokenize and get the returned generator g\n g = tokenize(BytesIO(line.encode('utf-8')).readline) # tokenize the string\n try:\n for toknum, tokval, starrt, eend, _ in g:\n # pdb.set_trace()\n chop_start = 0\n chop_end = len(tokval) - 1\n # pdb.set_trace()\n # if the token type is NAME / OP / NUMBER and not only consists of [,)\\-\\\"';\\[\\]|..+]+\n if (toknum in [NAME, OP, NUMBER, ERRORTOKEN] and re.compile( r\"^(?= chop_start + 3 and tokval[chop_start:chop_start + 3] == \"'''\")\n or (chop_end >= chop_start + 3 and tokval[chop_start:chop_start + 3] == '\"\"\"')):\n if (tokval[chop_start] == '#'):\n chop_start += 1\n else:\n chop_start += 3\n if (chop_start < chop_end or (tokval[chop_start] not in ['#', \"'\", '\"'])):\n words = CodesTokenizer(tokval[chop_start:chop_end + 1])._tokens\n if (words):\n self._tokens.extend(words)\n prev_num = toknum\n prev_val = tokval\n prev_end = eend\n except Exception as e:\n # print(\"Error in __setTokens__\", e, line)\n # pdb.set_trace()\n pass\n except Exception as e:\n print(\"Error in __setTokens__\", e, line)\n pdb.set_trace()\n pass\n\n # annotate: Based on _tokens and _codes, annotate the cooresponding tokens with token tags.\n def annotate(self):\n assert self._sb.__str__() == '', \"_sb already has value!\"\n # code_anchor mark the current position in codes, before which has been processed already\n code_anchor = 0\n if (len(self._tokens) == 0):\n return self._codes\n try:\n # For every token, find its starting pos and ending pos in codes, append original codes from code_anchor to starting pos\n #\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tand append annotated(taged) token\n for token in self._tokens:\n search = re.compile(re.escape(token)).search(self._codes, code_anchor)\n # pdb.set_trace()\n search_start = search.start()\n search_end = search.end()\n self._sb.Append(self._codes[code_anchor: search_start])\n self._sb.Append(code_tag[0] + token + code_tag[1])\n # update code_anchor to ending pos of current token\n code_anchor = search_end\n self._sb.Append(self._codes[code_anchor:])\n except Exception as e:\n print(e, \"code: \\n\", self._codes, \"tokens: \\n\", self._tokens)\n pdb.set_trace()\n raise ()\n # return the annotated codes\n return self._sb.__str__()\n\n\ndef main(file):\n source = codecs.open(file, encoding='UTF-8').read()\n code_secs = re.compile(\".*?\", flags=re.S | re.M).finditer(source)\n sb_file = StringBuilder()\n # file_anchor mark the current position in current file, before which has been processed already\n file_anchor = 0\n # iterate all codes area, defined by ... \n for code_sec in code_secs:\n # +6 and -7 to exclude & tags\n code_start = code_sec.start() + 6\n code_end = code_sec.end() - 7\n # Append the origin text from file_anchor to code_start\n sb_file.Append(source[file_anchor: code_start])\n # pdb.set_trace()\n # Init a new CodesTokenizer with codes, append the annotated codes to sb_file\n codes = source[code_start: code_end]\n ct = CodesTokenizer(codes)\n sb_file.Append(ct.annotate())\n file_anchor = code_end\n sb_file.Append(source[file_anchor:])\n file_sep = os.path.splitext(file)\n with open(file_sep[0] + \"_codeAnno\" + file_sep[1], 'w') as new_file:\n new_file.write(sb_file.__str__())\n\n\nif __name__ == '__main__':\n # take in 1+ file(s) for processing\n for file in sys.argv[1:]:\n main(file)\n","sub_path":"tokenizer/code_tokenizer.py","file_name":"code_tokenizer.py","file_ext":"py","file_size_in_byte":9855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"503690115","text":"# Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.\n#\n# This file is part of Navitia,\n# the software to build cool stuff with public transport.\n#\n# Hope you'll enjoy and contribute to this project,\n# powered by Canal TP (www.canaltp.fr).\n# Help us simplify mobility and open public transport:\n# a non ending quest to the responsive locomotion way of traveling!\n#\n# LICENCE: 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 published by\n# the Free Software Foundation, either version 3 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 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# Stay tuned using\n# twitter @navitia\n# IRC #navitia on freenode\n# https://groups.google.com/d/forum/navitia\n# www.navitia.io\nfrom datetime import datetime, timedelta\nimport json\n\nfrom bson import json_util\nfrom flask import Response\nfrom flask_restful import Resource, reqparse\nfrom tartare import mongo\n\n\ndef datetime_type(value: str) -> datetime:\n _datetime = datetime.strptime(value, '%Y-%m-%d')\n\n return reset_time(_datetime)\n\n\ndef reset_time(_datetime: datetime) -> datetime:\n return _datetime.replace(minute=0, hour=0, second=0, microsecond=0)\n\n\nclass RequestLogs(Resource):\n def __init__(self) -> None:\n\n self.parsers = reqparse.RequestParser()\n self.parsers.add_argument('start_date', type=datetime_type, default=None, location='args')\n\n default_date = datetime.utcnow()\n default_date = reset_time(default_date)\n self.parsers.add_argument('end_date', type=datetime_type, default=default_date, location='args')\n\n def get(self) -> Response:\n args = self.parsers.parse_args()\n\n start_date = args['start_date']\n end_date = args['end_date']\n\n if not start_date:\n start_date = end_date\n\n end_date += timedelta(days=1)\n\n results = mongo.db['logs'].aggregate([\n {\n \"$match\": {\n \"date\": {\n \"$gte\": start_date,\n \"$lt\": end_date\n }\n },\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"date\": {\n \"$dateToString\": {\n \"format\": \"%Y-%m-%dT%H:%M:%S.%LZ\",\n \"date\": \"$date\",\n }\n },\n \"request\": 1,\n \"response\": 1,\n }\n }\n ])\n\n return Response(\n json.dumps(list(results), default=json_util.default),\n mimetype='application/json'\n )\n","sub_path":"tartare/interfaces/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"651381185","text":"import torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport glob\nfrom PIL import Image\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport segmentation_models_pytorch as smp\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport numpy as np\nfrom utils import load_checkpoint\nimport cv2\nfrom model import get_model\n\n###Hyperparameter\nTEST_DATA_DIR = '/tmp/pycharm_project_677/data/origins/suichang_round1_test_partA_210120/suichang_round1_test_partA_210120'\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\nIMAGE_HEIGHT = 256\nIMAGE_WIDTH = 256\nCHECKPOINT = 'best_checkpoint.pth.tar'\n\n\ndef test(model, test_data_dir, transform=None, device='cuda'):\n model.eval()\n\n for idx, name in enumerate(tqdm(glob.glob(os.path.join(test_data_dir, '*.tif'))[:])):\n im = Image.open(name)\n image_RGB = np.array(im)[:, :, :-1]\n if transform is not None:\n image_RGB = transform(image=image_RGB)\n image_RGB = image_RGB['image']\n\n with torch.no_grad():\n image_RGB = image_RGB.unsqueeze(0).to(device=device)\n score = model(image_RGB).clone().cpu().softmax(1).numpy()\n\n score_sigmoid = score[0].argmax(0) + 1\n assert score_sigmoid.max() <= 10, \"category pred is wrong, bigger than 10\"\n assert score_sigmoid.min() >= 1, \"category pred is wrong, smaller than 1\"\n\n cv2.imwrite('results/' + os.path.basename(name).replace('.tif', '.png'), score_sigmoid)\n\n\ndef complicated_test(model, test_data_dir, transform_dict=None, device='cuda'):\n model.eval()\n\n for idx, name in enumerate(tqdm(glob.glob(os.path.join(test_data_dir, '*.tif'))[:])):\n im = Image.open(name)\n image_org = np.array(im)[:, :, :-1]\n if transform_dict is not None:\n score_list = []\n res = 0\n\n for method, transform in transform_dict.items():\n image_RGB = transform(image=image_org)\n image_RGB = image_RGB['image']\n with torch.no_grad():\n image_RGB = image_RGB.unsqueeze(0).to(device=device)\n score = model(image_RGB).clone().cpu().numpy()[0]\n\n if method == 'HorizontalFlip':\n score = np.flip(score, 2)\n\n if method == 'VerticalFlip':\n score = np.flip(score, 1)\n\n if method == 'Transpose':\n score = score.transpose((0, 2, 1))\n\n score_list.append(score)\n\n for score in score_list:\n res = res + score\n res = res / len(score_list)\n score_sigmoid = res.argmax(0) + 1\n assert score_sigmoid.max() <= 10, \"category pred is wrong, bigger than 10\"\n assert score_sigmoid.min() >= 1, \"category pred is wrong, smaller than 1\"\n\n cv2.imwrite('results/' + os.path.basename(name).replace('.tif', '.png'), score_sigmoid)\n\n\nif __name__ == \"__main__\":\n model = get_model().to(device=DEVICE)\n\n load_checkpoint(torch.load(CHECKPOINT), model)\n\n test_transform = A.Compose(\n [\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n A.Normalize(\n mean=[0.625, 0.448, 0.688],\n std=[0.131, 0.177, 0.101],\n max_pixel_value=255.0\n ),\n ToTensorV2(),\n ]\n )\n\n test_complicated_transfom1 = A.Compose(\n [\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n A.Normalize(\n mean=[48.5125, 60.0272, 56.5723],\n std=[32.3620, 31.1285, 30.2979],\n max_pixel_value=255.0\n ),\n A.HorizontalFlip(p=1),\n ToTensorV2(),\n ]\n )\n\n test_complicated_transfom2 = A.Compose(\n [\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n A.Normalize(\n mean=[48.5125, 60.0272, 56.5723],\n std=[32.3620, 31.1285, 30.2979],\n max_pixel_value=255.0\n ),\n A.VerticalFlip(p=0.5),\n ToTensorV2(),\n ]\n )\n test_complicated_transfom3 = A.Compose(\n [\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n A.Normalize(\n mean=[48.5125, 60.0272, 56.5723],\n std=[32.3620, 31.1285, 30.2979],\n max_pixel_value=255.0\n ),\n A.Transpose(p=1),\n ToTensorV2(),\n ]\n )\n method = ['original', 'HorizontalFlip', 'VerticalFlip', 'Transpose']\n transform_complicated = [test_transform, test_complicated_transfom1, test_complicated_transfom2,\n test_complicated_transfom3]\n transform_dict = dict(zip(method, transform_complicated))\n\n test(model, TEST_DATA_DIR, test_transform, device=DEVICE)\n # complicated_test(model, TEST_DATA_DIR, transform_dict=transform_dict,device=DEVICE)\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"543443087","text":"#utils.py\n#Author: Nabin\n\nimport pandas as pd\nimport pickle\nimport socket\nfrom config import *\n\nroles={\n '1': \"Admin\",\n '2': \"Doctor\",\n '3': \"Staff\",\n '4': \"Patient\",\n 1: \"Admin\",\n 2: \"Doctor\",\n 3: \"Staff\",\n 4: \"Patient\"\n}\n\n\n############# Client side utility methods for administrator ###############\n\ndef admin_view_users(choice, is_valid):\n message = {}\n message[\"user_type\"]=1\n message[\"is_valid\"] = is_valid\n message[\"choice\"] = choice\n message = pickle.dumps(message, -1)\n\n # create a TCP socket to connect to coordinator\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # connect to coordinator\n sock.connect((COORDINATOR_IP, COORDINATOR_MSG_PORT))\n #send data to coordinator\n sock.sendall(bytes(message))\n\n # block till coordinator replies back\n result = sock.recv(2048)\n sock.close()\n result = pickle.loads(result)\n result = pd.DataFrame().from_dict(data=result, orient='index')\n print(\"Here is the list of all users:\")\n print(result)\n print(\"-\"*20)\n print(\"Choose Again: \")\n\n\ndef admin_add_new_user(choice,is_valid):\n message = {}\n message[\"user_type\"] = 1\n message[\"is_valid\"] = is_valid\n message[\"choice\"] = choice\n print(\"Enter the details for the new user\")\n message[\"new_user_type\"]=input(\"enter user type(1-Admin, 2-Doctor,\\n 3-Staff): \")\n message[\"new_user_name\"]=input(\"enter user name :\")\n message[\"new_user_pwd\"]=input('enter password:')\n\n message = pickle.dumps(message, -1)\n\n # create a TCP socket to connect to coordinator\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # connect to coordinator\n sock.connect((COORDINATOR_IP, COORDINATOR_MSG_PORT))\n # send data to coordinator\n sock.sendall(bytes(message))\n\n # block till coordinator replies back\n result = sock.recv(2048)\n sock.close()\n result = pickle.loads(result)\n\n print(\"Successfully added follwing user\")\n print(\"user name: {}\".format(result[\"user_name\"]))\n print(\"user type: {}\".format(result[\"user_type\"]))\n print(\"-\" * 20)\n print(\"Choose Again: \")\n\ndef admin_delete_user(choice, is_valid):\n message={}\n message[\"user_type\"] = 1\n message[\"is_valid\"] = is_valid\n message[\"choice\"] = choice\n print(\"Enter user type and user name to delete \")\n message[\"del_user_type\"] = input(\"enter user type(1-Admin, 2-Doctor, 3-Staff): \")\n message[\"del_user_name\"] = input(\"enter user name :\")\n\n message = pickle.dumps(message, -1)\n\n # create a TCP socket to connect to coordinator\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # connect to coordinator\n sock.connect((COORDINATOR_IP, COORDINATOR_MSG_PORT))\n # send data to coordinator\n sock.sendall(bytes(message))\n\n # block till coordinator replies back\n result = sock.recv(2048)\n sock.close()\n result = pickle.loads(result)\n\n print(\"Successfully deleted follwing user\")\n print(\"user name: {}\".format(result[\"user_name\"]))\n print(\"user type: {}\".format(result[\"user_type\"]))\n print(\"-\" * 20)\n print(\"Choose Again: \")\n\n\n\n\ndef admin_choice():\n print(\"1. View all users\")\n print(\"2. Add new user\")\n print(\"3. Delete existing user\")\n print(\"4. Logout\")\n choice = input(\"select one:\")\n try:\n choice=int(choice)\n assert choice >=1 and choice <=4\n return choice\n except:\n print(\"invalid choice\")\n admin_choice()\n\n\ndef admin_activities(admin_name):\n print(\"Please choose one of the following\".format(admin_name))\n\n while True:\n choice = admin_choice()\n\n if choice==1:\n admin_view_users(choice=1, is_valid=True)\n\n elif choice == 2:\n admin_add_new_user(choice=2, is_valid=True)\n\n elif choice == 3:\n admin_delete_user(choice=3, is_valid=True)\n\n elif choice==4:\n print(\"Successfully logged out\")\n break\n else:\n print(\"Invalid Choice\")\n\n\n############# Server side utility methods for administrator ###############\n\n\ndef verify_login(user_type, user_name, password, server_users_file, server_patients_file):\n valid_user = False\n if str(user_type)=='4':#for patients username=name and password=patientid\n patients=pd.read_csv(server_patients_file).values\n for patient in patients:\n if str(patient[1]) == str(user_name) and \\\n str(patient[0]) == str(password):\n valid_user=True\n else:#for other users\n users = pd.read_csv(server_users_file).values\n for user in users:\n if str(user[1]) == str(user_type) and \\\n str(user[2]) == str(user_name) and \\\n str(user[3]) == str(password):\n valid_user = True\n\n return valid_user\n\n\ndef show_user_details(server_users_file):\n df = pd.read_csv(server_users_file)\n return df[['user_id','user_name', 'role']].to_dict('index')\n\n\n\ndef add_user(server_users_file, user_type,\n user_name, password):\n df = pd.read_csv(server_users_file)\n user_id=list(df[\"user_id\"])[-1]+1\n\n # add new entry\n df.loc[len(df)] = [user_id, user_type, user_name, password, roles[user_type]]\n df.to_csv(server_users_file, index=False)\n\n result={}\n result[\"user_type\"]=roles[int(user_type)]\n result[\"user_name\"]= user_name\n return result\n\n\ndef remove_user(server_users_file,\n user_type, user_name):\n df=pd.read_csv(server_users_file)\n new_df = df[~((df['user_type']==int(user_type)) & (df['user_name']==str(user_name)))]\n new_df.to_csv(server_users_file, index=False)\n result={}\n result[\"user_type\"]=roles[user_type]\n result[\"user_name\"]= user_name\n return result\n","sub_path":"admin_utils.py","file_name":"admin_utils.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"177664111","text":"\n\n\n\nimport numpy as np\nimport pickle\nfrom os.path import expanduser\nhome = expanduser(\"~\")\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.utils.data\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\n\n\n\nclass RNN(nn.Module):\n def __init__(self, specs):\n super(RNN, self).__init__()\n\n torch.manual_seed(1)\n\n\n self.input_size = specs['input_size']\n self.output_size = specs['output_size']\n self.z_size = specs['z_size']\n\n\n\n # self.update_net = torch.nn.Sequential(\n # torch.nn.Linear(self.input_size+self.z_size, specs['update_net'][0]),\n # torch.nn.ReLU(),\n # torch.nn.Linear(specs['update_net'][0], specs['update_net'][1]),\n # torch.nn.ReLU(),\n # torch.nn.Linear(specs['update_net'][1], self.z_size),\n # )\n\n\n self.update_net = torch.nn.Sequential(\n torch.nn.Linear(self.input_size+self.z_size, 100),\n torch.nn.ReLU(),\n torch.nn.Linear(100, 100),\n torch.nn.ReLU(),\n torch.nn.Linear(100, self.z_size),\n )\n\n # self.output_net = torch.nn.Sequential(\n # torch.nn.Linear(self.z_size, specs['output_net'][0]),\n # torch.nn.ReLU(),\n # torch.nn.Linear(specs['output_net'][0], specs['output_net'][1]),\n # torch.nn.ReLU(),\n # torch.nn.Linear(specs['output_net'][1], self.output_size),\n # )\n\n\n self.output_net = torch.nn.Sequential(\n torch.nn.Linear(self.z_size, 30),\n torch.nn.ReLU(),\n torch.nn.Linear(30, 30),\n torch.nn.ReLU(),\n torch.nn.Linear(30, self.output_size),\n )\n\n\n\n def init_state(self, batch_size):\n\n # self.state = Variable(torch.zeros(batch_size, self.z_size))\n return Variable(torch.zeros(batch_size, self.z_size))\n\n\n def output_prediction(self, state):\n '''\n z: [B,Z]\n out: [B,O]\n '''\n return self.output_net(state) \n\n\n def update_state(self, x, state):\n\n # print (x.size()) #[B,X]\n # print (self.state.size()) #[B,Z]\n\n x_z = torch.cat((x,state), dim=1) #[B,x+z]\n new_state = self.update_net(x_z)\n\n # return new_state\n # self.state = new_state #does this erase the grad??\n return new_state\n\n\n def train(self, data_x, data_y, batch_size):\n\n np.random.seed(0)\n\n n_data = data_x.shape[0]\n\n timesteps = 4\n\n # convert to pytorch\n data_x = Variable(torch.FloatTensor(data_x))\n data_y = Variable(torch.LongTensor(data_y))\n\n\n loss_func = nn.CrossEntropyLoss()\n self.optimizer = optim.Adam(self.parameters(), lr=.001)\n\n\n for p in self.parameters():\n print (p.size())\n fds\n\n\n\n for step_ in range(10000):\n\n\n # make a batch of sequences\n batch_x = []\n batch_y = []\n for i in range(batch_size):\n seq = []\n for t in range(timesteps):\n\n data_index = np.random.randint(n_data)\n seq.append(data_x[data_index])\n\n if t == 0:\n label = data_y[data_index]\n\n batch_x.append(torch.stack(seq, dim=0))\n batch_y.append(label)\n\n batch_x = torch.stack(batch_x, dim=1) #[T,B,X]\n # batch_y = torch.unsqueeze(torch.stack(batch_y, dim=0), dim=0) #[1,B,1]\n batch_y = torch.squeeze(torch.stack(batch_y, dim=0)) #[B,1]\n # print (batch_x.size())\n # print (batch_y.size())\n\n\n\n\n # Run model\n state = self.init_state(batch_size)\n for t in range(timesteps):\n state = self.update_state(batch_x[t], state)\n\n pred = self.output_prediction(state) #[B,Y]\n # print (pred.size())\n\n loss = loss_func(pred, batch_y) #[1]\n\n # print (loss.size())\n # fsad\n\n if step_ %100 == 0:\n print (step_, loss.data.numpy())\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # def step(self):\n\n\n #update state\n\n #output value\n\n # def reset_state():\n\n # self.state = Variable(pytorch.zeros())\n\n # def encode(self, x, a, prev_z):\n # '''\n # x: [B,X]\n # a: [B,A]\n # prev_z: [P,B,Z]\n # '''\n\n # out = torch.cat((x,a), 1) #[B,XA]\n # out = torch.unsqueeze(out, 0) #[1,B,XA]\n # out = out.repeat(self.k, 1, 1)#.float() #[P,B,XA]\n # out = torch.cat((out,prev_z), 2) #[P,B,XAZ]\n # out = out.view(self.k*self.B, self.input_size+self.action_size+self.z_size) #[P*B,XAZ]\n # out = self.encoder_net(out) #[P*B,Z*2]\n # out = out.view(self.k, self.B, 2*self.z_size) #[P,B,XAZ]\n # mean = out[:,:,:self.z_size]\n # logvar = out[:,:,self.z_size:]\n # return mean, logvar\n\n\n # def sample(self, mu, logvar):\n # '''\n # mu, logvar: [P,B,Z]\n # '''\n # eps = Variable(torch.FloatTensor(self.k, self.B, self.z_size).normal_()) #[P,B,Z]\n # z = eps.mul(torch.exp(.5*logvar)) + mu #[P,B,Z]\n # # logpz = lognormal(z, Variable(torch.zeros(self.k, self.B, self.z_size)), \n # # Variable(torch.zeros(self.k, self.B, self.z_size))) #[P,B]\n # logqz = lognormal(z, mu, logvar)\n # return z, logqz\n\n\n\n\n # def transition_prior(self, prev_z, a):\n # '''\n # prev_z: [P,B,Z]\n # a: [B,A]\n # '''\n # a = torch.unsqueeze(a, 0) #[1,B,A]\n # out = a.repeat(self.k, 1, 1) #[P,B,A]\n # out = torch.cat((out,prev_z), 2) #[P,B,AZ]\n # out = out.view(-1, self.action_size+self.z_size) #[P*B,AZ]\n # out = self.transition_net(out) #[P*B,Z*2]\n # out = out.view(self.k, self.B, 2*self.z_size) #[P,B,2Z]\n # mean = out[:,:,:self.z_size] #[P,B,Z]\n # logvar = out[:,:,self.z_size:]\n # return mean, logvar\n\n\n # def forward(self, x, a, k=1, current_state=None):\n # '''\n # x: [B,T,X]\n # a: [B,T,A]\n # output: elbo scalar\n # '''\n \n # self.B = x.size()[0]\n # self.T = x.size()[1]\n # self.k = k\n\n # a = a.float()\n # x = x.float()\n\n # # log_probs = [[] for i in range(k)]\n # # log_probs = []\n # logpxs = []\n # logpzs = []\n # logqzs = []\n\n\n # weights = Variable(torch.ones(k, self.B)/k)\n # # if current_state==None:\n # prev_z = Variable(torch.zeros(k, self.B, self.z_size))\n # # else:\n # # prev_z = current_state\n # for t in range(self.T):\n # current_x = x[:,t] #[B,X]\n # current_a = a[:,t] #[B,A]\n\n # #Encode\n # mu, logvar = self.encode(current_x, current_a, prev_z) #[P,B,Z]\n # #Sample\n # z, logqz = self.sample(mu, logvar) #[P,B,Z], [P,B]\n # #Decode\n # x_hat = self.decode(z) #[P,B,X]\n # logpx = log_bernoulli(x_hat, current_x) #[P,B]\n # #Transition/Prior prob\n # prior_mean, prior_log_var = self.transition_prior(prev_z, current_a) #[P,B,Z]\n # logpz = lognormal(z, prior_mean, prior_log_var) #[P,B]\n\n\n\n\n\n\n # log_alpha_t = logpx + logpz - logqz #[P,B]\n # log_weights_tmp = torch.log(weights * torch.exp(log_alpha_t))\n\n # max_ = torch.max(log_weights_tmp, 0)[0] #[B]\n # log_p_hat = torch.log(torch.sum(torch.exp(log_weights_tmp - max_), 0)) + max_ #[B]\n\n # # p_hat = torch.sum(alpha_t,0) #[B]\n # normalized_alpha_t = log_weights_tmp - log_p_hat #[P,B]\n\n # weights = torch.exp(normalized_alpha_t) #[P,B]\n\n # #if resample\n # if t%2==0:\n # # print weights\n # #[B,P] indices of the particles for each bactch\n # sampled_indices = torch.multinomial(torch.t(weights), k, replacement=True).detach()\n # new_z = []\n # for b in range(self.B):\n # tmp = z[:,b] #[P,Z]\n # z_b = tmp[sampled_indices[b]] #[P,Z]\n # new_z.append(z_b)\n # new_z = torch.stack(new_z, 1) #[P,B,Z]\n # weights = Variable(torch.ones(k, self.B)/k)\n # z = new_z\n\n # logpxs.append(logpx)\n # logpzs.append(logpz)\n # logqzs.append(logqz)\n # # log_probs.append(logpx + logpz - logqz)\n # prev_z = z\n\n\n\n # logpxs = torch.stack(logpxs) \n # logpzs = torch.stack(logpzs)\n # logqzs = torch.stack(logqzs) #[T,P,B]\n\n # logws = logpxs + logpzs - logqzs #[T,P,B]\n # logws = torch.mean(logws, 0) #[P,B]\n\n # # elbo = logpx + logpz - logqz #[P,B]\n\n # if k>1:\n # max_ = torch.max(logws, 0)[0] #[B]\n # elbo = torch.log(torch.mean(torch.exp(logws - max_), 0)) + max_ #[B]\n # elbo = torch.mean(elbo) #over batch\n # else:\n # elbo = torch.mean(logws)\n\n # # print log_probs[0]\n\n\n # # #for printing\n # logpx = torch.mean(logpxs)\n # logpz = torch.mean(logpzs)\n # logqz = torch.mean(logqzs)\n # # self.x_hat_sigmoid = F.sigmoid(x_hat)\n\n # # elbo = torch.mean(torch.stack(log_probs)) #[1]\n # # elbo = logpx + logpz - logqz\n\n # return elbo, logpx, logpz, logqz\n\n\n\n","sub_path":"SL2/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"162817827","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nr'''\n调用Web API并处理结果,找出GitHub上星级最高的Python项目\n并进行数据可视化\n'''\nimport requests\nimport pygal\nfrom pygal.style import LightColorizedStyle as LCS, LightenStyle as LS\n\n# 执行API调用并储存响应\nurl = 'https://api.github.com/search/repositories?q=language:python&sort=stars'\nr = requests.get(url)\nprint('Status code:', r.status_code)\n# 将API响应存储在一个变量中\nresponse_dict = r.json()\nprint('Total repositories:', response_dict['total_count'])\n# 探索有关仓库的信息\nrepo_dicts = response_dict['items']\n# 仓库名和星数集合\nnames, stars = [], []\nfor repo_dict in repo_dicts:\n names.append(repo_dict['name'])\n stars.append(repo_dict['stargazers_count'])\n# 数据可视化\nmy_style = LS('#336699', base_style=LCS) # 图形基色设置为深蓝色\nchart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False) # x_label_rotation=45-代表让标签绕x 轴旋转45度;show_legend=False-代表隐藏图例\nchart.title = 'Most-Starred Python Projects on GitHub'\nchart.x_labels = names\nchart.add('Stars', stars)\n# 渲染成SVG文件\nchart.render_to_file('images/python_repository_github_1.svg')\n","sub_path":"webapi/github/python_repository_github_2.py","file_name":"python_repository_github_2.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"146538321","text":"class Transport(object):\n def __init__(self, id, account, FC, customer, date, catty, income, cost):\n self.id = id\n self.account =account\n self.FC = FC\n self.customer =customer\n self.date = date\n self.catty = catty\n self.income = income\n self.cost = cost\n ","sub_path":"dbproject/Transport.py","file_name":"Transport.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"35223181","text":"# %%\nimport gym\n\n# %%\nenv = gym.make('CartPole-v0')\n\ntotal_reward = 0.\ntotal_steps = 0\nenv.reset()\n\nfor _ in range(1000):\n env.render()\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n if done:\n env.reset()\n\nenv.close()\n# %%\n","sub_path":"models/reinforcement/gym_tutorial.py","file_name":"gym_tutorial.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"104608257","text":"\"\"\" \n@Author: huuuuusy\n@GitHub: https://github.com/huuuuusy\n系统: Ubuntu 18.04\nIDE: VS Code 1.39\n工具: python == 3.7.3\n\"\"\"\n\n\"\"\"\n思路:\n 滑动窗口\n参考:\n https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-dong-chuang-kou-by-powcai/\n结果:\n 执行用时 : 96 ms, 在所有 Python3 提交中击败了98.03%的用户\n 内存消耗 : 14.4 MB, 在所有 Python3 提交中击败了15.28%的用户\n\"\"\"\n\nclass Solution:\n def minWindow(self, s, t):\n from collections import defaultdict\n lookup = defaultdict(int) # 存储当前需要检索的字母个数\n for alp in t: # 先将t中的字母存入lookup;t中的字母初始个数是1,则其他字母初始个数为0\n lookup[alp] += 1\n start = 0 # 滑动窗口的起始\n end = 0\n min_len = float('inf') \n counter = len(t) # counter用来统计t中的字母是否都在窗口中,若都在,则counter=0\n res = \"\"\n while end < len(s):\n if lookup[s[end]] > 0: # 如果lookup中s[end]的值大于0,说明是t中的字母,此时窗口中包含t中的一个字母,所以counter可以减一\n counter -= 1\n lookup[s[end]] -= 1 # 将lookup中当前字母的个数减一,lookup中存储的是该字母有几个出现在窗口中,和初始值的差值表示出现的个数\n end += 1\n while counter == 0: # 此时表明t中所有字母均在窗口中\n if min_len > end - start: # 更新min_len\n min_len = end - start\n res = s[start:end] # 更新res\n if lookup[s[start]] == 0:\n counter += 1\n lookup[s[start]] += 1 # 移动窗口起点\n start += 1\n return res\n \n\n\nif __name__ == \"__main__\":\n s = \"ADOBECODEBANC\"\n t = \"ABC\"\n answer = Solution().minWindow(s, t)\n print(answer)\n","sub_path":"LeetCode/python-R1/0076-最小覆盖子串D/V1.py","file_name":"V1.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"428205959","text":"import numpy\r\nimport numpy\r\nn = int(input())\r\nar = []\r\nar1 = []\r\nfor i in range(n):\r\n row = list(map(int,input().split()))\r\n ar.append(row)\r\nx = numpy.array(ar)\r\nfor i in range(n):\r\n row = list(map(int,input().split()))\r\n ar1.append(row)\r\ny = numpy.array(ar1)\r\nprint(numpy.dot(x,y))","sub_path":"Dot and Cross.py","file_name":"Dot and Cross.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"133756011","text":"from optparse import OptionParser\nimport enchant\n\nSENSSTRING = \"#$@&%*!\"\n\nclass piglatin_error(Exception):\n \"\"\"\n Custom Exception\n \"\"\"\n def __init__(self, message=\"\"):\n Exception.__init__(self, message)\n\ndef main():\n \"\"\"\n Main function, where we handle the parsing\n \"\"\"\n parser = OptionParser()\n parser.add_option(\"-r\", \"--reverse\", dest=\"reverse\",\n action=\"store_true\", default=False,\n help=\"translate from PigLatin to English\", metavar=\"STRING\")\n\n (options, args) = parser.parse_args()\n\n if len(args) == 0:\n raise piglatin_error(\"No input string\")\n\n # take first argument from cmdline\n sentence = args[0]\n\n if len(sentence) == 0:\n raise piglatin_error(\"Input string is empty\")\n\n if options.reverse:\n print(sentencetoenglish(sentence))\n else:\n print(sentencetopiglatin(sentence))\n\ndef checklastcharacter(word):\n \"\"\"\n Check whether the last character is \". or !, or...\".\n\n ARQS:\n word (string): The word to be checked.\n \"\"\"\n if word.isalpha():\n return word, \"\"\n original_word = word\n i = 0\n while not word[-1].isalpha():\n i += 1\n word = word[0:-1]\n if len(word) == 0:\n return original_word, \"\"\n\n return word, original_word[-i:]\n\ndef wordtopiglatin(word):\n \"\"\"Translates ONE word to Pig Latin.\n\n :word -- (string) The word that should be translated.\n \"\"\"\n\n if not isinstance(word, str):\n raise piglatin_error(\"Not instance of str\")\n\n if len(word) == 0:\n return \"\"\n\n # We filter out the sensitive words\n pwl = enchant.request_pwl_dict(\"senswords.txt\")\n if pwl.check(word):\n return SENSSTRING\n\n vowes = 'aeiou'\n vowend = 'way'\n otherend = 'ay'\n\n word, ending = checklastcharacter(word.lower())\n\n if word[0] in vowes:\n word += vowend + ending\n return word\n\n for i in range(0, len(word)):\n if word[i] not in vowes:\n continue\n word = word[i:] + word[0:i] + otherend + ending\n break\n\n return word\n\ndef sentencetopiglatin(sentence):\n \"\"\"Translates a sentence to Pig Latin.\n\n :sentence -- (string) The sentence that should be translated.\n \"\"\"\n\n if not isinstance(sentence, str):\n return \"\"\n\n sentence = sentence.split(\" \")\n pigsentence = \"\"\n for word in sentence:\n pigsentence += wordtopiglatin(word) + \" \"\n\n return pigsentence.strip()\n\ndef wordtoenglish(word):\n \"\"\"\n We use the English dict to try reverse translating the word.\n \"\"\"\n endict = enchant.Dict('en_GB')\n\n if len(word) == 0:\n return \"\"\n\n original_word, ending = checklastcharacter(word)\n\n if endict.check(original_word):\n return word\n\n # edge-case: if ending on way, we are quite confident that\n # the word stats with a vowel (and can just remove \"way\")\n if original_word[-3:] == 'way':\n if endict.check(original_word[0:-3]):\n return original_word[0:-3] + ending\n\n test_word = original_word[0:-2]\n\n # we are moving one consonent from the end to the start and checking\n # the dictionary for a match. Else iterate and move next\n for _ in range(1, len(test_word)):\n test_word = test_word[-1:] + test_word[0:len(test_word)-1]\n if endict.check(test_word):\n return test_word + ending\n\n # if no match is found we return the original word + the ending\n return original_word + ending\n\ndef sentencetoenglish(sentence):\n \"\"\"\n We try to translate a sentence back to English using the dictionary.\n \"\"\"\n\n if not isinstance(sentence, str):\n return \"\"\n\n sentence = sentence.split(\" \")\n pigsentence = \"\"\n\n for word in sentence:\n pigsentence += wordtoenglish(word) + \" \"\n\n return pigsentence.strip()\n\nif __name__ == \"__main__\":\n try:\n main()\n except piglatin_error as err:\n print(\"An error occured: {}\".format(err))\n","sub_path":"PigLatin.py","file_name":"PigLatin.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"652498632","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 16 21:21:15 2020\r\n\r\n@author: erolc\r\n\"\"\"\r\n\r\n#import libraries\r\nimport os\r\nimport json\r\n\r\n#functions for reading and writing data \r\nmy_directory = os.getcwd()\r\ninp_path,out_path = my_directory+\"\\\\in\\\\in.txt\",my_directory+\"\\\\out\\\\out.json\"\r\ndef read_input(input_path):\r\n with open(input_path,encoding = \"utf8\") as file:\r\n result = file.readlines()\r\n return result\r\ndef write_output(output_path, finaldata):\r\n with open(output_path, \"w\",encoding = \"utf8\") as jsondata:\r\n json.dump(finaldata,jsondata, ensure_ascii=False)\r\ndata = read_input(inp_path) \r\n\r\n\"\"\"\r\nTask-1:\r\nIn this HW, I will build hash table data structure to keep my data more reachable.\r\nHash tables are very efficient for most of the data analysis tasks. Reaching \r\nto the value of any element of the hash table keys has O(1) time complexity. \r\n\r\nTask-2:\r\nSince JSON format uses list of hash tables, this is the best format for me. \r\nAlso, I am experienced in this format. Thus, I chose JSON to export my data.\r\n\r\n\r\nTask-3:\r\nIn my course project, I want to create a new dataset from scratch. This will be\r\na clear and well structured dataset. Thus, I am working on a different dataset for homework\r\nand I do not need any meta-data at this stage.\r\n\"\"\"\r\n\r\ndef structure_data(data=data):\r\n result,i = {},1\r\n for e in data: # Basically, I trace my data and create lists for dependency structures.\r\n result[i] = {}\r\n list_of_analysis = e[:-1].split(\"(\")\r\n result[i][list_of_analysis[0]] = [] #Working on the first element.\r\n temp = list_of_analysis[0]\r\n for f in list_of_analysis[1:-1]: #Since I used split function, first and last elements will be outliers. I should work on them separately. This is why [1:-1]\r\n words_and_tags = f.split()\r\n result[i][temp].append((words_and_tags[2][:-1],words_and_tags[0]))\r\n temp = words_and_tags[3]\r\n if temp not in result[i]:\r\n result[i][temp] = []\r\n words_and_tags = list_of_analysis[-1].split() #Working on the last element.\r\n result[i][temp].append((words_and_tags[2][:-1],words_and_tags[0]))\r\n i += 1\r\n return result\r\n\r\nwrite_output(out_path,structure_data())\r\n\r\n\r\n \r\n ","sub_path":"assignments/2319606/part_3/part_3.py","file_name":"part_3.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"486485888","text":"from django.db.models import Q, Count\nfrom django.shortcuts import render, get_object_or_404\nfrom rest_framework import generics\nfrom rest_framework.response import Response\n#from .models import Journal, Category\n#from .serializers import JournalSerializer\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib import messages\n#from django.views.generic import ListView\nimport bcrypt\nfrom .models import User,UserManager,PropertyMaster,Property_TypeMaster,TypeMaster\nfrom django.db.models import Q, Count\nfrom django.shortcuts import render, get_object_or_404\n#from .serializers import JournalSerializer\nimport pandas as pd\nimport json\nimport numpy as np\nfrom datetime import datetime\nfrom django.core import mail\nfrom django.template.loader import render_to_string\n\nfrom django.utils.html import strip_tags\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n# Create your views here.\nimport functools\n\ndef index(request):\n return render(request, 'index2.html')\ndef register(request):\n errors = User.objects.validator(request.POST)\n if len(errors):\n for tag, error in errors.items():\n messages.error(request, error, extra_tags=tag)\n return redirect('/')\n\n # hashed_password = bcrypt.hashpw(request.POST['password'].encode('utf-8'), bcrypt.gensalt())\n # password= User.objects.create()\n user = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], password=request.POST['password'], email=request.POST['email'])\n user.save()\n request.session['id'] = user.id\n return redirect('/success')\n\n\ndef disjunction(*conditions):\n return functools.reduce(np.logical_or, conditions)\n\ndef Alert(request):\n dfp = pd.read_csv(\"core/rishu.csv\")\n df = pd.read_csv(\"core/rishuAlert2.csv\")\n if request.method == 'GET':\n view_state = request.GET.get('view_state')\n types = request.GET.get('types')\n view_percentage = request.GET.get('view_percentage')\n x = 1 - float(get_float(view_percentage)/100)\n print(\"Rishuuu\",x)\n # akp1 =True\n akp2 = True\n akp3 = True\n print(\"Available Field\",view_state)\n # (1) Condition for State , County and City\n if (view_state and view_percentage) is not None :\n akp1 = compute_county_wise_price(df, dfp, view_state, x);\n # print(df1)\n df1=dfp.loc[akp1, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",'types', 'status', 'created_at', 'updated_at']]\n\n else:\n df1 = dfp\n\n print(\"DF1\",df1)\n\n json_records = df1.reset_index().to_json(orient='records')\n data = []\n data = json.loads(json_records)\n page = request.GET.get('page', 1)\n paginator = Paginator(data, 500)\n\n try:\n users = paginator.page(page)\n except PageNotAnInteger:\n users = paginator.page(1)\n except EmptyPage:\n users = paginator.page(paginator.num_pages(10))\n\n\n return render(request, 'bootstrap_form.html', {'users': users})\n\n\ndef compute_county_wise_price(df1, df2, state, x):\n netprice_per_county = df1[df1['state'] == state]\n netprice_per_county = netprice_per_county.drop('state', axis=1)\n\n price_per_county = {county: price*x for county, price in netprice_per_county.items()}\n results = []\n\n for index, row in df2.iterrows():\n if ((row['state'] == state) and (price_per_county[row['county']] > row['Rate'])):\n results.append(True)\n else:\n results.append(False)\n return results\n\ndef show(request):\n df = pd.read_csv(\"core/rishu.csv\")\n if request.method == 'GET':\n title_contains_query = request.GET.get('title_contains')\n id_exact_query = request.GET.get('id_exact')\n title_or_author_query = request.GET.get('title_or_author')\n view_count_min = request.GET.get('view_count_min')\n view_count_max = request.GET.get('view_count_max')\n date_min = request.GET.get('date_min')\n date_max = request.GET.get('date_max')\n Udate_min = request.GET.get('date_min2')\n Udate_max = request.GET.get('date_max2')\n view_acres = request.GET.get('view_acres')\n status = request.GET.get('status')\n title2_contains_query = request.GET.get('title2_contains')\n view_state = request.GET.get('view_state')\n types = request.GET.get('types')\n view_percentage = request.GET.get('view_percentage')\n akp1 = df['state']== 'Anji'\n # akp1 =True\n akp2 = True\n akp3 = True\n print(\"Available Field\",title_contains_query)\n # (1) Condition for State , County and City\n if title_contains_query is not None :\n akp1 = (df['state'] == title_contains_query ) | (df['city'] == title_contains_query) | (df['county'] == title_contains_query)\n # print(df1)\n df1=df.loc[akp1, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",'types', 'status', 'created_at', 'updated_at']]\n\n else:\n df1 =df\n\n print(\"DF1\",df1)\n # (2) Condition for Types\n if types is not None :\n akp2 = (df1['types'].str.contains(types , na=False))\n # akp2 = (df1['types'] == types)\n df2=df1.loc[akp2, [\"lwPropertyId\", 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",'types', 'status', 'created_at', 'updated_at']]\n\n else :\n df2 =df1\n\n print(\"DF2\",df2)\n\n # (3) Condition for Status\n if status is not \"\" :\n print(status)\n akp3 = (df2['status'] == status)\n # akp2 = (df1['status'] == types)\n df3 = df2.loc[akp3, [\"lwPropertyId\", 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",'types', 'status', 'created_at', 'updated_at']]\n else :\n df3 = df2\n print(\"DF3\",df3)\n\n # print(view_acres)\n # (4) Condition For Min Price :\n\n if view_count_min is not None :\n akp4 = df3['price'] >= get_float(view_count_min)\n df4 = df3.loc[akp4, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",\n 'types', 'status', 'created_at', 'updated_at']]\n else :\n df4 = df3\n print(\"DF4\",df4)\n\n # (5) Condition For Max Price :\n\n if view_count_max is \"100000\":\n print(\"word\",view_count_max)\n akp5 = df4['price'] <= get_float(view_count_max)\n df5 = df4.loc[\n akp5, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",\n 'types', 'status', 'created_at', 'updated_at']]\n else:\n print(\"Hello\",view_count_max)\n df5 = df4\n print(\"DF5\",df5)\n\n #(6) Condition for Area :\n\n if view_acres is not None :\n akp6 = df5['acres'] >= get_float(view_acres)\n df6 = df5.loc[akp6, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",\n 'types', 'status', 'created_at', 'updated_at']]\n # print(df5)\n else :\n df6 = df5\n print(\"DF6\",df6)\n\n # (7) Condition For Publish Date :\n\n if date_min is \"2000-01-01\" and date_max is \"2050-01-01\":\n print(\"RishuuuDAte\")\n print(date_min)\n print(date_max)\n akp7 = data_within_date(df6, date_min, date_max)\n df7 = df6.loc[akp7, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",'types', 'status', 'created_at', 'updated_at']]\n else:\n print(\"NA Date\",date_min)\n df7 = df6\n print(\"DF7\",df7)\n\n # (7) Condition For Update Date :\n\n if Udate_min is \"2000-01-01\" and Udate_max is \"2050-01-01\":\n akp8 = data_within_date(df7, Udate_min, Udate_max)\n df8 = df7.loc[\n akp8, ['lwPropertyId', 'address', 'city', 'state', 'county', 'zip', 'price', 'acres', \"Rate\", \"Url\",\n 'types', 'status', 'created_at', 'updated_at']]\n else:\n print(\"NA Date\", Udate_min)\n df8 = df7\n print(\"DF8\", df8)\n\n\n\n\n json_records = df7.reset_index().to_json(orient='records')\n data = []\n data = json.loads(json_records)\n page = request.GET.get('page', 1)\n paginator = Paginator(data, 5000)\n\n try:\n users = paginator.page(page)\n except PageNotAnInteger:\n users = paginator.page(1)\n except EmptyPage:\n users = paginator.page(paginator.num_pages(10))\n\n\n return render(request, 'bootstrap_form.html', {'users': users})\n\ndef get_float(s):\n ans_int = 0\n ans_float = 0\n divisor = 1\n\n int_part = s.split('.')[0]\n\n for d in int_part:\n ans_int = (ans_int * 10) + int(d)\n\n if (not s.find('.') == -1):\n\n float_part = s.split('.')[1]\n\n for d in float_part:\n ans_float = (ans_float * 10) + int(d)\n\n divisor = 10 ** len(float_part)\n\n ans = ans_int + (ans_float / divisor)\n\n return ans\n\ndef data_within_date(df, min_date, max_date):\n created_dates = [date.split()[0] for date in df['created_at']]\n min_d = datetime.strptime(min_date, '%Y-%m-%d')\n max_d = datetime.strptime(max_date, '%Y-%m-%d')\n results = []\n for date in created_dates:\n date = datetime.strptime(date, '%Y-%m-%d')\n if (date >= min_d and date <= max_d):\n results.append(True)\n else:\n results.append(False)\n return results\n\n\ndef login(request):\n print(\"Rishi\")\n rishu = request.POST.get('login_email')\n print(\"Rishu\",rishu)\n if rishu =='purchase@tayloredideas.com':\n print(\"Login Entry\")\n\n # user = User.objects.get(email__exact='usermail@example.com')\n # if (bcrypt.checkpw(request.POST['login_password'].encode('utf-8'), user.password.encode('utf-8'))):\n if (request.POST.get('login_password') == \"usa_texas_property_stuff\"):\n print(\"Sahi Hai\")\n # request.session['id'] = user.id\n return redirect('/show')\n return redirect('/')\n\ndef success(request):\n user = User.objects.get(id=request.session['id'])\n context = {\n \"user\": user\n }\n # job(request)\n\n return render(request, 'test111.html', context)\n\ndef set_password(self, pw):\n pwhash = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt())\n self.password_hash = pwhash.decode('utf8') # decode the hash to prevent is encoded twice\n\n\ndef is_valid_queryparam(param):\n return param != '' and param is not None\n\n\ndef filter(request):\n qs = PropertyMaster.objects.all()\n category = PropertyMaster.objects.all()\n title_contains_query = request.GET.get('title_contains')\n id_exact_query = request.GET.get('id_exact')\n title_or_author_query = request.GET.get('title_or_author')\n view_count_min = request.GET.get('view_count_min')\n view_count_max = request.GET.get('view_count_max')\n date_min = request.GET.get('date_min')\n date_max = request.GET.get('date_max')\n view_acres = request.GET.get('view_acres')\n category = request.GET.get('category')\n reviewed = request.GET.get('reviewed')\n not_reviewed = request.GET.get('notReviewed')\n\n if is_valid_queryparam(title_contains_query):\n qs = qs.filter(city__icontains=title_contains_query)\n\n elif is_valid_queryparam(id_exact_query):\n qs = qs.filter(id=id_exact_query)\n\n elif is_valid_queryparam(title_or_author_query):\n qs = qs.filter(Q(city__icontains=title_or_author_query)).distinct()\n # | Q(author__name__icontains=title_or_author_query)\n\n\n if is_valid_queryparam(view_count_min):\n qs = qs.filter(price__gte=view_count_min)\n\n if is_valid_queryparam(view_count_max):\n qs = qs.filter(price__lt=view_count_max+\"1\")\n\n if is_valid_queryparam(date_min):\n qs = qs.filter(publish_date__gte=date_min)\n\n if is_valid_queryparam(category) and category != 'Choose...':\n qs = qs.filter(price__name=category)\n\n if is_valid_queryparam(date_max):\n qs = qs.filter(publish_date__lt=date_max)\n\n if is_valid_queryparam(view_acres):\n qs = qs.filter(acres__gte=view_acres)\n #\n # if is_valid_queryparam(acres) :\n # qs = qs.filter(acres__values=acres)\n\n if reviewed == 'on':\n qs = qs.filter(reviewed=True)\n\n elif not_reviewed == 'on':\n qs = qs.filter(reviewed=False)\n\n return qs\n\n\ndef infinite_filter(request):\n limit = request.GET.get('limit')\n offset = request.GET.get('offset')\n return PropertyMaster.objects.all()[int(offset): int(offset) + int(limit)]\n\n\ndef is_there_more_data(request):\n offset = request.GET.get('offset')\n if int(offset) > PropertyMaster.objects.all().count():\n return False\n return True\n\n# class ReactFilterView(generics.ListAPIView):\n# serializer_class = JournalSerializer\n#\n# def get_queryset(self):\n# qs = filter(self.request)\n# return qs\n\n\n# class ReactInfiniteView(generics.ListAPIView):\n# serializer_class = JournalSerializer\n#\n# def get_queryset(self):\n# qs = infinite_filter(self.request)\n# return qs\n#\n# def list(self, request):\n# queryset = self.get_queryset()\n# serializer = self.serializer_class(queryset, many=True)\n# return Response({\n# \"journals\": serializer.data,\n# \"has_more\": is_there_more_data(request)\n# })\n\n\n\ndef logout_view(request):\n return render(request,'index2.html')\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"342867465","text":"\"\"\"\nEach ListNode holds a reference to its previous node\nas well as its next node in the List.\n\"\"\"\nclass ListNode:\n def __init__(self, value, prev=None, next=None):\n self.prev = prev\n self.value = value\n self.next = next\n\n def __str__(self):\n return f\"Value = {self.value}\"\n\n def get_value(self):\n return self.value\n\n def get_next(self):\n return self.next\n\n def set_next(self, new_next):\n self.next = new_next\n\n def get_prev(self):\n return self.prev\n\n def set_prev(self, new_prev):\n self.prev = new_prev\n\n def delete(self):\n if self.prev:\n self.prev.next = self.next\n if self.next:\n self.next.prev = self.prev\n \n\"\"\"\nOur doubly-linked list class. It holds references to \nthe list's head and tail nodes.\n\"\"\"\nclass DoublyLinkedList:\n def __init__(self, node=None):\n self.head = node\n self.tail = node\n self.length = 1 if node is not None else 0\n\n def __str__(self):\n output = \"\"\n if self.head is None:\n return \"There are no any nodes\"\n current_node = self.head\n\n while current_node:\n output += f\"\\n{current_node.get_value()}\"\n current_node = current_node.get_next()\n return output\n\n def __len__(self):\n return self.length\n \n \"\"\"\n Wraps the given value in a ListNode and inserts it \n as the new head of the list. Don't forget to handle \n the old head node's previous pointer accordingly.\n \"\"\"\n def add_to_head(self, value):\n new_node = ListNode(value)\n self.length +=1\n #check if linked list is empty\n if self.head is None:\n self.head = new_node\n self.tail = new_node\n else:\n #new_node should point ot current head\n new_node.set_next(self.head)\n self.head.set_prev(new_node)\n #move head to new node\n self.head = new_node \n \n \"\"\"\n Removes the List's current head node, making the\n current head's next node the new head of the List.\n Returns the value of the removed Node.\n \"\"\"\n def remove_from_head(self):\n if self.head is None:\n return None\n # self.length -=1\n head_value = self.head.get_value()\n # if self.head.get_next() is None:\n # self.head = None\n # self.tail = None\n # return head_value\n\n # self.head = self.head.get_next()\n # self.head.set_prev(None) \n self.delete(self.head)\n return head_value\n \n \n \"\"\"\n Wraps the given value in a ListNode and inserts it \n as the new tail of the list. Don't forget to handle \n the old tail node's next pointer accordingly.\n \"\"\"\n def add_to_tail(self, value):\n new_node = ListNode(value)\n self.length +=1\n if not self.head :\n self.head = new_node\n self.tail = new_node\n else:\n new_node.set_prev(self.tail)\n self.tail.set_next(new_node)\n self.tail = new_node\n \n \"\"\"\n Removes the List's current tail node, making the \n current tail's previous node the new tail of the List.\n Returns the value of the removed Node.\n \"\"\"\n def remove_from_tail(self):\n if not self.head:\n return None\n # self.length -=1\n tail_value = self.tail.get_value()\n # if self.head is self.tail:\n # self.head = None \n # self.tail = None\n # return tail_value\n \n\n # self.tail = self.tail.get_prev()\n # self.tail.set_next(None)\n self.delete(self.tail)\n return tail_value\n \n \"\"\"\n Removes the input node from its current spot in the \n List and inserts it as the new head node of the List.\n \"\"\"\n def move_to_front(self, node):\n if node is None or self.head is None or self.head is node:\n return \n node_value = node.get_value()\n # if node is self.tail:\n # self.remove_from_tail()\n \n # else:\n # if node.get_prev():\n # node.prev.set_next(node.get_next())\n # if node.get_next():\n # node.next.set_prev(node.get_prev())\n # self.length -=1\n self.delete(node)\n self.add_to_head(node_value)\n\n\n \n \"\"\"\n Removes the input node from its current spot in the \n List and inserts it as the new tail node of the List.\n \"\"\"\n def move_to_end(self, node):\n if node is None or self.head is None or self.tail is node:\n return \n node_value = node.get_value()\n # if node is self.head:\n # self.remove_from_head()\n \n # else:\n # if node.get_prev():\n # node.prev.set_next(node.get_next())\n # if node.get_next():\n # node.next.set_prev(node.get_prev())\n # self.length -=1\n self.delete(node)\n self.add_to_tail(node_value)\n\n \"\"\"\n Deletes the input node from the List, preserving the \n order of the other elements of the List.\n \"\"\"\n def delete(self, node):\n if node is None or self.head is None:\n return\n self.length -= 1\n if self.head is self.tail and node is self.head:\n self.head = None\n self.tail = None\n elif node is self.head:\n self.head = self.head.get_next()\n self.head.set_prev(None) \n elif node == self.tail:\n self.tail = self.tail.get_prev()\n self.tail.set_next(None)\n\n else:\n node.delete()\n # node.prev.set_next(node.get_next())\n # node.next.set_prev(node.get_prev())\n\n\n \n \n\n \"\"\"\n Finds and returns the maximum value of all the nodes \n in the List.\n \"\"\"\n def get_max(self):\n if self.head is None:\n return None\n max_value = self.head.get_value()\n current_node = self.head.get_next()\n while current_node:\n if max_value < current_node.get_value():\n max_value = current_node.get_value()\n current_node = current_node.get_next()\n return max_value\n \n \n\ndoubly_linked_list = DoublyLinkedList()\ndoubly_linked_list.add_to_head(1)\nprint(\"length = \", doubly_linked_list.length)\ndoubly_linked_list.add_to_head(2)\ndoubly_linked_list.add_to_head(3)\ndoubly_linked_list.remove_from_head()\ndoubly_linked_list.remove_from_head()\ndoubly_linked_list.remove_from_head()\nprint(doubly_linked_list)\n\n\n","sub_path":"doubly_linked_list/doubly_linked_list.py","file_name":"doubly_linked_list.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"79400433","text":"# -*- coding: utf-8 -*-\n#\n# Telefónica Digital - Product Development and Innovation\n#\n# THIS CODE AND INFORMATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n#\n# Copyright (c) Telefónica Investigación y Desarrollo S.A.U.\n# All rights reserved.\n#\n\"\"\"Routes mapping\"\"\"\n\nimport re\nfrom urlparse import urlparse\n\nPATH_PATTERN = re.compile('(?:/[^/]+)*/v(\\d+)/?')\n\n\nclass Routes(object):\n \"\"\"Resource URLs factory\"\"\"\n\n def __init__(self, base_url):\n \"\"\"Initializes a Routes object and pre-computes fixed resources.\n\n >>> instance = Routes('http://foo/base/v1')\n >>> instance.storage\n 'http://foo/base/v1/storage'\n >>> instance.profile\n 'http://foo/base/v1/profile'\n >>> instance.api_version\n 1\n\n Base urls must include a version tag or a ValueError is raised.\n\n >>> Routes('http://foo/unversioned')\n Traceback (most recent call last):\n ...\n ValueError: Base API url has not version tag: \"http://foo/unversioned\"\n \"\"\"\n self.__set_base_url(base_url)\n self.info = self.base_url + \"/info\"\n self.storage = self.base_url + \"/storage\"\n self.profile = self.base_url + \"/profile\"\n self.services = self.base_url + \"/services\"\n\n def clusters(self):\n \"\"\"Construct the clusters resource URL.\n\n >>> Routes('http://foo/base/v1').clusters()\n 'http://foo/base/v1/cluster'\n \"\"\"\n return \"%s/cluster\" % (self.base_url)\n\n def cluster(self, cluster_id, action=None):\n \"\"\"Construct a cluster resource URL.\n\n >>> Routes('http://foo/base/v1').cluster('37')\n 'http://foo/base/v1/cluster/37'\n\n If you need to perform a concrete action use the optional argument action:\n\n >>> Routes('http://foo/base/v1').cluster('37', action=\"terminate\")\n 'http://foo/base/v1/cluster/37/terminate'\n \"\"\"\n parts = [self.clusters(), cluster_id]\n if action:\n parts.append(action)\n return \"/\".join(parts)\n\n def __set_base_url(self, url):\n parts = urlparse(url)\n match = PATH_PATTERN.match(parts.path)\n if not match:\n raise ValueError('Base API url has not version tag: \"%s\"' % url)\n self.base_url = url if not url.endswith('/') else url[:-1]\n self.api_version = int(match.group(1))\n","sub_path":"cosmos-cli/cosmos/common/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"561350711","text":"import numpy\nfrom pyparsing import CaselessLiteral, Combine, Forward, Literal, Optional, Word, ZeroOrMore, alphas, nums\n\nfrom django.contrib.gis.gdal import GDALRaster\n\nfrom .const import ALGEBRA_PIXEL_TYPE_GDAL, ALGEBRA_PIXEL_TYPE_NUMPY\n\n\nclass FormulaParser(object):\n \"\"\"\n Deconstruct mathematical algebra expressions and convert those into\n callable funcitons.\n\n Adopted from: http://pyparsing.wikispaces.com/file/view/fourFn.py\n \"\"\"\n expr_stack = []\n\n # The data dictionary holds the values on which to evaluate the formula\n data = {}\n\n # Map operator symbols to arithmetic operations in numpy\n opn = {\n \"+\": numpy.add,\n \"-\": numpy.subtract,\n \"*\": numpy.multiply,\n \"/\": numpy.divide,\n \"^\": numpy.power,\n \"==\": numpy.equal,\n \"!=\": numpy.not_equal,\n \">\": numpy.greater,\n \">=\": numpy.greater_equal,\n \"<\": numpy.less,\n \"<=\": numpy.less_equal,\n \"|\": numpy.logical_or,\n \"&\": numpy.logical_and\n }\n\n # Map function names to python functions\n fn = {\n \"sin\": numpy.sin,\n \"cos\": numpy.cos,\n \"tan\": numpy.tan,\n \"log\": numpy.log,\n \"exp\": numpy.exp,\n \"abs\": numpy.abs,\n \"int\": numpy.int,\n \"round\": numpy.round,\n \"sign\": numpy.sign,\n }\n\n def __init__(self):\n \"\"\"\n Setup the Backus Normal Form (BNF) parser logic.\n \"\"\"\n self.dtype=ALGEBRA_PIXEL_TYPE_NUMPY\n point = Literal(\".\")\n\n e = CaselessLiteral(\"E\")\n\n fnumber = Combine(\n Word(\"+-\" + nums, nums) +\n Optional(point + Optional(Word(nums))) +\n Optional(e + Word(\"+-\" + nums, nums))\n )\n\n ident = Word(alphas, alphas + nums + \"_$\")\n\n # Operators\n plus = Literal(\"+\")\n minus = Literal(\"-\")\n mult = Literal(\"*\")\n div = Literal(\"/\")\n eq = Literal(\"==\")\n neq = Literal(\"!=\")\n lt = Literal(\"<\")\n le = Literal(\"<=\")\n gt = Literal(\">\")\n ge = Literal(\">=\")\n ior = Literal(\"|\")\n iand = Literal(\"&\")\n lpar = Literal(\"(\").suppress()\n rpar = Literal(\")\").suppress()\n addop = plus | minus | eq\n multop = mult | div | eq | neq | ge | le | gt | lt | ior | iand # Order matters here due to \"<=\" being caught by \"<\"\n expop = Literal(\"^\")\n pi = CaselessLiteral(\"PI\")\n\n # Letters for variables\n aa = CaselessLiteral(\"a\")\n bb = CaselessLiteral(\"b\")\n cc = CaselessLiteral(\"c\")\n dd = CaselessLiteral(\"d\")\n ee = CaselessLiteral(\"e\")\n ff = CaselessLiteral(\"f\")\n gg = CaselessLiteral(\"g\")\n hh = CaselessLiteral(\"h\")\n ii = CaselessLiteral(\"i\")\n jj = CaselessLiteral(\"j\")\n kk = CaselessLiteral(\"k\")\n ll = CaselessLiteral(\"l\")\n mm = CaselessLiteral(\"m\")\n nn = CaselessLiteral(\"n\")\n oo = CaselessLiteral(\"o\")\n pp = CaselessLiteral(\"p\")\n qq = CaselessLiteral(\"q\")\n rr = CaselessLiteral(\"r\")\n ss = CaselessLiteral(\"s\")\n tt = CaselessLiteral(\"t\")\n uu = CaselessLiteral(\"u\")\n vv = CaselessLiteral(\"v\")\n ww = CaselessLiteral(\"w\")\n xx = CaselessLiteral(\"x\")\n yy = CaselessLiteral(\"y\")\n zz = CaselessLiteral(\"z\")\n\n bnf = Forward()\n\n atom = (\n Optional('-') + Optional(\"!\") + (\n pi | e | fnumber | ident + lpar + bnf + rpar | # pi needs to be before the letters for it to be found\n aa | bb | cc | dd | ee | ff | gg | hh | ii | jj | kk | ll | mm |\n nn | oo | pp | qq | rr | ss | tt | uu | vv | ww | xx | yy | zz\n ).setParseAction(self.push_first) | (lpar + bnf.suppress() + rpar)\n ).setParseAction(self.push_unary_operator)\n\n # By defining exponentiation as \"atom [ ^ factor ]...\" instead of \"atom [ ^ atom ]...\",\n # we get right-to-left exponents, instead of left-to-righ\n # that is, 2^3^2 = 2^(3^2), not (2^3)^2.\n factor = Forward()\n factor << atom + ZeroOrMore((expop + factor).setParseAction(self.push_first))\n\n term = factor + ZeroOrMore((multop + factor).setParseAction(self.push_first))\n bnf << term + ZeroOrMore((addop + term).setParseAction(self.push_first))\n\n self.bnf = bnf\n\n def push_first(self, strg, loc, toks):\n self.expr_stack.append(toks[0])\n\n def push_unary_operator(self, strg, loc, toks):\n \"\"\"\n Sets custom flag for unary operators.\n \"\"\"\n if toks:\n if toks[0] == '-':\n self.expr_stack.append('unary -')\n elif toks[0] == '!':\n self.expr_stack.append('unary !')\n\n def evaluate_stack(self, stack):\n \"\"\"\n Evaluate a stack element.\n \"\"\"\n # Get operator element\n op = stack.pop()\n\n # Evaluate unary operators\n if op == 'unary -':\n return -self.evaluate_stack(stack)\n if op == 'unary !':\n return numpy.logical_not(self.evaluate_stack(stack))\n\n # Evaluate binary operators\n if op in [\"+\", \"-\", \"*\", \"/\", \"^\", \">\", \"<\", \"==\", \"!=\", \"<=\", \">=\", \"|\", \"&\", \"!\"]:\n op2 = self.evaluate_stack(stack)\n op1 = self.evaluate_stack(stack)\n return self.opn[op](op1, op2)\n elif op == \"PI\":\n return numpy.pi\n elif op == \"E\":\n return numpy.e\n elif op in self.fn:\n return self.fn[op](self.evaluate_stack(stack))\n elif op[0].isalpha() and len(op[0]) == 1 and op[0] in self.data:\n return self.data[op[0]]\n elif op[0].isalpha() and len(op[0]) == 1:\n raise Exception('Found an undeclared variable in formula.')\n else:\n # If numeric, convert to numpy float\n return numpy.array(op, dtype=self.dtype)\n\n def parse_formula(self, formula):\n \"\"\"\n Parse a string formula into a BNF expression.\n \"\"\"\n # Clean formula before parsing\n formula = self.clean_formula(formula)\n\n # Reset expression stack\n self.expr_stack = []\n\n # Use bnf to parse the string\n self.bnf.parseString(formula)\n\n def clean_formula(self, formula):\n \"\"\"\n Remove any white space and line breaks from formula.\n \"\"\"\n return formula.replace(' ', '').replace('\\n', '').replace('\\r', '')\n\n def evaluate(self, data=None):\n \"\"\"\n Evaluate the input data using the current formula expression stack.\n \"\"\"\n # Make sure a formula has been parsed before evaluating\n if self.expr_stack == []:\n raise Exception('Please specify a formula to evaluate.')\n\n # Update dataset\n if data:\n self.data = data\n\n # Evaluate stack on data\n self.result = self.evaluate_stack(self.expr_stack)\n\n return self.result\n\n def evaluate_formula(self, formula, data={}, dtype=ALGEBRA_PIXEL_TYPE_NUMPY):\n \"\"\"\n Helper function to set formula and evaluate in one call.\n \"\"\"\n self.dtype = dtype\n self.parse_formula(formula)\n return self.evaluate(data)\n\n\nclass RasterAlgebraParser(FormulaParser):\n \"\"\"\n Compute raster algebra expressions using the FormulaParser class.\n \"\"\"\n\n def evaluate_raster_algebra(self, data, formula, check_aligned=False):\n \"\"\"\n Evaluate a raster algebra expression on a set of rasters. All input\n rasters need to be strictly aligned (same size, geotransform and srid).\n\n The input raster list will be zipped into a dictionary using the input\n names. The resulting dictionary will be used as input data for formula\n evaluation. If the check_aligned flag is set, the input rasters are\n compared to make sure they are aligned.\n \"\"\"\n # Check that all input rasters are aligned\n if check_aligned:\n self.check_aligned(list(data.values()))\n\n # Construct list of numpy arrays holding raster pixel data\n data_arrays = {\n key: numpy.ma.masked_values(rast.bands[0].data().ravel(), rast.bands[0].nodata_value)\n for key, rast in data.items()\n }\n\n # Evaluate formula on raster data\n result = self.evaluate_formula(formula, data_arrays)\n\n # Reference first original raster for constructing result\n orig = list(data.values())[0]\n orig_band = orig.bands[0]\n\n # Convert to default number type\n result = result.astype(ALGEBRA_PIXEL_TYPE_NUMPY)\n\n # Return GDALRaster holding results\n return GDALRaster({\n 'datatype': ALGEBRA_PIXEL_TYPE_GDAL,\n 'driver': 'MEM',\n 'width': orig.width,\n 'height': orig.height,\n 'nr_of_bands': 1,\n 'srid': orig.srs.srid,\n 'origin': orig.origin,\n 'scale': orig.scale,\n 'skew': orig.skew,\n 'bands': [{\n 'nodata_value': orig_band.nodata_value,\n 'data': result\n }],\n })\n\n def check_aligned(self, rasters):\n \"\"\"\n Assert that all input rasters are properly aligned.\n \"\"\"\n if not len(set([x.srs.srid for x in rasters])) == 1:\n raise Exception('Raster aligment check failed: SRIDs not all the same')\n\n gt = rasters[0].geotransform\n if any([gt != rast.geotransform for rast in rasters[1:]]):\n raise Exception('Raster aligment check failed: geotransform arrays are not all the same')\n","sub_path":"raster/formulas.py","file_name":"formulas.py","file_ext":"py","file_size_in_byte":9578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"454051621","text":"import unittest\n\nfrom Grid import Grid\n\n\nclass TestGrid(unittest.TestCase):\n def test_add_state(self):\n grid = Grid()\n grid.set_sigma([\"a\", \"b\"])\n with self.assertRaises(ValueError):\n grid.add_state([\"1\", \"1\", \"2\", \"3\"])\n grid.add_state([\"1\", \"1\"])\n self.assertTrue(grid.add_state([\"0\", \"1\", \"2\"]))\n self.assertTrue(grid.has_state(\"0\"))\n self.assertFalse(grid.has_state(\"1\"))\n self.assertEqual(grid.get_states(), [\"0\"])\n\n def test_set_sigma(self):\n grid = Grid()\n with self.assertRaises(TypeError):\n grid.set_sigma([\"a\", \"b\"])\n with self.assertRaises(ValueError):\n grid.set_sigma([\"a\", \"a\"])\n grid.set_sigma([\"a\", \"b\", \"c\"])\n self.assertEqual(grid.get_sigma_length(), 3)\n self.assertEqual(grid.get_sigma(), [\"a\", \"b\", \"c\"])\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"TestGrid.py","file_name":"TestGrid.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"268054484","text":"import socket\r\nimport sys\r\nimport os\r\nimport subprocess\r\n\r\nglobal option\r\ndef main():\r\n\tprint(\" \")\r\n\tprint(\" SHELLPY Remote Shell Application \")\r\n\tprint(\" \")\r\n\tprint(\" ###################################\")\r\n\tprint(\" [1]: Connect\")\r\n\tprint(\" [2]: About\")\r\n\tprint(\" [3]: Quit\")\r\n\tprint(\" ###################################\")\r\n\tprint(\" \")\r\n\toption = input(\" > \")\r\n\toptions(option)\r\n\r\ndef options(a):\r\n\tif a=='1':\r\n\t\tconnectserv()\r\n\telif a=='2':\r\n\t\tprint(\"SHELLPY ( ABOUT US ) \\n\\n\")\r\n\t\tprint(\"ShellPy is a standalone program capable of sharing your terminal and all it’s features with other desktop. In addition to this terminal service sharing, the application is completely transparent to user.\\n\\nA reverse shell works by the remote computer sending its shell to a specific user.This allows root commands over the remote server.\\n\\nTo use this reverse shell, two scripts need to be running:\\n\\t[*]Server.py - runs on a public server and waits for clients to connect.\\n\\t[*]Client.py - connects to a remote server and then wait for commands \")\r\n\t\tinput()\r\n\telif a=='3':\r\n\t\texit()\r\n\telse:\r\n\t\tprint(\"Try Again\")\r\n\r\n\r\ndef connectserv():\r\n socket_create()\r\n socket_bind()\r\n socket_accept()\r\n\r\n# Create socket (allows two computers to connect)\r\ndef socket_create():\r\n try:\r\n global host\r\n global port\r\n global s\r\n host = ''\r\n port = 9999\r\n s = socket.socket()\r\n except socket.error as msg:\r\n print(\"Socket creation error: \" + str(msg))\r\n\r\n\r\n# Bind socket to port (the host and port the communication will take place) and wait for connection from client\r\ndef socket_bind():\r\n try:\r\n global host\r\n global port\r\n global s\r\n print(\"Binding socket to port: \" + str(port))\r\n s.bind((host, port))\r\n s.listen(5)\r\n except socket.error as msg:\r\n print(\"Socket binding error: \" + str(msg) + \"\\n\" + \"Retrying...\")\r\n socket_bind()\r\n\r\n\r\n# Establish connection with client (socket must be listening for them)\r\ndef socket_accept():\r\n conn, address = s.accept()\r\n print(\"Connection has been established | \" + \"IP \" + address[0] + \" | Port \" + str(address[1]))\r\n send_commands(conn)\r\n conn.close()\r\n\r\n\r\n# Send commands\r\ndef send_commands(conn):\r\n while True:\r\n cmd = input()\r\n if cmd == 'quit':\r\n conn.close()\r\n s.close()\r\n sys.exit()\r\n if len(str.encode(cmd)) > 0:\r\n conn.send(str.encode(cmd))\r\n client_response = str(conn.recv(1024), \"utf-8\")\r\n print(client_response, end=\"\")\r\n\r\n\r\n\t\r\nmain()\r\n","sub_path":"ShellPy.py","file_name":"ShellPy.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"524231635","text":"a, b, c = map(int, input().split())\n\nif a == b == c:\n answer = 10000 + a * 1000\nelif a == b:\n answer = 1000 + a * 100\nelif b == c:\n answer = 1000 + b * 100\nelif c == a:\n answer = 1000 + c * 100\nelse:\n m = max([a, b, c])\n answer = m * 100\n\nprint(answer)\n","sub_path":"solved/three_dice.py","file_name":"three_dice.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"278798510","text":"import socket\nfrom multiprocessing import Process\nimport time\nimport os\nimport sys\nimport logging\nfrom pathlib import Path\n\nHOST = 'localhost'\nPORT = 60000\nDEBUG = True\n\ndef main():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.bind((HOST, PORT))\n s.listen(5)\n except Exception as e:\n logging.critical(f'Lesten {HOST}:{PORT} failed: {e}')\n sys.exit(1)\n logging.info('服务器socket设置完成:{}:{}'.format(HOST, PORT))\n\n try:\n while True:\n time.sleep(0.01)\n # 接受请求\n connection, address = s.accept()\n logging.info(\"接收到新连接,客户端 {}:{}\".format(address[0], address[1]))\n \n # 开一个新进程处理请求\n p = Process(target=echo_server, args=(connection, address))\n p.start()\n\n connection.close()\n finally:\n s.close()\n\n# echo服务器处理代码\ndef echo_server(conn, addr):\n logging.info('进入echo服务器, 客户端 {}:{}, pid: {}'.format(addr[0], addr[1], os.getpid()))\n while True:\n buf = conn.recv(1024)\n # 如果buf是eof,则退出\n if not buf:\n break\n else:\n command = buf.decode('utf-8')\n logging.debug('接收到客户端 {}:{} 内容:{}'.format(addr[0], addr[1], command))\n if command.split()[0].lower() == 'put':\n logging.debug(f'收到一个put请求: {command}')\n server_put(command, conn)\n elif command.split()[0].lower() == 'get':\n logging.debug(f'收到一个get请求: {command}')\n server_get(command, conn)\n else:\n conn.sendall(buf)\n logging.debug('发送到客户端 {}:{} 内容:{}'.format(addr[0], addr[1], command))\n conn.close()\n logging.info('客户端退出, 客户端 {}:{}, pid: {}'.format(addr[0], addr[1], os.getpid()))\n\ndef server_put(command, conn):\n # 检查put命令是否是3个参数,如果不是,发送错误回应,并返回\n if len(command.split()) != 4:\n conn.sendall(\"Error: 错误的命令,正确命令应该为 put source_file [None|target_dir|target_file] size.\".encode('utf-8'))\n else:\n _, src_file, target_file, file_size = command.split()\n filename = Path(src_file).name\n # 如果没有指定目标目录,则为当前目录下的recv目录\n if target_file == 'None':\n target_p = Path(__file__).resolve().parent.joinpath('recv', filename)\n else:\n if target_file[-1] == '/':\n target_p = Path(target_file).joinpath(filename)\n else:\n target_p = Path(target_file)\n if target_p.is_dir():\n target_p = target_p.joinpath(filename)\n \n # 取出目录和文件名\n target_dir = target_p.parent\n filename = target_p.name\n try:\n target_dir.mkdir(parents=True, exist_ok=True)\n with open(target_p, 'wb') as f:\n pass\n except Exception as e:\n logging.critical('Error: {}'.format(e))\n conn.sendall('Error: {}'.format(e).encode('utf-8'))\n return \n \n logging.debug('文件名: {}, 目标目录:{}'.format(filename, target_dir))\n # 一切正常,则向客户端返回OK\n conn.sendall(b'OK: Server is ready to recieve file.')\n try:\n with open(target_p, 'wb') as f:\n r_size = 0\n while r_size < int(file_size):\n buf = conn.recv(1024)\n r_size += len(buf)\n print(buf.decode('utf-8'))\n if not buf:\n break\n else:\n f.write(buf)\n except Exception as e:\n conn.sendall(b'Error: Server side error occured {}'.format(e))\n logging.critical('Error: {}'.format(e))\n return\n # 向客户端发送成功的msg\n conn.sendall('Succeed!')\n logging.debug('接受文件完成,{},文件大小:{}'.format(target_p, file_size))\n\ndef server_get(command, conn):\n elements = command.split()\n if len(elements) != 3:\n conn.sendall('Error: 参数数量错误'.encode('utf-8'))\n else:\n src_file = elements[1]\n src_p = Path(src_file)\n if not src_p.is_file():\n conn.sendall('Error: 文件没有找到'.encode('utf-8'))\n else:\n try:\n with open(src_p, 'rb') as f:\n pass\n except Exception as e:\n conn.sendall('Error: 读取文件错误'.encode('utf-8'))\n return\n conn.sendall('OK {}'.format(src_p.stat().st_size).encode('utf-8'))\n response = conn.recv(1024)\n if response.decode('utf-8').startswith('OK'):\n # 开始传输文件\n try:\n with open(src_p, 'rb') as f:\n while True:\n file_data = f.read(1024)\n if not file_data:\n break\n conn.sendall(file_data)\n except Exception as e:\n logging.critical('Error: 发送文件时候出错: {}'.format(e))\n logging.info('发送文件{}成功'.format(src_p))\n response = conn.recv(1024)\n logging.debug('从客户端收到: {}'.format(response.decode('utf-8')))\n\n# 启动守护进程\ndef daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):\n try:\n # 创建新进程\n pid = os.fork()\n\n # 父进程退出\n if pid > 0:\n sys.exit(0)\n except OSError as err:\n sys.stderr.write('_Fork #1 failed: {}\\n'.format(err))\n sys.exit(1)\n \n # 从父进程环境脱离\n # chdir确认进程不占用任何目录,否则不能umount\n os.chdir('/')\n os.umask(0)\n os.setsid()\n\n # 第二次fork\n try:\n pid = os.fork()\n\n if pid > 0:\n # 第二个父进程退出\n sys.exit(0)\n except OSError as err:\n sys.stderr.write('_Fork #2 failed: {}\\n'.format(err))\n sys.exit(1)\n\n # 重定向标准文件描述符\n sys.stdout.flush()\n sys.stderr.flush()\n\n si = open(stdin, 'r')\n so = open(stdout, 'a+')\n se = open(stderr, 'w')\n\n # dup2函数原子化关闭和复制文件描述符\n os.dup2(si.fileno(), sys.stdin.fileno())\n os.dup2(so.fileno(), sys.stdout.fileno())\n os.dup2(se.fileno(), sys.stderr.fileno())\n logging.info('守护进程初始化完成,当前进程号: {}'.format(os.getpid()))\n\ndef config_logging():\n loglevel = logging.DEBUG\n if DEBUG:\n logfile = '/dev/stdout'\n else:\n logfile = Path(__file__).parent.joinpath('echo_server.log')\n logging.basicConfig(filename=logfile,\n level=loglevel,\n datefmt='%Y-%m-%d %X',\n format='%(asctime)s %(levelname)-8s %(message)s')\n logging.info('logging配置完成')\n\nif __name__ == '__main__':\n config_logging()\n if not DEBUG:\n daemonize()\n main()\n","sub_path":"week02/echo_server.py","file_name":"echo_server.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"606239158","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.dates as mdates\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\n#指定行のcsvデータの取得\ndef Input():\n datas = pd.read_csv('stock/date.csv', header=None, index_col=0, usecols=[0])\n \n return datas\n\n\n#日付データの取得\nx=Input()\nprint(x)\nprint(x.dtyeps)\n\n# 横軸:日付 periods分の日付を用意します。\n\n\n# 縦軸:数値\ny = [130, 141, 142, 143, 171, 230, 231, 260, 276, 297]\nprint(y)\nprint(y.dtypes)\n\nax.plot(x,y)\n\n# 日付ラベルフォーマットを修正\ndays = mdates.DayLocator() \ndaysFmt = mdates.DateFormatter('%m-%d')\nax.xaxis.set_major_locator(days)\nax.xaxis.set_major_formatter(daysFmt)\n\n# グラフの表示\nplt.show()","sub_path":"stock/day_test.py","file_name":"day_test.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"176778093","text":"# You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.\n#\n# Return the maximum score you can get by erasing exactly one subarray.\n#\n# An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).\n#\n# \n# Example 1:\n#\n#\n# Input: nums = [4,2,4,5,6]\n# Output: 17\n# Explanation: The optimal subarray here is [2,4,5,6].\n#\n#\n# Example 2:\n#\n#\n# Input: nums = [5,2,1,2,5,2,1,2,5]\n# Output: 8\n# Explanation: The optimal subarray here is [5,2,1] or [1,2,5].\n#\n#\n# \n# Constraints:\n#\n#\n# \t1 <= nums.length <= 105\n# \t1 <= nums[i] <= 104\n#\n#\n\n\nclass Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n cnt = defaultdict(int)\n ans = 0\n i, j = 0, 0\n \n prefix = [0]\n for v in nums:\n prefix.append(prefix[-1] + v)\n \n while i < len(nums):\n while i < len(nums):\n if cnt[nums[i]] >= 1:\n break\n cnt[nums[i]] += 1\n i += 1\n if (i == len(nums)):\n ans = max(ans, prefix[-1] - prefix[j])\n break\n ans = max(ans, prefix[i] - prefix[j])\n while j < len(nums):\n cnt[nums[j]] -= 1\n j += 1\n if cnt[nums[i]] < 1:\n break\n return ans \n \n","sub_path":"solutions/1813-maximum-erasure-value/maximum-erasure-value.py","file_name":"maximum-erasure-value.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"627429255","text":"'''\n@Time : 2019/8/19 12:04\n@Author : mjh\n@File : adaboost.py\n'''\n\nimport math\n\nclass AdaBoost():\n def __init__(self, M=5):\n '''初始化参数'''\n self.weights = None #数据权值分布\n self.M = M #训练轮数\n self.alpha = [] #分类器权值\n self.feature = [] #选择的特征\n self.dump = [] #分类器规则\n\n def fit(self, Xdata, Ydata):\n #模型训练\n self.weights = [1/len(Xdata) for i in range(0, len(Xdata))]\n for iter in range(0, self.M):\n self.__getdump(Xdata, Ydata)\n\n def predict(self, Xdata):\n #预测数据\n result = []\n for iter1 in range(0, len(Xdata)):\n predict = 0\n for iter2 in range(0, self.M):\n predict += self.alpha[iter2]*self.dump[iter2](Xdata[iter1][self.feature[iter2]])\n if predict >= 0:\n result.append(1)\n else:\n result.append(-1)\n return result\n\n def __getdump(self, X, Y):\n #在一个特征上确定一个决策树桩\n minerror = float(\"inf\")\n dump = None\n feature = None\n for iter1 in range(0, len(X[0])): #遍历每一个特征\n for iter2 in range(0, len(X)): #遍历每一个分类点\n func1 = lambda x: 1 if x >= X[iter2][iter1] else -1\n func2 = lambda x: -1 if x >= X[iter2][iter1] else 1\n error1 = 0; error2 = 0\n for i in range(0, len(X)):\n if func1(X[i][iter1]) != Y[i]:\n error1 += self.weights[i]\n if func2(X[i][iter1]) != Y[i]:\n error2 += self.weights[i]\n\n if error1 < error2:\n if error1 < minerror:\n minerror = error1\n a = X[iter2][iter1]\n dump = lambda x: 1 if x >= a else -1\n feature = iter1\n else:\n if error2 < minerror:\n minerror = error2\n a = X[iter2][iter1]\n dump = lambda x: -1 if x >= a else 1\n feature = iter1\n\n if minerror < float(\"inf\"):\n self.dump.append(dump) #添加分类规则\n self.feature.append(feature)\n if minerror != 0:\n alpha = 0.5*math.log((1-minerror)/minerror)\n else:\n alpha = 1\n self.alpha.append(alpha)\n\n total = 0 #更新数据权重\n for i in range(0, len(self.weights)):\n self.weights[i] = self.weights[i]*math.exp(-1*alpha*Y[i]*dump(X[i][feature]))\n total += self.weights[i]\n self.weights = [self.weights[i] / total for i in range(0, len(self.weights))]\n\nif __name__==\"__main__\":\n x = [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]\n y = [1, 1, 1, -1, -1, -1, 1, 1, 1, -1]\n\n x2 = [[0, 1, 3], [0, 3, 1], [1, 2, 2], [1, 1, 3], [1, 2, 3], [0, 1, 2], [1, 1, 2], [1, 1, 1], [1, 3, 1], [0, 2, 1]]\n y2 = [-1, -1, -1, -1, -1, -1, 1, 1, -1, -1]\n\n ada = AdaBoost(10)\n ada.fit(x2, y2)\n result = ada.predict(x2)\n print(result)","sub_path":"code/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"627409799","text":"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#MMMR=[(thetai,ri,xi,yi,xpi,ypi)]\r\n\r\n\r\nimport copy\r\nfrom zonesafe import *\r\nN=720\r\nlidar=[]\r\nrv=20\r\nm=5\r\ni=0\r\nr=50\r\n\r\nwhile i 0:\n\t\t\t\turl = \"{}guonei/list_{}.html\".format(self.start_urls[0], page)\n\t\t\t\tif page == 1:\n\t\t\t\t\turl = \"{}guonei/\".format(self.start_urls[0])\n\t\t\t\tyield scrapy.Request(url, callback=self.parsePage)\n\n\n\tdef parsePage(self, response):\n\t\tdivs = response.xpath(\"\"\"//div[@id=\"infinite_scroll\"]/div\"\"\")\n\t\tfor d in divs:\n\t\t\titem = ForumDuanzibarComItem()\n\t\t\ttitle = d.xpath(\"\"\"./div[@class=\"item_b clearfix\"]/div[@class=\"title\"]/span/a/text()\"\"\").extract_first()\n\t\t\tarticle_url = \"{}{}\".format(self.start_urls[0], d.xpath(\"\"\"./div[@class=\"item_b clearfix\"]/div[@class=\"title\"]/span/a/@href\"\"\").extract_first())\n\t\t\tthumbnail_src = d.xpath(\"\"\"./div[@class=\"item_t\"]/div[@class=\"img\"]/a/img/@data-original\"\"\").extract_first()\n\t\t\titem['fid'] = self.fid\n\t\t\titem['response_url'] = response.url\n\t\t\titem['title'] = title\n\t\t\titem['categories'] = self.categories\n\t\t\titem['image_urls'] = []\n\t\t\titem['thumbnail_url'] = thumbnail_src\n\t\t\titem['image_urls'].append(item['thumbnail_url'])\n\t\t\titem['content_url'] = article_url\n\t\t\titem['contents'] = []\n\t\t\tyield scrapy.Request(item['content_url'], meta={'item': item}, callback=self.parseContent)\n\n\n\tdef parseContent(self, response):\n\t\titem = response.meta['item']\n\t\timages = response.xpath(\"\"\"//div[@id=\"big-pic\"]/p/a\"\"\")\n\t\tfor img in images:\n\t\t\timage = img.xpath(\"\"\"./img/@src\"\"\").extract_first()\n\t\t\tif image:\n\t\t\t\titem['contents'].append(image)\n\t\t\t\tif image not in item['image_urls']:\n\t\t\t\t\titem['image_urls'].append(image)\n\t\tnxt = response.xpath(\"\"\"//div[@class=\"pages\"]/ul/li/a[contains(text(), \"下一页\")]/@href\"\"\").extract_first()\n\t\tif nxt:\n\t\t\tyield scrapy.Request(\"{}{}\".format(self.start_urls[0], nxt), meta={'item': item}, callback=self.parseContent)\n\t\telse:\n\t\t\tyield item","sub_path":"forum_duanzibar_com/forum_duanzibar_com/spiders/www_aitaotu_com_guonei.py","file_name":"www_aitaotu_com_guonei.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"233732054","text":"#!/usr/bin/python3\n\"\"\"\nTask 0: N queens\n\"\"\"\n\nimport sys\n\n\ndef canMove(final, row, column):\n \"\"\"\n Checks if the queen would be able to move\n \"\"\"\n rows = []\n columns = []\n top_left = []\n top_right = []\n\n for nums in final:\n rows.append(nums[0])\n columns.append(nums[1])\n top_left.append(nums[1] - nums[0])\n top_right.append(nums[0] + nums[1])\n\n if row in rows or column in columns:\n return False\n if column - row in top_left or row + column in top_right:\n return False\n\n return True\n\n\ndef nqueens(final, column, checked_queens=[]):\n \"\"\"\n The main recursive program\n \"\"\"\n for item in range(n):\n if canMove(final, item, column):\n final.append([item, column])\n if column == n - 1:\n checked_queens.append(final.copy())\n del final[-1]\n else:\n nqueens(final, column + 1)\n\n if len(final) > 0:\n del final[-1]\n return checked_queens\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n\n try:\n n = int(sys.argv[1])\n except:\n print(\"N must be a number\")\n sys.exit(1)\n\n if n < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\n\n final = []\n final = nqueens(final, 0)\n\n for nums in final:\n print(nums)\n","sub_path":"0x0C-nqueens/0-nqueens.py","file_name":"0-nqueens.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"384008392","text":"import time \nimport requests \nfrom plyer import notification \ncovidData = None\ntry:\n covidData = requests.get(\"https://corona-rest-api.herokuapp.com/Api/india\")\nexcept:\n print(\"Please! Check your internet connection\")\nif (covidData != None):\n data = covidData.json()['Success'] \n while(True):\n notification.notify(\n title = \"COVID-19 Stats in India\",\n message = \"Total cases reported : {totalcases}\\nCases reported today : {todaycases}\\nDeaths reported : {todaydeaths}\\nTotal active cases : {active}\".format(\n totalcases = data['cases'],\n todaycases = data['todayCases'],\n todaydeaths = data['todayDeaths'],\n active = data[\"active\"]),\n app_icon = \"coronavirus.ico\",\n timeout = 100\n )\n time.sleep(60*60*4)\n","sub_path":"covi-notifier.py","file_name":"covi-notifier.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}
+{"seq_id":"579925558","text":"import discord\r\nfrom discord.ext.commands import Bot\r\nfrom discord.ext import commands\r\nfrom discord.utils import get\r\nfrom google.oauth2 import service_account\r\nfrom google.cloud import texttospeech\r\nfrom google.cloud import translate\r\nimport googleapiclient.discovery\r\nimport googleapiclient.errors\r\nimport spotipy\r\nfrom spotipy.oauth2 import SpotifyClientCredentials\r\nfrom cleverbot_aio_free.cbaio import CleverBot\r\nimport asyncio\r\nimport os, sys, pathlib\r\nimport signal\r\nimport youtube_dl\r\nimport aiohttp\r\nimport requests\r\nfrom random import randint \r\nimport datetime\r\n\r\nfrom auth import DISCORD_API_KEY, GOOGLE_API_KEY, GIPHY_API_KEY, X_RAPID_API_KEY, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET\r\n\r\nmax_quotes = 0\r\ntts_count = 0\r\n\r\n\r\nreaction_dict = [\"zitto_babbano\" ,\"yo_simon\" ,\"yo_mattia\", \"yes_david\", \"wtf\", \"valeria_messina\", \"u_kiddin_paolo\", \"the_doctor\", \"steveboty\", \"SI\", \"se_sei_forte\", \"sblowjobbed\", \"sad_simon\", \"rom_luke\", \"rich_laurence\", \"razor\", \"qt_vale\", \"potato_john\", \"old_xono\", \"oh_yes\", \"nica\", \"metauomometacanna\", \"mart_189\", \"mad_approved\", \"luca_maestro\", \"lorenzo_drugs\", \"lorenzo_approved\", \"lorenzo\", \"hungry_simon\", \"giuseppe_ritardato\", \"ghostrick_face\", \"francicec_trolling\", \"eugene_got_hacked\", \"drunk_si\", \"doubting_giuanni\", \"ciccied\", \"bored_luke\", \"armando\", \"aok\", \"andrea\", \"and_the_cops_silent\" ]\r\nwords_list = [\"porc\",\"dio\",\"madonn\",\"padre\",\"crist\",\"stefano\", \"giuseppe\", \"giovanni\", \"valerio\", \"simone\", \"carlo\", \"andrea\", \"lorenzo\"]\r\n\r\nGOOGLE_TTS_CLIENT_SECRET = os.path.join(\"auth\",\"tts_client_secret_youtify.json\") \r\n\r\nFILE_INSULTI = os.path.join(\"random\",\"insulti.txt\") \r\n\r\nsongs_url_queue = asyncio.Queue()\r\nsongs_names_queue = asyncio.Queue()\r\ntts_queue = asyncio.Queue()\r\n\r\ntts_cred = service_account.Credentials.from_service_account_file(GOOGLE_TTS_CLIENT_SECRET)\r\n\r\nbot = commands.Bot(command_prefix=\"!\")\r\n\r\ncb = CleverBot()\r\n\r\nbot_voice_status = 0\r\ntts_status = 0\r\nplaylist_status = 0\r\nchat_status = 0\r\n\r\n@bot.command(pass_context=True)\r\nasync def commands(ctx):\r\n await bot.say(\"List of available commands: !song - !playlist - !tts - !tr + - !llist - !spotify - !ripeti - !quote - !insulta - !reaction - !gif - !udict \")\r\n\r\nasync def smoke_timer(): \r\n now = datetime.datetime.now()\r\n if int(now.hour) == 16 and int(now.minute) == 20 and int(now.second) == 0: \r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), \"<:420:580109657746702336>\")\r\n\r\n\r\n\r\n@bot.command(pass_context=True)\r\nasync def st3ve(ctx, *, content:str):\r\n global cb\r\n global chat_status\r\n if chat_status == 0:\r\n chat_status = 1\r\n await cb.init()\r\n\r\n \r\n if str(content).lower().find(\"addio\") != -1 and chat_status == 1:\r\n chat_status = 0\r\n await cb.close()\r\n await bot.say(\"Alla prossima ;)\")\r\n return\r\n \r\n response = await cb.getResponse(str(content))\r\n await bot.say(str(response))\r\n\r\n@bot.command(pass_context=True)\r\nasync def tts(ctx, *, content:str):\r\n global bot_voice_status\r\n global tts_count\r\n global tts_status\r\n author = ctx.message.author\r\n if(str(author).find(\"St3veB0T\") == -1):\r\n client = texttospeech.TextToSpeechClient()\r\n synthesis_input = texttospeech.types.SynthesisInput(text=content)\r\n voice = texttospeech.types.VoiceSelectionParams(language_code='it-IT',ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)\r\n audio_config = texttospeech.types.AudioConfig(audio_encoding=texttospeech.enums.AudioEncoding.MP3)\r\n response = client.synthesize_speech(synthesis_input, voice, audio_config)\r\n tts_count = tts_count + 1\r\n with open((os.path.join(\"tts\",\"record\"+str(tts_count)+\".mp3\") ), \"wb\") as out:\r\n out.write(response.audio_content)\r\n out.close()\r\n await tts_queue.put(\"record\"+str(tts_count)+\".mp3\")\r\n server = discord.Server(id=\"139354435989143553\")\r\n author = ctx.message.author\r\n if(bot_voice_status == 0):\r\n bot_voice_status = 1\r\n tts_status = 1\r\n while(tts_queue.qsize() > 0 and bot_voice_status == 1):\r\n voice_channel = author.voice_channel\r\n global vc\r\n if tts_queue.qsize() == 1:\r\n try:\r\n vc = await bot.join_voice_channel(voice_channel)\r\n except:\r\n pass\r\n\r\n global player\r\n try:\r\n player = vc.create_ffmpeg_player((os.path.join(\"tts\",str(await tts_queue.get()))))\r\n except:\r\n player.stop()\r\n await vc.disconnect()\r\n bot_voice_status = 0\r\n tts_status = 0\r\n return\r\n\r\n player.start()\r\n\r\n while not player.is_done():\r\n await asyncio.sleep(1)\r\n \r\n sec = 75\r\n while(sec and tts_status == 1):\r\n await asyncio.sleep(1)\r\n if tts_queue.qsize() > 0:\r\n try:\r\n player = vc.create_ffmpeg_player((os.path.join(\"tts\",str(await tts_queue.get()))))\r\n except:\r\n player.stop()\r\n await vc.disconnect()\r\n bot_voice_status = 0\r\n tts_status = 0\r\n return\r\n\r\n player.start()\r\n\r\n while not player.is_done():\r\n await asyncio.sleep(1)\r\n sec = sec - 1\r\n if tts_status == 1:\r\n player.stop()\r\n await vc.disconnect()\r\n bot_voice_status = 0\r\n tts_status = 0\r\n for filename in os.listdir(\"tts\"):\r\n os.remove((os.path.join(\"tts\",filename)))\r\n\r\n@bot.command(pass_context=True)\r\nasync def spotify(ctx, *, content:str):\r\n if(str(ctx.message.author).find(\"St3veB0T\") == -1):\r\n client_credentials_manager = SpotifyClientCredentials(client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET) \r\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\r\n \r\n try:\r\n res = sp.search(q=content, type=\"track\") \r\n await bot.say(res[\"tracks\"][\"items\"][0][\"external_urls\"][\"spotify\"])\r\n except:\r\n await bot.say(\"Can't find that song...\")\r\n \r\n \r\nasync def is_Available_Language(language):\r\n client = translate.Client()\r\n languages = client.get_languages()\r\n for item in languages:\r\n if str(item[\"language\"]).find(language) != -1:\r\n return True\r\n return False\r\n\r\nasync def isUser_in_last_message(ctx, name):\r\n async for message in bot.logs_from(ctx.message.channel, limit=100):\r\n if str(message.author).find(str(name)) != -1:\r\n return True\r\n return False\r\n\r\n\r\nasync def Get_Nlines_File_Insulti():\r\n c = 0\r\n with open(FILE_INSULTI) as fp:\r\n for line in fp:\r\n c = c + 1\r\n fp.close()\r\n return c\r\n\r\ndef Save_Message_to_File(message):\r\n try:\r\n fp = open(\"random/phrase.txt\", \"a+\", encoding=\"utf-8\")\r\n except:\r\n fp = open(\"random/phrase.txt\", \"x\", encoding=\"utf-8\")\r\n fp.close()\r\n fp = open(\"random/phrase.txt\", \"a+\", encoding=\"utf-8\")\r\n fp.seek(0)\r\n for line in fp:\r\n if line.find(message) != -1:\r\n return\r\n fp.seek(2)\r\n fp.write(str(message.encode(\"utf-8\").decode(\"utf-8\")))\r\n fp.write(\"\\n\")\r\n fp.close()\r\n\r\nasync def Translate(ctx, args=None, language=\"en\", user=None):\r\n client = translate.Client()\r\n if args == None and user != None:\r\n async for message in bot.logs_from(ctx.message.channel, limit=50):\r\n if str(user).find(message.author) != -1:\r\n data = client.translate(message.content, target_language=language)\r\n await bot.send_message(ctx.message.channel, str(data[\"translatedText\"]))\r\n return\r\n await bot.send_message(ctx.message.channel, \"Wrong Username - Maybe use @\")\r\n return\r\n else:\r\n data = client.translate(args, target_language=language)\r\n await bot.send_message(ctx.message.channel, str(data[\"translatedText\"]))\r\n\r\nasync def Pick_Random_Phrase():\r\n \r\n while(1):\r\n try:\r\n fp = open(\"random/phrase.txt\", \"r\", encoding=\"utf-8\")\r\n except:\r\n fp = open(\"random/phrase.txt\", \"x\", encoding=\"utf-8\")\r\n fp.close()\r\n fp = open(\"random/phrase.txt\", \"r\", encoding=\"utf-8\")\r\n\r\n rand_sleep_time = randint(3600, 5400)\r\n await asyncio.sleep(rand_sleep_time)\r\n lines = 0\r\n fp.seek(0)\r\n for line in fp:\r\n lines += 1\r\n fp.seek(0)\r\n rand = randint(0, lines-1)\r\n c = 0\r\n for phrase in fp:\r\n if c == rand:\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), str(phrase))\r\n c = c + 1\r\n\r\n fp.close()\r\n\r\nasync def Get_Streamer_Event():\r\n status_dict = {\"st3ver0nix\":0, \"angelthelion\": 0, \"stereophonics\":0, \"madbulk22\":0, \"zarkent\":0, \"unluckyrazor\":0, \"vajinvegeta1996\":0}\r\n streamer_dict = {\"st3ver0nix\": \"https://www.twitch.tv/st3ver0nix\", \"angelthelion\":\"https://www.twitch.tv/angelthelion\", \"stereophonics\": \"https://www.twitch.tv/stereophonics\", \"madbulk22\":\"https://www.twitch.tv/madbulk22\", \"zarkent\":\"https://www.twitch.tv/zarkent\", \"unluckyrazor\":\"https://www.twitch.tv/unluckyrazor\", \"vajinvegeta1996\":\"https://www.twitch.tv/vajinvegeta1996\"} \r\n header = {\"Content-Type\": \"text/plain\",\"Accept\": \"application/json\", \"Connection \" : \"close\"}\r\n \r\n while(1):\r\n async with aiohttp.ClientSession() as session: \r\n for name in streamer_dict:\r\n await smoke_timer()\r\n await asyncio.sleep(1) \r\n url = \"http://decapi.me/twitch/uptime?channel=\" + str(name)\r\n async with session.get(url, headers = header) as res:\r\n if(str(await res.text()).find(\"hour\") != -1 or str(await res.text()).find(\"minute\") != -1 or str(await res.text()).find(\"second\") != -1):\r\n if status_dict[name] == 0:\r\n message = \"@everyone Hey, \" + str(name) + \" è online su twitch! \" + str(streamer_dict[name])\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), str(message))\r\n status_dict[name] = 1\r\n else:\r\n if str(await res.text()).find(\"offline\") != -1:\r\n status_dict[name] = 0\r\n\r\nasync def Birthdays():\r\n actual_year = int(datetime.datetime.today().year)\r\n actual_month = int(datetime.datetime.today().month)\r\n actual_day = int(datetime.datetime.today().day)\r\n \r\n if actual_day == 23 and actual_month == 3:\r\n message = \"Auguri Tullio, per i tuoi \" + str(actual_year - 1996 ) + \" anni!\"\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), message)\r\n if actual_day == 9 and actual_month == 4:\r\n message = \"Auguri Carlo, per i tuoi \" + str(actual_year - 1996 ) + \" anni!\"\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), message)\r\n if actual_day == 27 and actual_month == 4:\r\n message = \"Auguri Valerio, per i tuoi \" + str(actual_year - 1997 ) + \" anni!\"\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), message)\r\n \r\n@bot.event \r\nasync def on_ready():\r\n print(\"Bot Ready\")\r\n loop = asyncio.get_event_loop()\r\n task1 = loop.create_task(Get_Streamer_Event())\r\n task2 = loop.create_task(Pick_Random_Phrase())\r\n await bot.send_message(bot.get_channel(id=\"327424537211830273\"), \"Ciao amici, sono online!\") \r\n await Birthdays()\r\n await task1\r\n await task2 \r\n \r\n@bot.event\r\nasync def on_message(message):\r\n print(str(message.author)+\":\"+str(message.content))\r\n if(str(message.author).find(\"St3veB0T\") == -1):\r\n mess = str(message.content).lower()\r\n for word in words_list:\r\n if str(mess).find(word) != -1 and str(mess).find(\"\\n\") == -1 and str(mess).startswith(\"!\") == False:\r\n Save_Message_to_File(message.content) \r\n # await bot.send_message(message.channel, str(message.content))\r\n break\r\n\r\n if str(message.author).find(\"St3veB0T\") == -1:\r\n if(str(message.content).find(\"<@547054033270079508>\") != -1 or str(message.content).find(\"St3veB0T\") != -1):\r\n with open(FILE_INSULTI) as fp:\r\n lines = await Get_Nlines_File_Insulti()\r\n random = randint(0, lines)\r\n c = 0\r\n for line in fp:\r\n if c == random:\r\n mess = \"||\" + (line.replace(\"$\", str(message.author))) + \"||\"\r\n await bot.send_message(message.channel, mess.encode(\"windows-1252\").decode(\"utf-8\"))\r\n fp.close()\r\n return\r\n c = c + 1 \r\n await bot.process_commands(message)\r\n\r\n@bot.event\r\nasync def on_voice_state_update(before, after):\r\n global bot_voice_status\r\n global tts_status\r\n if(bot_voice_status == 0 and tts_status == 0 and after.display_name.find(\"St3veB0T\") == -1):\r\n if(before.voice_channel == None): \r\n rand = randint(0, len(os.listdir(\"audio\"))-1) \r\n ix = 0\r\n for filename in os.listdir(\"audio\"):\r\n if(ix == rand): \r\n c = 0\r\n try:\r\n vc = await bot.join_voice_channel(after.voice_channel)\r\n c = 1\r\n except:\r\n break\r\n if(c == 1):\r\n try:\r\n player = vc.create_ffmpeg_player((os.path.join(\"audio\",filename) ), after=lambda: print(''))\r\n player.start()\r\n while not player.is_done():\r\n await asyncio.sleep(1)\r\n player.stop()\r\n await vc.disconnect()\r\n break\r\n except:\r\n await vc.disconnect()\r\n break\r\n ix = ix + 1\r\n\"\"\"\r\n@bot.event\r\nasync def on_member_update(before, after):\r\n if(str(before.status).find(\"offline\") != -1 and str(after.status).find(\"online\") != -1):\r\n for role in after.roles:\r\n if str(role).find(\"AHK Member\") != -1:\r\n if(str(after.display_name) != \"\" and str(after.display_name).find(\"St3veB0T\") == -1):\r\n message = \"Ehy, \" + str(after.display_name) + \" è online!\"\r\n await bot.send_message(bot.get_channel(id=\"139354435989143553\"), message)\r\n\"\"\"\r\n@bot.command(pass_context=True)\r\nasync def llist(ctx):\r\n client = translate.Client()\r\n lang = client.get_languages()\r\n string = \"List of available languages with their id: \"\r\n for item in lang:\r\n string += (str(item[\"name\"]) + \":\" + str(item[\"language\"]) + \" | \")\r\n await bot.say(string)\r\n\r\n\r\n@bot.command(pass_context=True)\r\nasync def tr(ctx, *, content:str):\r\n try:\r\n splitted_content = content.split(\" \")\r\n except:\r\n await bot.say(\"Usage: !tr